From 9e639c1cb6abd5ffed0f9017de26f93d2ee99eac Mon Sep 17 00:00:00 2001 From: Chasel Chiu Date: Fri, 25 Oct 2019 15:46:19 +0800 Subject: [PATCH 001/384] IntelFsp2Pkg/SplitFspBin.py: Command crashed when FV almost full. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2310 When target FV 99% used and only few bytes space left, SplitFspBin.py may crash with below error: File "SplitFspBin.py", line 457, in ParseFv ffshdr = EFI_FFS_FILE_HEADER.from_buffer (self.FvData, offset) ValueError: Buffer size too small (40960 instead of at least 40968 bytes) It was because the offset used by FFS_HEADER parser out of bounds. It should stop parsing when offset equal or larger than (buffer size - FFS_HEADER size). This patch also fixed another crash issue when running script with Python 3.x and no input parameter given: File "SplitFspBin.py", line 868, in main if args.which in ['rebase', 'split', 'genhdr', 'info']: AttributeError: 'Namespace' object has no attribute 'which' Test: 1. Ran script with both py2 and py3 with no input and no crash observed. 2. Compare the script result before and after the patch are identical. Cc: Maurice Ma Cc: Nate DeSimone Cc: Star Zeng Signed-off-by: Chasel Chiu Reviewed-by: Nate DeSimone --- IntelFsp2Pkg/Tools/SplitFspBin.py | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/IntelFsp2Pkg/Tools/SplitFspBin.py b/IntelFsp2Pkg/Tools/SplitFspBin.py index b326241fa9d..39a7ea7460b 100644 --- a/IntelFsp2Pkg/Tools/SplitFspBin.py +++ b/IntelFsp2Pkg/Tools/SplitFspBin.py @@ -428,7 +428,7 @@ def ParseFfs(self): ffssize = len(self.FfsData) offset = sizeof(self.FfsHdr) if self.FfsHdr.Name != '\xff' * 16: - while offset < ffssize: + while offset < (ffssize - sizeof (EFI_COMMON_SECTION_HEADER)): sechdr = EFI_COMMON_SECTION_HEADER.from_buffer (self.FfsData, offset) sec = Section (offset, self.FfsData[offset:offset + int(sechdr.Size)]) self.SecList.append(sec) @@ -453,7 +453,7 @@ def ParseFv(self): else: offset = self.FvHdr.HeaderLength offset = AlignPtr(offset) - while offset < fvsize: + while offset < (fvsize - sizeof (EFI_FFS_FILE_HEADER)): ffshdr = EFI_FFS_FILE_HEADER.from_buffer (self.FvData, offset) if (ffshdr.Name == '\xff' * 16) and (int(ffshdr.Size) == 0xFFFFFF): offset = fvsize @@ -515,7 +515,7 @@ def ParseFd(self): offset = 0 fdsize = len(self.FdData) self.FvList = [] - while offset < fdsize: + while offset < (fdsize - sizeof (EFI_FIRMWARE_VOLUME_HEADER)): fvh = EFI_FIRMWARE_VOLUME_HEADER.from_buffer (self.FdData, offset) if b'_FVH' != fvh.Signature: raise Exception("ERROR: Invalid FV header !") @@ -838,7 +838,7 @@ def RebaseFspBin (FspBinary, FspComponent, FspBase, OutputDir, OutputFile): def main (): parser = argparse.ArgumentParser() - subparsers = parser.add_subparsers(title='commands') + subparsers = parser.add_subparsers(title='commands', dest="which") parser_rebase = subparsers.add_parser('rebase', help='rebase a FSP into a new base address') parser_rebase.set_defaults(which='rebase') @@ -880,7 +880,7 @@ def main (): elif args.which == 'info': ShowFspInfo (args.FspBinary) else: - pass + parser.print_help() return 0 From 4976a776b283021c252be794e90947732b6f8a92 Mon Sep 17 00:00:00 2001 From: Siyuan Fu Date: Thu, 24 Oct 2019 10:50:19 +0800 Subject: [PATCH 002/384] Maintainers.txt: Change NetworkPkg maintainer role. Change Siyuan Fu from Maintainer to Reviewer. Cc: Jiaxin Wu Signed-off-by: Siyuan Fu Reviewed-by: Jiaxin Wu --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index 6b89bec55e2..adc98118808 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -354,8 +354,8 @@ M: Liming Gao NetworkPkg F: NetworkPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg -M: Siyuan Fu M: Jiaxin Wu +R: Siyuan Fu OvmfPkg F: OvmfPkg/ From d4269c8e7c4d132f24bfc08bd723f81265154546 Mon Sep 17 00:00:00 2001 From: Julien Grall Date: Mon, 28 Oct 2019 10:34:06 +0000 Subject: [PATCH 003/384] Maintainers.txt: Update my e-mail address I will soon lose access to my Arm e-mail address. Update it to my xen.org one. Signed-off-by: Julien Grall Message-Id: <20191028103406.10253-1-julien.grall@arm.com> Acked-by: Anthony PERARD Reviewed-by: Laszlo Ersek --- Maintainers.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Maintainers.txt b/Maintainers.txt index adc98118808..71a34a28456 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -127,7 +127,7 @@ F: ArmVirtPkg/PrePi/ F: ArmVirtPkg/XenAcpiPlatformDxe/ F: ArmVirtPkg/XenPlatformHasAcpiDtDxe/ F: ArmVirtPkg/XenioFdtDxe/ -R: Julien Grall +R: Julien Grall BaseTools F: BaseTools/ @@ -396,7 +396,7 @@ F: OvmfPkg/XenPvBlkDxe/ F: OvmfPkg/XenResetVector/ F: OvmfPkg/XenTimerDxe/ R: Anthony Perard -R: Julien Grall +R: Julien Grall OvmfPkg: TCG- and TPM2-related modules F: OvmfPkg/Include/IndustryStandard/QemuTpm.h From 6f3ac73cd3792c7eeccb4533e545270d640bef4c Mon Sep 17 00:00:00 2001 From: "Siyuan, Fu" Date: Tue, 29 Oct 2019 09:41:10 +0800 Subject: [PATCH 004/384] NetworkPkg/SnpDxe: Use PcdGetBool() instead of FixedPcdGetBool in Snp.c This patch fixes a problem introduced by commit 61bb6eeb4d93c0a34c1995d87914ab41398f9550. The PcdSnpCreateExitBootServicesEvent is not guaranteed to be FixedAtBuild, so use PcdGetBool() to supports both fixed and patchable PCD. Cc: Jiaxin Wu Signed-off-by: Siyuan Fu Reviewed-by: Jiaxin Wu --- NetworkPkg/SnpDxe/Snp.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/NetworkPkg/SnpDxe/Snp.c b/NetworkPkg/SnpDxe/Snp.c index 9fb007f7aec..1099dbfa6a2 100644 --- a/NetworkPkg/SnpDxe/Snp.c +++ b/NetworkPkg/SnpDxe/Snp.c @@ -647,7 +647,7 @@ SimpleNetworkDriverStart ( PxeShutdown (Snp); PxeStop (Snp); - if (FixedPcdGetBool (PcdSnpCreateExitBootServicesEvent)) { + if (PcdGetBool (PcdSnpCreateExitBootServicesEvent)) { // // Create EXIT_BOOT_SERIVES Event // @@ -780,7 +780,7 @@ SimpleNetworkDriverStop ( return Status; } - if (FixedPcdGetBool (PcdSnpCreateExitBootServicesEvent)) { + if (PcdGetBool (PcdSnpCreateExitBootServicesEvent)) { // // Close EXIT_BOOT_SERIVES Event // From dc254af6a492d554efaba924c4903463a1d56f36 Mon Sep 17 00:00:00 2001 From: Maggie Chu Date: Fri, 25 Oct 2019 17:19:34 +0800 Subject: [PATCH 005/384] MdeModulePkg/NvmExpressPei: Fix Opal S3 unlock issue https://bugzilla.tianocore.org/show_bug.cgi?id=2312 This patch is for fixing unexpected system hang during S3 unlock process. FatPei driver maintained and updated internal BlockIo devices list when there is new BlockIo PPI has installed, and it relied on BlockIo PPI service to get data from devices. Because BlockIo Ppi leverage NvmExpressPei Ppi to transit Nvm command to device, we should make sure NvmePassThruPpi installed before BlockIo PPI. Signed-off-by: Maggie Chu Reviewed-by: Hao A Wu Cc: Jian J Wang Cc: Ray Ni Cc: Star Zeng Cc: Eric Dong --- .../Bus/Pci/NvmExpressPei/NvmExpressPei.c | 43 ++++++++++--------- 1 file changed, 23 insertions(+), 20 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c index 987eed420e2..a8cb7f3a675 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPei.c @@ -376,6 +376,29 @@ NvmExpressPeimEntry ( continue; } + // + // Nvm Express Pass Thru PPI + // + Private->PassThruMode.Attributes = EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | + EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL | + EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_CMD_SET_NVM; + Private->PassThruMode.IoAlign = sizeof (UINTN); + Private->PassThruMode.NvmeVersion = EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI_REVISION; + Private->NvmePassThruPpi.Mode = &Private->PassThruMode; + Private->NvmePassThruPpi.GetDevicePath = NvmePassThruGetDevicePath; + Private->NvmePassThruPpi.GetNextNameSpace = NvmePassThruGetNextNameSpace; + Private->NvmePassThruPpi.PassThru = NvmePassThru; + CopyMem ( + &Private->NvmePassThruPpiList, + &mNvmePassThruPpiListTemplate, + sizeof (EFI_PEI_PPI_DESCRIPTOR) + ); + Private->NvmePassThruPpiList.Ppi = &Private->NvmePassThruPpi; + PeiServicesInstallPpi (&Private->NvmePassThruPpiList); + + // + // Block Io PPI + // Private->BlkIoPpi.GetNumberOfBlockDevices = NvmeBlockIoPeimGetDeviceNo; Private->BlkIoPpi.GetBlockDeviceMediaInfo = NvmeBlockIoPeimGetMediaInfo; Private->BlkIoPpi.ReadBlocks = NvmeBlockIoPeimReadBlocks; @@ -398,26 +421,6 @@ NvmExpressPeimEntry ( Private->BlkIo2PpiList.Ppi = &Private->BlkIo2Ppi; PeiServicesInstallPpi (&Private->BlkIoPpiList); - // - // Nvm Express Pass Thru PPI - // - Private->PassThruMode.Attributes = EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_PHYSICAL | - EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_LOGICAL | - EFI_NVM_EXPRESS_PASS_THRU_ATTRIBUTES_CMD_SET_NVM; - Private->PassThruMode.IoAlign = sizeof (UINTN); - Private->PassThruMode.NvmeVersion = EDKII_PEI_NVM_EXPRESS_PASS_THRU_PPI_REVISION; - Private->NvmePassThruPpi.Mode = &Private->PassThruMode; - Private->NvmePassThruPpi.GetDevicePath = NvmePassThruGetDevicePath; - Private->NvmePassThruPpi.GetNextNameSpace = NvmePassThruGetNextNameSpace; - Private->NvmePassThruPpi.PassThru = NvmePassThru; - CopyMem ( - &Private->NvmePassThruPpiList, - &mNvmePassThruPpiListTemplate, - sizeof (EFI_PEI_PPI_DESCRIPTOR) - ); - Private->NvmePassThruPpiList.Ppi = &Private->NvmePassThruPpi; - PeiServicesInstallPpi (&Private->NvmePassThruPpiList); - // // Check if the NVME controller supports the Security Receive/Send commands // From 9f4fbd56d43054cc73d722c1643659f9741c0fcf Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 29 Oct 2019 15:43:11 +0000 Subject: [PATCH 006/384] CryptoPkg/OpensslLib: Update process_files.pl to generate .h files There are missing headers added into INF files at 8906f076de35b222a.. They are now manually added but not auto-generated. So we update the perl script to enable this feature. Meanwhile, update the order of the .h files in INF files, which are auto-generated now. https://bugzilla.tianocore.org/show_bug.cgi?id=2085 Cc: Jian J Wang Cc: Xiaoyu Lu Signed-off-by: Shenglei Zhang Reviewed-by: Jian J Wang Reviewed-by: Xiaoyu Lu --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 103 +++++++++--------- .../Library/OpensslLib/OpensslLibCrypto.inf | 96 ++++++++-------- CryptoPkg/Library/OpensslLib/process_files.pl | 28 +++++ 3 files changed, 129 insertions(+), 98 deletions(-) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index b40d82783b4..b28dd9e4800 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -34,9 +34,7 @@ $(OPENSSL_PATH)/crypto/aes/aes_misc.c $(OPENSSL_PATH)/crypto/aes/aes_ofb.c $(OPENSSL_PATH)/crypto/aes/aes_wrap.c - $(OPENSSL_PATH)/crypto/aes/aes_locl.h $(OPENSSL_PATH)/crypto/aria/aria.c - $(OPENSSL_PATH)/crypto/arm_arch.h $(OPENSSL_PATH)/crypto/asn1/a_bitstr.c $(OPENSSL_PATH)/crypto/asn1/a_d2i_fp.c $(OPENSSL_PATH)/crypto/asn1/a_digest.c @@ -101,21 +99,12 @@ $(OPENSSL_PATH)/crypto/asn1/x_sig.c $(OPENSSL_PATH)/crypto/asn1/x_spki.c $(OPENSSL_PATH)/crypto/asn1/x_val.c - $(OPENSSL_PATH)/crypto/asn1/standard_methods.h - $(OPENSSL_PATH)/crypto/asn1/charmap.h - $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h - $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h - $(OPENSSL_PATH)/crypto/asn1/asn1_locl.h $(OPENSSL_PATH)/crypto/async/arch/async_null.c $(OPENSSL_PATH)/crypto/async/arch/async_posix.c $(OPENSSL_PATH)/crypto/async/arch/async_win.c $(OPENSSL_PATH)/crypto/async/async.c $(OPENSSL_PATH)/crypto/async/async_err.c $(OPENSSL_PATH)/crypto/async/async_wait.c - $(OPENSSL_PATH)/crypto/async/arch/async_win.h - $(OPENSSL_PATH)/crypto/async/async_locl.h - $(OPENSSL_PATH)/crypto/async/arch/async_posix.h - $(OPENSSL_PATH)/crypto/async/arch/async_null.h $(OPENSSL_PATH)/crypto/bio/b_addr.c $(OPENSSL_PATH)/crypto/bio/b_dump.c $(OPENSSL_PATH)/crypto/bio/b_sock.c @@ -138,7 +127,6 @@ $(OPENSSL_PATH)/crypto/bio/bss_mem.c $(OPENSSL_PATH)/crypto/bio/bss_null.c $(OPENSSL_PATH)/crypto/bio/bss_sock.c - $(OPENSSL_PATH)/crypto/bio/bio_lcl.h $(OPENSSL_PATH)/crypto/bn/bn_add.c $(OPENSSL_PATH)/crypto/bn/bn_asm.c $(OPENSSL_PATH)/crypto/bn/bn_blind.c @@ -170,9 +158,6 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c - $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h - $(OPENSSL_PATH)/crypto/bn/bn_prime.h - $(OPENSSL_PATH)/crypto/bn/bn_lcl.h $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c @@ -181,7 +166,6 @@ $(OPENSSL_PATH)/crypto/comp/c_zlib.c $(OPENSSL_PATH)/crypto/comp/comp_err.c $(OPENSSL_PATH)/crypto/comp/comp_lib.c - $(OPENSSL_PATH)/crypto/comp/comp_lcl.h $(OPENSSL_PATH)/crypto/conf/conf_api.c $(OPENSSL_PATH)/crypto/conf/conf_def.c $(OPENSSL_PATH)/crypto/conf/conf_err.c @@ -190,8 +174,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_mod.c $(OPENSSL_PATH)/crypto/conf/conf_sap.c $(OPENSSL_PATH)/crypto/conf/conf_ssl.c - $(OPENSSL_PATH)/crypto/conf/conf_lcl.h - $(OPENSSL_PATH)/crypto/conf/conf_def.h $(OPENSSL_PATH)/crypto/cpt_err.c $(OPENSSL_PATH)/crypto/cryptlib.c $(OPENSSL_PATH)/crypto/ctype.c @@ -215,8 +197,6 @@ $(OPENSSL_PATH)/crypto/des/set_key.c $(OPENSSL_PATH)/crypto/des/str2key.c $(OPENSSL_PATH)/crypto/des/xcbc_enc.c - $(OPENSSL_PATH)/crypto/des/spr.h - $(OPENSSL_PATH)/crypto/des/des_locl.h $(OPENSSL_PATH)/crypto/dh/dh_ameth.c $(OPENSSL_PATH)/crypto/dh/dh_asn1.c $(OPENSSL_PATH)/crypto/dh/dh_check.c @@ -231,7 +211,6 @@ $(OPENSSL_PATH)/crypto/dh/dh_prn.c $(OPENSSL_PATH)/crypto/dh/dh_rfc5114.c $(OPENSSL_PATH)/crypto/dh/dh_rfc7919.c - $(OPENSSL_PATH)/crypto/dh/dh_locl.h $(OPENSSL_PATH)/crypto/dso/dso_dl.c $(OPENSSL_PATH)/crypto/dso/dso_dlfcn.c $(OPENSSL_PATH)/crypto/dso/dso_err.c @@ -239,7 +218,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_openssl.c $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c - $(OPENSSL_PATH)/crypto/dso/dso_locl.h $(OPENSSL_PATH)/crypto/ebcdic.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c @@ -304,13 +282,11 @@ $(OPENSSL_PATH)/crypto/evp/pmeth_fn.c $(OPENSSL_PATH)/crypto/evp/pmeth_gn.c $(OPENSSL_PATH)/crypto/evp/pmeth_lib.c - $(OPENSSL_PATH)/crypto/evp/evp_locl.h $(OPENSSL_PATH)/crypto/ex_data.c $(OPENSSL_PATH)/crypto/getenv.c $(OPENSSL_PATH)/crypto/hmac/hm_ameth.c $(OPENSSL_PATH)/crypto/hmac/hm_pmeth.c $(OPENSSL_PATH)/crypto/hmac/hmac.c - $(OPENSSL_PATH)/crypto/hmac/hmac_lcl.h $(OPENSSL_PATH)/crypto/init.c $(OPENSSL_PATH)/crypto/kdf/hkdf.c $(OPENSSL_PATH)/crypto/kdf/kdf_err.c @@ -318,13 +294,10 @@ $(OPENSSL_PATH)/crypto/kdf/tls1_prf.c $(OPENSSL_PATH)/crypto/lhash/lh_stats.c $(OPENSSL_PATH)/crypto/lhash/lhash.c - $(OPENSSL_PATH)/crypto/lhash/lhash_lcl.h $(OPENSSL_PATH)/crypto/md4/md4_dgst.c $(OPENSSL_PATH)/crypto/md4/md4_one.c - $(OPENSSL_PATH)/crypto/md4/md4_locl.h $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c - $(OPENSSL_PATH)/crypto/md5/md5_locl.h $(OPENSSL_PATH)/crypto/mem.c $(OPENSSL_PATH)/crypto/mem_clr.c $(OPENSSL_PATH)/crypto/mem_dbg.c @@ -339,7 +312,6 @@ $(OPENSSL_PATH)/crypto/modes/ofb128.c $(OPENSSL_PATH)/crypto/modes/wrap128.c $(OPENSSL_PATH)/crypto/modes/xts128.c - $(OPENSSL_PATH)/crypto/modes/modes_lcl.h $(OPENSSL_PATH)/crypto/o_dir.c $(OPENSSL_PATH)/crypto/o_fips.c $(OPENSSL_PATH)/crypto/o_fopen.c @@ -351,9 +323,6 @@ $(OPENSSL_PATH)/crypto/objects/obj_err.c $(OPENSSL_PATH)/crypto/objects/obj_lib.c $(OPENSSL_PATH)/crypto/objects/obj_xref.c - $(OPENSSL_PATH)/crypto/objects/obj_dat.h - $(OPENSSL_PATH)/crypto/objects/obj_xref.h - $(OPENSSL_PATH)/crypto/objects/obj_lcl.h $(OPENSSL_PATH)/crypto/ocsp/ocsp_asn.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_cl.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_err.c @@ -364,7 +333,6 @@ $(OPENSSL_PATH)/crypto/ocsp/ocsp_srv.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_vfy.c $(OPENSSL_PATH)/crypto/ocsp/v3_ocsp.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_lcl.h $(OPENSSL_PATH)/crypto/pem/pem_all.c $(OPENSSL_PATH)/crypto/pem/pem_err.c $(OPENSSL_PATH)/crypto/pem/pem_info.c @@ -392,7 +360,6 @@ $(OPENSSL_PATH)/crypto/pkcs12/p12_sbag.c $(OPENSSL_PATH)/crypto/pkcs12/p12_utl.c $(OPENSSL_PATH)/crypto/pkcs12/pk12err.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_lcl.h $(OPENSSL_PATH)/crypto/pkcs7/bio_pk7.c $(OPENSSL_PATH)/crypto/pkcs7/pk7_asn1.c $(OPENSSL_PATH)/crypto/pkcs7/pk7_attr.c @@ -401,7 +368,6 @@ $(OPENSSL_PATH)/crypto/pkcs7/pk7_mime.c $(OPENSSL_PATH)/crypto/pkcs7/pk7_smime.c $(OPENSSL_PATH)/crypto/pkcs7/pkcs7err.c - $(OPENSSL_PATH)/crypto/ppc_arch.h $(OPENSSL_PATH)/crypto/rand/drbg_ctr.c $(OPENSSL_PATH)/crypto/rand/drbg_lib.c $(OPENSSL_PATH)/crypto/rand/rand_egd.c @@ -410,10 +376,8 @@ $(OPENSSL_PATH)/crypto/rand/rand_unix.c $(OPENSSL_PATH)/crypto/rand/rand_vms.c $(OPENSSL_PATH)/crypto/rand/rand_win.c - $(OPENSSL_PATH)/crypto/rand/rand_lcl.h $(OPENSSL_PATH)/crypto/rc4/rc4_enc.c $(OPENSSL_PATH)/crypto/rc4/rc4_skey.c - $(OPENSSL_PATH)/crypto/rc4/rc4_locl.h $(OPENSSL_PATH)/crypto/rsa/rsa_ameth.c $(OPENSSL_PATH)/crypto/rsa/rsa_asn1.c $(OPENSSL_PATH)/crypto/rsa/rsa_chk.c @@ -436,24 +400,18 @@ $(OPENSSL_PATH)/crypto/rsa/rsa_ssl.c $(OPENSSL_PATH)/crypto/rsa/rsa_x931.c $(OPENSSL_PATH)/crypto/rsa/rsa_x931g.c - $(OPENSSL_PATH)/crypto/rsa/rsa_locl.h - $(OPENSSL_PATH)/crypto/s390x_arch.h $(OPENSSL_PATH)/crypto/sha/keccak1600.c $(OPENSSL_PATH)/crypto/sha/sha1_one.c $(OPENSSL_PATH)/crypto/sha/sha1dgst.c $(OPENSSL_PATH)/crypto/sha/sha256.c $(OPENSSL_PATH)/crypto/sha/sha512.c - $(OPENSSL_PATH)/crypto/sha/sha_locl.h $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/siphash/siphash_local.h $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c - $(OPENSSL_PATH)/crypto/sm3/sm3_locl.h $(OPENSSL_PATH)/crypto/sm4/sm4.c $(OPENSSL_PATH)/crypto/stack/stack.c - $(OPENSSL_PATH)/crypto/sparc_arch.h $(OPENSSL_PATH)/crypto/threads_none.c $(OPENSSL_PATH)/crypto/threads_pthread.c $(OPENSSL_PATH)/crypto/threads_win.c @@ -463,8 +421,6 @@ $(OPENSSL_PATH)/crypto/ui/ui_null.c $(OPENSSL_PATH)/crypto/ui/ui_openssl.c $(OPENSSL_PATH)/crypto/ui/ui_util.c - $(OPENSSL_PATH)/crypto/ui/ui_locl.h - $(OPENSSL_PATH)/crypto/vms_rms.h $(OPENSSL_PATH)/crypto/uid.c $(OPENSSL_PATH)/crypto/x509/by_dir.c $(OPENSSL_PATH)/crypto/x509/by_file.c @@ -502,7 +458,6 @@ $(OPENSSL_PATH)/crypto/x509/x_req.c $(OPENSSL_PATH)/crypto/x509/x_x509.c $(OPENSSL_PATH)/crypto/x509/x_x509a.c - $(OPENSSL_PATH)/crypto/x509/x509_lcl.h $(OPENSSL_PATH)/crypto/x509v3/pcy_cache.c $(OPENSSL_PATH)/crypto/x509v3/pcy_data.c $(OPENSSL_PATH)/crypto/x509v3/pcy_lib.c @@ -540,11 +495,57 @@ $(OPENSSL_PATH)/crypto/x509v3/v3_tlsf.c $(OPENSSL_PATH)/crypto/x509v3/v3_utl.c $(OPENSSL_PATH)/crypto/x509v3/v3err.c + $(OPENSSL_PATH)/crypto/hmac/hmac_lcl.h + $(OPENSSL_PATH)/crypto/dh/dh_locl.h + $(OPENSSL_PATH)/crypto/bio/bio_lcl.h + $(OPENSSL_PATH)/crypto/conf/conf_def.h + $(OPENSSL_PATH)/crypto/conf/conf_lcl.h + $(OPENSSL_PATH)/crypto/lhash/lhash_lcl.h + $(OPENSSL_PATH)/crypto/sha/sha_locl.h + $(OPENSSL_PATH)/crypto/md5/md5_locl.h + $(OPENSSL_PATH)/crypto/store/store_locl.h + $(OPENSSL_PATH)/crypto/dso/dso_locl.h + $(OPENSSL_PATH)/crypto/pkcs12/p12_lcl.h + $(OPENSSL_PATH)/crypto/arm_arch.h + $(OPENSSL_PATH)/crypto/mips_arch.h + $(OPENSSL_PATH)/crypto/ppc_arch.h + $(OPENSSL_PATH)/crypto/s390x_arch.h + $(OPENSSL_PATH)/crypto/sparc_arch.h + $(OPENSSL_PATH)/crypto/vms_rms.h + $(OPENSSL_PATH)/crypto/bn/bn_lcl.h + $(OPENSSL_PATH)/crypto/bn/bn_prime.h + $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h + $(OPENSSL_PATH)/crypto/ui/ui_locl.h + $(OPENSSL_PATH)/crypto/md4/md4_locl.h + $(OPENSSL_PATH)/crypto/rc4/rc4_locl.h + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h + $(OPENSSL_PATH)/crypto/asn1/asn1_locl.h + $(OPENSSL_PATH)/crypto/asn1/charmap.h + $(OPENSSL_PATH)/crypto/asn1/standard_methods.h + $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h + $(OPENSSL_PATH)/crypto/evp/evp_locl.h + $(OPENSSL_PATH)/crypto/rand/rand_lcl.h + $(OPENSSL_PATH)/crypto/ocsp/ocsp_lcl.h + $(OPENSSL_PATH)/crypto/modes/modes_lcl.h + $(OPENSSL_PATH)/crypto/comp/comp_lcl.h + $(OPENSSL_PATH)/crypto/rsa/rsa_locl.h + $(OPENSSL_PATH)/crypto/x509/x509_lcl.h + $(OPENSSL_PATH)/crypto/async/arch/async_null.h + $(OPENSSL_PATH)/crypto/async/arch/async_posix.h + $(OPENSSL_PATH)/crypto/async/arch/async_win.h + $(OPENSSL_PATH)/crypto/sm3/sm3_locl.h + $(OPENSSL_PATH)/crypto/des/des_locl.h + $(OPENSSL_PATH)/crypto/des/spr.h + $(OPENSSL_PATH)/crypto/siphash/siphash_local.h + $(OPENSSL_PATH)/crypto/aes/aes_locl.h + $(OPENSSL_PATH)/crypto/async/async_locl.h + $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h $(OPENSSL_PATH)/crypto/x509v3/pcy_int.h - $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h - $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h - $(OPENSSL_PATH)/ms/uplink.h + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h + $(OPENSSL_PATH)/crypto/objects/obj_dat.h + $(OPENSSL_PATH)/crypto/objects/obj_lcl.h + $(OPENSSL_PATH)/crypto/objects/obj_xref.h $(OPENSSL_PATH)/ssl/bio_ssl.c $(OPENSSL_PATH)/ssl/d1_lib.c $(OPENSSL_PATH)/ssl/d1_msg.c @@ -589,13 +590,13 @@ $(OPENSSL_PATH)/ssl/t1_trce.c $(OPENSSL_PATH)/ssl/tls13_enc.c $(OPENSSL_PATH)/ssl/tls_srp.c - $(OPENSSL_PATH)/ssl/record/record_locl.h $(OPENSSL_PATH)/ssl/statem/statem.h $(OPENSSL_PATH)/ssl/statem/statem_locl.h + $(OPENSSL_PATH)/ssl/packet_locl.h + $(OPENSSL_PATH)/ssl/ssl_cert_table.h $(OPENSSL_PATH)/ssl/ssl_locl.h $(OPENSSL_PATH)/ssl/record/record.h - $(OPENSSL_PATH)/ssl/ssl_cert_table.h - $(OPENSSL_PATH)/ssl/packet_locl.h + $(OPENSSL_PATH)/ssl/record/record_locl.h # Autogenerated files list ends here ossl_store.c diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index 0a60196c8a9..1b6ff5ed547 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -33,9 +33,7 @@ $(OPENSSL_PATH)/crypto/aes/aes_misc.c $(OPENSSL_PATH)/crypto/aes/aes_ofb.c $(OPENSSL_PATH)/crypto/aes/aes_wrap.c - $(OPENSSL_PATH)/crypto/aes/aes_locl.h $(OPENSSL_PATH)/crypto/aria/aria.c - $(OPENSSL_PATH)/crypto/arm_arch.h $(OPENSSL_PATH)/crypto/asn1/a_bitstr.c $(OPENSSL_PATH)/crypto/asn1/a_d2i_fp.c $(OPENSSL_PATH)/crypto/asn1/a_digest.c @@ -100,21 +98,12 @@ $(OPENSSL_PATH)/crypto/asn1/x_sig.c $(OPENSSL_PATH)/crypto/asn1/x_spki.c $(OPENSSL_PATH)/crypto/asn1/x_val.c - $(OPENSSL_PATH)/crypto/asn1/standard_methods.h - $(OPENSSL_PATH)/crypto/asn1/charmap.h - $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h - $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h - $(OPENSSL_PATH)/crypto/asn1/asn1_locl.h $(OPENSSL_PATH)/crypto/async/arch/async_null.c $(OPENSSL_PATH)/crypto/async/arch/async_posix.c $(OPENSSL_PATH)/crypto/async/arch/async_win.c - $(OPENSSL_PATH)/crypto/async/arch/async_posix.h - $(OPENSSL_PATH)/crypto/async/arch/async_null.h - $(OPENSSL_PATH)/crypto/async/arch/async_win.h $(OPENSSL_PATH)/crypto/async/async.c $(OPENSSL_PATH)/crypto/async/async_err.c $(OPENSSL_PATH)/crypto/async/async_wait.c - $(OPENSSL_PATH)/crypto/async/async_locl.h $(OPENSSL_PATH)/crypto/bio/b_addr.c $(OPENSSL_PATH)/crypto/bio/b_dump.c $(OPENSSL_PATH)/crypto/bio/b_sock.c @@ -137,7 +126,6 @@ $(OPENSSL_PATH)/crypto/bio/bss_mem.c $(OPENSSL_PATH)/crypto/bio/bss_null.c $(OPENSSL_PATH)/crypto/bio/bss_sock.c - $(OPENSSL_PATH)/crypto/bio/bio_lcl.h $(OPENSSL_PATH)/crypto/bn/bn_add.c $(OPENSSL_PATH)/crypto/bn/bn_asm.c $(OPENSSL_PATH)/crypto/bn/bn_blind.c @@ -169,9 +157,6 @@ $(OPENSSL_PATH)/crypto/bn/bn_srp.c $(OPENSSL_PATH)/crypto/bn/bn_word.c $(OPENSSL_PATH)/crypto/bn/bn_x931p.c - $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h - $(OPENSSL_PATH)/crypto/bn/bn_prime.h - $(OPENSSL_PATH)/crypto/bn/bn_lcl.h $(OPENSSL_PATH)/crypto/buffer/buf_err.c $(OPENSSL_PATH)/crypto/buffer/buffer.c $(OPENSSL_PATH)/crypto/cmac/cm_ameth.c @@ -180,7 +165,6 @@ $(OPENSSL_PATH)/crypto/comp/c_zlib.c $(OPENSSL_PATH)/crypto/comp/comp_err.c $(OPENSSL_PATH)/crypto/comp/comp_lib.c - $(OPENSSL_PATH)/crypto/comp/comp_lcl.h $(OPENSSL_PATH)/crypto/conf/conf_api.c $(OPENSSL_PATH)/crypto/conf/conf_def.c $(OPENSSL_PATH)/crypto/conf/conf_err.c @@ -189,8 +173,6 @@ $(OPENSSL_PATH)/crypto/conf/conf_mod.c $(OPENSSL_PATH)/crypto/conf/conf_sap.c $(OPENSSL_PATH)/crypto/conf/conf_ssl.c - $(OPENSSL_PATH)/crypto/conf/conf_lcl.h - $(OPENSSL_PATH)/crypto/conf/conf_def.h $(OPENSSL_PATH)/crypto/cpt_err.c $(OPENSSL_PATH)/crypto/cryptlib.c $(OPENSSL_PATH)/crypto/ctype.c @@ -214,8 +196,6 @@ $(OPENSSL_PATH)/crypto/des/set_key.c $(OPENSSL_PATH)/crypto/des/str2key.c $(OPENSSL_PATH)/crypto/des/xcbc_enc.c - $(OPENSSL_PATH)/crypto/des/spr.h - $(OPENSSL_PATH)/crypto/des/des_locl.h $(OPENSSL_PATH)/crypto/dh/dh_ameth.c $(OPENSSL_PATH)/crypto/dh/dh_asn1.c $(OPENSSL_PATH)/crypto/dh/dh_check.c @@ -230,7 +210,6 @@ $(OPENSSL_PATH)/crypto/dh/dh_prn.c $(OPENSSL_PATH)/crypto/dh/dh_rfc5114.c $(OPENSSL_PATH)/crypto/dh/dh_rfc7919.c - $(OPENSSL_PATH)/crypto/dh/dh_locl.h $(OPENSSL_PATH)/crypto/dso/dso_dl.c $(OPENSSL_PATH)/crypto/dso/dso_dlfcn.c $(OPENSSL_PATH)/crypto/dso/dso_err.c @@ -238,7 +217,6 @@ $(OPENSSL_PATH)/crypto/dso/dso_openssl.c $(OPENSSL_PATH)/crypto/dso/dso_vms.c $(OPENSSL_PATH)/crypto/dso/dso_win32.c - $(OPENSSL_PATH)/crypto/dso/dso_locl.h $(OPENSSL_PATH)/crypto/ebcdic.c $(OPENSSL_PATH)/crypto/err/err.c $(OPENSSL_PATH)/crypto/err/err_prn.c @@ -280,7 +258,6 @@ $(OPENSSL_PATH)/crypto/evp/evp_pkey.c $(OPENSSL_PATH)/crypto/evp/m_md2.c $(OPENSSL_PATH)/crypto/evp/m_md4.c - $(OPENSSL_PATH)/crypto/md4/md4_locl.h $(OPENSSL_PATH)/crypto/evp/m_md5.c $(OPENSSL_PATH)/crypto/evp/m_md5_sha1.c $(OPENSSL_PATH)/crypto/evp/m_mdc2.c @@ -304,13 +281,11 @@ $(OPENSSL_PATH)/crypto/evp/pmeth_fn.c $(OPENSSL_PATH)/crypto/evp/pmeth_gn.c $(OPENSSL_PATH)/crypto/evp/pmeth_lib.c - $(OPENSSL_PATH)/crypto/evp/evp_locl.h $(OPENSSL_PATH)/crypto/ex_data.c $(OPENSSL_PATH)/crypto/getenv.c $(OPENSSL_PATH)/crypto/hmac/hm_ameth.c $(OPENSSL_PATH)/crypto/hmac/hm_pmeth.c $(OPENSSL_PATH)/crypto/hmac/hmac.c - $(OPENSSL_PATH)/crypto/hmac/hmac_lcl.h $(OPENSSL_PATH)/crypto/init.c $(OPENSSL_PATH)/crypto/kdf/hkdf.c $(OPENSSL_PATH)/crypto/kdf/kdf_err.c @@ -318,12 +293,10 @@ $(OPENSSL_PATH)/crypto/kdf/tls1_prf.c $(OPENSSL_PATH)/crypto/lhash/lh_stats.c $(OPENSSL_PATH)/crypto/lhash/lhash.c - $(OPENSSL_PATH)/crypto/lhash/lhash_lcl.h $(OPENSSL_PATH)/crypto/md4/md4_dgst.c $(OPENSSL_PATH)/crypto/md4/md4_one.c $(OPENSSL_PATH)/crypto/md5/md5_dgst.c $(OPENSSL_PATH)/crypto/md5/md5_one.c - $(OPENSSL_PATH)/crypto/md5/md5_locl.h $(OPENSSL_PATH)/crypto/mem.c $(OPENSSL_PATH)/crypto/mem_clr.c $(OPENSSL_PATH)/crypto/mem_dbg.c @@ -338,7 +311,6 @@ $(OPENSSL_PATH)/crypto/modes/ofb128.c $(OPENSSL_PATH)/crypto/modes/wrap128.c $(OPENSSL_PATH)/crypto/modes/xts128.c - $(OPENSSL_PATH)/crypto/modes/modes_lcl.h $(OPENSSL_PATH)/crypto/o_dir.c $(OPENSSL_PATH)/crypto/o_fips.c $(OPENSSL_PATH)/crypto/o_fopen.c @@ -350,9 +322,6 @@ $(OPENSSL_PATH)/crypto/objects/obj_err.c $(OPENSSL_PATH)/crypto/objects/obj_lib.c $(OPENSSL_PATH)/crypto/objects/obj_xref.c - $(OPENSSL_PATH)/crypto/objects/obj_dat.h - $(OPENSSL_PATH)/crypto/objects/obj_xref.h - $(OPENSSL_PATH)/crypto/objects/obj_lcl.h $(OPENSSL_PATH)/crypto/ocsp/ocsp_asn.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_cl.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_err.c @@ -363,7 +332,6 @@ $(OPENSSL_PATH)/crypto/ocsp/ocsp_srv.c $(OPENSSL_PATH)/crypto/ocsp/ocsp_vfy.c $(OPENSSL_PATH)/crypto/ocsp/v3_ocsp.c - $(OPENSSL_PATH)/crypto/ocsp/ocsp_lcl.h $(OPENSSL_PATH)/crypto/pem/pem_all.c $(OPENSSL_PATH)/crypto/pem/pem_err.c $(OPENSSL_PATH)/crypto/pem/pem_info.c @@ -399,8 +367,6 @@ $(OPENSSL_PATH)/crypto/pkcs7/pk7_mime.c $(OPENSSL_PATH)/crypto/pkcs7/pk7_smime.c $(OPENSSL_PATH)/crypto/pkcs7/pkcs7err.c - $(OPENSSL_PATH)/crypto/pkcs12/p12_lcl.h - $(OPENSSL_PATH)/crypto/ppc_arch.h $(OPENSSL_PATH)/crypto/rand/drbg_ctr.c $(OPENSSL_PATH)/crypto/rand/drbg_lib.c $(OPENSSL_PATH)/crypto/rand/rand_egd.c @@ -409,10 +375,8 @@ $(OPENSSL_PATH)/crypto/rand/rand_unix.c $(OPENSSL_PATH)/crypto/rand/rand_vms.c $(OPENSSL_PATH)/crypto/rand/rand_win.c - $(OPENSSL_PATH)/crypto/rand/rand_lcl.h $(OPENSSL_PATH)/crypto/rc4/rc4_enc.c $(OPENSSL_PATH)/crypto/rc4/rc4_skey.c - $(OPENSSL_PATH)/crypto/rc4/rc4_locl.h $(OPENSSL_PATH)/crypto/rsa/rsa_ameth.c $(OPENSSL_PATH)/crypto/rsa/rsa_asn1.c $(OPENSSL_PATH)/crypto/rsa/rsa_chk.c @@ -435,24 +399,18 @@ $(OPENSSL_PATH)/crypto/rsa/rsa_ssl.c $(OPENSSL_PATH)/crypto/rsa/rsa_x931.c $(OPENSSL_PATH)/crypto/rsa/rsa_x931g.c - $(OPENSSL_PATH)/crypto/rsa/rsa_locl.h $(OPENSSL_PATH)/crypto/sha/keccak1600.c $(OPENSSL_PATH)/crypto/sha/sha1_one.c $(OPENSSL_PATH)/crypto/sha/sha1dgst.c $(OPENSSL_PATH)/crypto/sha/sha256.c $(OPENSSL_PATH)/crypto/sha/sha512.c - $(OPENSSL_PATH)/crypto/sha/sha_locl.h $(OPENSSL_PATH)/crypto/siphash/siphash.c $(OPENSSL_PATH)/crypto/siphash/siphash_ameth.c $(OPENSSL_PATH)/crypto/siphash/siphash_pmeth.c - $(OPENSSL_PATH)/crypto/siphash/siphash_local.h $(OPENSSL_PATH)/crypto/sm3/m_sm3.c $(OPENSSL_PATH)/crypto/sm3/sm3.c - $(OPENSSL_PATH)/crypto/sm3/sm3_locl.h $(OPENSSL_PATH)/crypto/sm4/sm4.c $(OPENSSL_PATH)/crypto/stack/stack.c - $(OPENSSL_PATH)/crypto/s390x_arch.h - $(OPENSSL_PATH)/crypto/sparc_arch.h $(OPENSSL_PATH)/crypto/threads_none.c $(OPENSSL_PATH)/crypto/threads_pthread.c $(OPENSSL_PATH)/crypto/threads_win.c @@ -462,9 +420,7 @@ $(OPENSSL_PATH)/crypto/ui/ui_null.c $(OPENSSL_PATH)/crypto/ui/ui_openssl.c $(OPENSSL_PATH)/crypto/ui/ui_util.c - $(OPENSSL_PATH)/crypto/ui/ui_locl.h $(OPENSSL_PATH)/crypto/uid.c - $(OPENSSL_PATH)/crypto/vms_rms.h $(OPENSSL_PATH)/crypto/x509/by_dir.c $(OPENSSL_PATH)/crypto/x509/by_file.c $(OPENSSL_PATH)/crypto/x509/t_crl.c @@ -501,7 +457,6 @@ $(OPENSSL_PATH)/crypto/x509/x_req.c $(OPENSSL_PATH)/crypto/x509/x_x509.c $(OPENSSL_PATH)/crypto/x509/x_x509a.c - $(OPENSSL_PATH)/crypto/x509/x509_lcl.h $(OPENSSL_PATH)/crypto/x509v3/pcy_cache.c $(OPENSSL_PATH)/crypto/x509v3/pcy_data.c $(OPENSSL_PATH)/crypto/x509v3/pcy_lib.c @@ -539,10 +494,57 @@ $(OPENSSL_PATH)/crypto/x509v3/v3_tlsf.c $(OPENSSL_PATH)/crypto/x509v3/v3_utl.c $(OPENSSL_PATH)/crypto/x509v3/v3err.c + $(OPENSSL_PATH)/crypto/hmac/hmac_lcl.h + $(OPENSSL_PATH)/crypto/dh/dh_locl.h + $(OPENSSL_PATH)/crypto/bio/bio_lcl.h + $(OPENSSL_PATH)/crypto/conf/conf_def.h + $(OPENSSL_PATH)/crypto/conf/conf_lcl.h + $(OPENSSL_PATH)/crypto/lhash/lhash_lcl.h + $(OPENSSL_PATH)/crypto/sha/sha_locl.h + $(OPENSSL_PATH)/crypto/md5/md5_locl.h + $(OPENSSL_PATH)/crypto/store/store_locl.h + $(OPENSSL_PATH)/crypto/dso/dso_locl.h + $(OPENSSL_PATH)/crypto/pkcs12/p12_lcl.h + $(OPENSSL_PATH)/crypto/arm_arch.h + $(OPENSSL_PATH)/crypto/mips_arch.h + $(OPENSSL_PATH)/crypto/ppc_arch.h + $(OPENSSL_PATH)/crypto/s390x_arch.h + $(OPENSSL_PATH)/crypto/sparc_arch.h + $(OPENSSL_PATH)/crypto/vms_rms.h + $(OPENSSL_PATH)/crypto/bn/bn_lcl.h + $(OPENSSL_PATH)/crypto/bn/bn_prime.h + $(OPENSSL_PATH)/crypto/bn/rsaz_exp.h + $(OPENSSL_PATH)/crypto/ui/ui_locl.h + $(OPENSSL_PATH)/crypto/md4/md4_locl.h + $(OPENSSL_PATH)/crypto/rc4/rc4_locl.h + $(OPENSSL_PATH)/crypto/asn1/asn1_item_list.h + $(OPENSSL_PATH)/crypto/asn1/asn1_locl.h + $(OPENSSL_PATH)/crypto/asn1/charmap.h + $(OPENSSL_PATH)/crypto/asn1/standard_methods.h + $(OPENSSL_PATH)/crypto/asn1/tbl_standard.h + $(OPENSSL_PATH)/crypto/evp/evp_locl.h + $(OPENSSL_PATH)/crypto/rand/rand_lcl.h + $(OPENSSL_PATH)/crypto/ocsp/ocsp_lcl.h + $(OPENSSL_PATH)/crypto/modes/modes_lcl.h + $(OPENSSL_PATH)/crypto/comp/comp_lcl.h + $(OPENSSL_PATH)/crypto/rsa/rsa_locl.h + $(OPENSSL_PATH)/crypto/x509/x509_lcl.h + $(OPENSSL_PATH)/crypto/async/arch/async_null.h + $(OPENSSL_PATH)/crypto/async/arch/async_posix.h + $(OPENSSL_PATH)/crypto/async/arch/async_win.h + $(OPENSSL_PATH)/crypto/sm3/sm3_locl.h + $(OPENSSL_PATH)/crypto/des/des_locl.h + $(OPENSSL_PATH)/crypto/des/spr.h + $(OPENSSL_PATH)/crypto/siphash/siphash_local.h + $(OPENSSL_PATH)/crypto/aes/aes_locl.h + $(OPENSSL_PATH)/crypto/async/async_locl.h + $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h $(OPENSSL_PATH)/crypto/x509v3/pcy_int.h - $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h $(OPENSSL_PATH)/crypto/x509v3/standard_exts.h - $(OPENSSL_PATH)/crypto/x509v3/ext_dat.h + $(OPENSSL_PATH)/crypto/x509v3/v3_admis.h + $(OPENSSL_PATH)/crypto/objects/obj_dat.h + $(OPENSSL_PATH)/crypto/objects/obj_lcl.h + $(OPENSSL_PATH)/crypto/objects/obj_xref.h # Autogenerated files list ends here buildinf.h rand_pool_noise.h diff --git a/CryptoPkg/Library/OpensslLib/process_files.pl b/CryptoPkg/Library/OpensslLib/process_files.pl index e13c0acb4dd..4fe54cd808a 100755 --- a/CryptoPkg/Library/OpensslLib/process_files.pl +++ b/CryptoPkg/Library/OpensslLib/process_files.pl @@ -144,6 +144,34 @@ BEGIN } } + +# +# Update the perl script to generate the missing header files +# +my @dir_list = (); +for (keys %{$unified_info{dirinfo}}){ + push @dir_list,$_; +} + +my $dir = getcwd(); +my @files = (); +my @headers = (); +chdir ("openssl"); +foreach(@dir_list){ + @files = glob($_."/*.h"); + push @headers, @files; +} +chdir ($dir); + +foreach (@headers){ + if(/ssl/){ + push @sslfilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; + next; + } + push @cryptofilelist, ' $(OPENSSL_PATH)/' . $_ . "\r\n"; +} + + # # Update OpensslLib.inf with autogenerated file list # From b15646484eaffcf7cc464fdea0214498f26addc2 Mon Sep 17 00:00:00 2001 From: Sunny Wang Date: Wed, 16 Oct 2019 17:19:22 +0800 Subject: [PATCH 007/384] MdeModulePkg/BdsDxe: Fix PlatformRecovery issue For now, PlatformRecovery doesn't work if OsIndications variable doesn't exist, which is wrong. According to the UEFI specification section 3.4.1 and 3.4.2, if processing of BootOrder does not result in success, the OsRecovery and PlatformRecovery options should still be processed regardless of the existence of the OsIndications variable. Therefore, update the code to check PcdPlatformRecoverySupport instead of the value of OsIndications variable (PlatformRecovery) to fix this issue. Cc: Jian J Wang Cc: Hao Wu Cc: Ray Ni Cc: Zhichao Gao Cc: Walon Li Signed-off-by: Sunny Wang Reviewed-by: Ray Ni Reviewed-by: Zhichao Gao Acked-by: Jian J Wang --- MdeModulePkg/Universal/BdsDxe/BdsEntry.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c index d6ec31118c1..d387dbe7ac1 100644 --- a/MdeModulePkg/Universal/BdsDxe/BdsEntry.c +++ b/MdeModulePkg/Universal/BdsDxe/BdsEntry.c @@ -6,7 +6,7 @@ to enter BDS phase. Copyright (c) 2004 - 2019, Intel Corporation. All rights reserved.
-(C) Copyright 2016 Hewlett Packard Enterprise Development LP
+(C) Copyright 2016-2019 Hewlett Packard Enterprise Development LP
(C) Copyright 2015 Hewlett-Packard Development Company, L.P.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -1069,7 +1069,7 @@ BdsEntry ( } if (!BootSuccess) { - if (PlatformRecovery) { + if (PcdGetBool (PcdPlatformRecoverySupport)) { LoadOptions = EfiBootManagerGetLoadOptions (&LoadOptionCount, LoadOptionTypePlatformRecovery); ProcessLoadOptions (LoadOptions, LoadOptionCount); EfiBootManagerFreeLoadOptions (LoadOptions, LoadOptionCount); From 31efec82796cb950e99d1622aa9c0eb8380613a0 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Fri, 27 Sep 2019 11:44:38 +0800 Subject: [PATCH 008/384] MdePkg/Include/Protocol/Tls.h: Add the data type of EfiTlsVerifyHost (CVE-2019-14553) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 In the patch, we add the new data type named "EfiTlsVerifyHost" and the EFI_TLS_VERIFY_HOST_FLAG for the TLS protocol consumer (HTTP) to enable the host name check so as to avoid the potential Man-In-The-Middle attack. Signed-off-by: Wu Jiaxin Reviewed-by: Ye Ting Reviewed-by: Long Qin Reviewed-by: Fu Siyuan Acked-by: Laszlo Ersek Message-Id: <20190927034441.3096-2-Jiaxin.wu@intel.com> Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Signed-off-by: Laszlo Ersek Reviewed-by: Liming Gao --- MdePkg/Include/Protocol/Tls.h | 68 +++++++++++++++++++++++++++++------ 1 file changed, 57 insertions(+), 11 deletions(-) diff --git a/MdePkg/Include/Protocol/Tls.h b/MdePkg/Include/Protocol/Tls.h index bf1b6727a1e..af524ae2a60 100644 --- a/MdePkg/Include/Protocol/Tls.h +++ b/MdePkg/Include/Protocol/Tls.h @@ -41,10 +41,6 @@ typedef struct _EFI_TLS_PROTOCOL EFI_TLS_PROTOCOL; /// EFI_TLS_SESSION_DATA_TYPE /// typedef enum { - /// - /// Session Configuration - /// - /// /// TLS session Version. The corresponding Data is of type EFI_TLS_VERSION. /// @@ -86,11 +82,6 @@ typedef enum { /// The corresponding Data is of type EFI_TLS_SESSION_STATE. /// EfiTlsSessionState, - - /// - /// Session information - /// - /// /// TLS session data client random. /// The corresponding Data is of type EFI_TLS_RANDOM. @@ -106,9 +97,15 @@ typedef enum { /// The corresponding Data is of type EFI_TLS_MASTER_SECRET. /// EfiTlsKeyMaterial, + /// + /// TLS session hostname for validation which is used to verify whether the name + /// within the peer certificate matches a given host name. + /// This parameter is invalid when EfiTlsVerifyMethod is EFI_TLS_VERIFY_NONE. + /// The corresponding Data is of type EFI_TLS_VERIFY_HOST. + /// + EfiTlsVerifyHost, EfiTlsSessionDataTypeMaximum - } EFI_TLS_SESSION_DATA_TYPE; /// @@ -178,7 +175,8 @@ typedef UINT32 EFI_TLS_VERIFY; /// #define EFI_TLS_VERIFY_PEER 0x1 /// -/// TLS session will fail peer certificate is absent. +/// EFI_TLS_VERIFY_FAIL_IF_NO_PEER_CERT is only meaningful in the server mode. +/// TLS session will fail if client certificate is absent. /// #define EFI_TLS_VERIFY_FAIL_IF_NO_PEER_CERT 0x2 /// @@ -187,6 +185,54 @@ typedef UINT32 EFI_TLS_VERIFY; /// #define EFI_TLS_VERIFY_CLIENT_ONCE 0x4 +/// +/// EFI_TLS_VERIFY_HOST_FLAG +/// +typedef UINT32 EFI_TLS_VERIFY_HOST_FLAG; +/// +/// There is no additional flags set for hostname validation. +/// Wildcards are supported and they match only in the left-most label. +/// +#define EFI_TLS_VERIFY_FLAG_NONE 0x00 +/// +/// Always check the Subject Distinguished Name (DN) in the peer certificate even if the +/// certificate contains Subject Alternative Name (SAN). +/// +#define EFI_TLS_VERIFY_FLAG_ALWAYS_CHECK_SUBJECT 0x01 +/// +/// Disable the match of all wildcards. +/// +#define EFI_TLS_VERIFY_FLAG_NO_WILDCARDS 0x02 +/// +/// Disable the "*" as wildcard in labels that have a prefix or suffix (e.g. "www*" or "*www"). +/// +#define EFI_TLS_VERIFY_FLAG_NO_PARTIAL_WILDCARDS 0x04 +/// +/// Allow the "*" to match more than one labels. Otherwise, only matches a single label. +/// +#define EFI_TLS_VERIFY_FLAG_MULTI_LABEL_WILDCARDS 0x08 +/// +/// Restrict to only match direct child sub-domains which start with ".". +/// For example, a name of ".example.com" would match "www.example.com" with this flag, +/// but would not match "www.sub.example.com". +/// +#define EFI_TLS_VERIFY_FLAG_SINGLE_LABEL_SUBDOMAINS 0x10 +/// +/// Never check the Subject Distinguished Name (DN) even there is no +/// Subject Alternative Name (SAN) in the certificate. +/// +#define EFI_TLS_VERIFY_FLAG_NEVER_CHECK_SUBJECT 0x20 + +/// +/// EFI_TLS_VERIFY_HOST +/// +#pragma pack (1) +typedef struct { + EFI_TLS_VERIFY_HOST_FLAG Flags; + CHAR8 *HostName; +} EFI_TLS_VERIFY_HOST; +#pragma pack () + /// /// EFI_TLS_RANDOM /// Note: The definition of EFI_TLS_RANDOM is from "RFC 5246 A.4.1. From 2ca74e1a175232cc201798e27437700adc7fb07e Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Fri, 27 Sep 2019 11:44:39 +0800 Subject: [PATCH 009/384] CryptoPkg/TlsLib: Add the new API "TlsSetVerifyHost" (CVE-2019-14553) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 In the patch, we add the new API "TlsSetVerifyHost" for the TLS protocol to set the specified host name that need to be verified. Signed-off-by: Wu Jiaxin Reviewed-by: Ye Ting Reviewed-by: Long Qin Reviewed-by: Fu Siyuan Acked-by: Laszlo Ersek Message-Id: <20190927034441.3096-3-Jiaxin.wu@intel.com> Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Jian J Wang --- CryptoPkg/Include/Library/TlsLib.h | 20 +++++++++++++++ CryptoPkg/Library/TlsLib/TlsConfig.c | 38 +++++++++++++++++++++++++++- 2 files changed, 57 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Include/Library/TlsLib.h b/CryptoPkg/Include/Library/TlsLib.h index 9875cb6e746..3af7d4bc095 100644 --- a/CryptoPkg/Include/Library/TlsLib.h +++ b/CryptoPkg/Include/Library/TlsLib.h @@ -396,6 +396,26 @@ TlsSetVerify ( IN UINT32 VerifyMode ); +/** + Set the specified host name to be verified. + + @param[in] Tls Pointer to the TLS object. + @param[in] Flags The setting flags during the validation. + @param[in] HostName The specified host name to be verified. + + @retval EFI_SUCCESS The HostName setting was set successfully. + @retval EFI_INVALID_PARAMETER The parameter is invalid. + @retval EFI_ABORTED Invalid HostName setting. + +**/ +EFI_STATUS +EFIAPI +TlsSetVerifyHost ( + IN VOID *Tls, + IN UINT32 Flags, + IN CHAR8 *HostName + ); + /** Sets a TLS/SSL session ID to be used during TLS/SSL connect. diff --git a/CryptoPkg/Library/TlsLib/TlsConfig.c b/CryptoPkg/Library/TlsLib/TlsConfig.c index 74b577d60ee..2bf5aee7c09 100644 --- a/CryptoPkg/Library/TlsLib/TlsConfig.c +++ b/CryptoPkg/Library/TlsLib/TlsConfig.c @@ -1,7 +1,7 @@ /** @file SSL/TLS Configuration Library Wrapper Implementation over OpenSSL. -Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.
+Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
(C) Copyright 2016 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -497,6 +497,42 @@ TlsSetVerify ( SSL_set_verify (TlsConn->Ssl, VerifyMode, NULL); } +/** + Set the specified host name to be verified. + + @param[in] Tls Pointer to the TLS object. + @param[in] Flags The setting flags during the validation. + @param[in] HostName The specified host name to be verified. + + @retval EFI_SUCCESS The HostName setting was set successfully. + @retval EFI_INVALID_PARAMETER The parameter is invalid. + @retval EFI_ABORTED Invalid HostName setting. + +**/ +EFI_STATUS +EFIAPI +TlsSetVerifyHost ( + IN VOID *Tls, + IN UINT32 Flags, + IN CHAR8 *HostName + ) +{ + TLS_CONNECTION *TlsConn; + + TlsConn = (TLS_CONNECTION *) Tls; + if (TlsConn == NULL || TlsConn->Ssl == NULL || HostName == NULL) { + return EFI_INVALID_PARAMETER; + } + + SSL_set_hostflags(TlsConn->Ssl, Flags); + + if (SSL_set1_host(TlsConn->Ssl, HostName) == 0) { + return EFI_ABORTED; + } + + return EFI_SUCCESS; +} + /** Sets a TLS/SSL session ID to be used during TLS/SSL connect. From eb520d94dba7369d1886cd5522d5a2c36fb02209 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 24 Oct 2019 16:44:08 +0200 Subject: [PATCH 010/384] CryptoPkg/Crt: turn strchr() into a function (CVE-2019-14553) According to the ISO C standard, strchr() is a function. We #define it as a macro. Unfortunately, our macro evaluates the first argument ("str") twice. If the expression passed for "str" has side effects, the behavior may be undefined. In a later patch in this series, we're going to resurrect "inet_pton.c" (originally from the StdLib package), which calls strchr() just like that: strchr((xdigits = xdigits_l), ch) strchr((xdigits = xdigits_u), ch) To enable this kind of function call, turn strchr() into a function. Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Jian J Wang Reviewed-by: Jiaxin Wu --- CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c | 5 +++++ CryptoPkg/Library/Include/CrtLibSupport.h | 2 +- 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c b/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c index 71a2ef34ed2..42235ab96ac 100644 --- a/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c @@ -115,6 +115,11 @@ QuickSortWorker ( // -- String Manipulation Routines -- // +char *strchr(const char *str, int ch) +{ + return ScanMem8 (str, AsciiStrSize (str), (UINT8)ch); +} + /* Scan a string for the last occurrence of a character */ char *strrchr (const char *str, int c) { diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index 5806f50f748..b90da20ff7e 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -147,6 +147,7 @@ int isupper (int); int tolower (int); int strcmp (const char *, const char *); int strncasecmp (const char *, const char *, size_t); +char *strchr (const char *, int); char *strrchr (const char *, int); unsigned long strtoul (const char *, char **, int); long strtol (const char *, char **, int); @@ -188,7 +189,6 @@ void abort (void); #define strcpy(strDest,strSource) AsciiStrCpyS(strDest,MAX_STRING_SIZE,strSource) #define strncpy(strDest,strSource,count) AsciiStrnCpyS(strDest,MAX_STRING_SIZE,strSource,(UINTN)count) #define strcat(strDest,strSource) AsciiStrCatS(strDest,MAX_STRING_SIZE,strSource) -#define strchr(str,ch) ScanMem8((VOID *)(str),AsciiStrSize(str),(UINT8)ch) #define strncmp(string1,string2,count) (int)(AsciiStrnCmp(string1,string2,(UINTN)(count))) #define strcasecmp(str1,str2) (int)AsciiStriCmp(str1,str2) #define sprintf(buf,...) AsciiSPrint(buf,MAX_STRING_SIZE,__VA_ARGS__) From 2ac41c12c0d4b3d3ee8f905ab80da019e784de00 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 24 Oct 2019 17:03:57 +0200 Subject: [PATCH 011/384] CryptoPkg/Crt: satisfy "inet_pton.c" dependencies (CVE-2019-14553) In a later patch in this series, we're going to resurrect "inet_pton.c" (originally from the StdLib package). That source file has a number of standard C and BSD socket dependencies. Provide those dependencies here: - The header files below will simply #include : - arpa/inet.h - arpa/nameser.h - netinet/in.h - sys/param.h - sys/socket.h - EAFNOSUPPORT comes from "StdLib/Include/errno.h", at commit e2d3a25f1a31; which is the commit immediately preceding the removal of StdLib from edk2 (964f432b9b0a). Note that the other error macro, which we alread #define, namely EINVAL, has a value (22) that also matches "StdLib/Include/errno.h". - The AF_INET and AF_INET6 address family macros come from "StdLib/Include/sys/socket.h". - The NS_INT16SZ, NS_INADDRSZ and NS_IN6ADDRSZ macros come from "StdLib/Include/arpa/nameser.h". - The "u_int" and "u_char" types come from "StdLib/Include/sys/types.h". Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 Signed-off-by: Laszlo Ersek Reviewed-by: Jian J Wang Reviewed-by: Jiaxin Wu --- CryptoPkg/Library/Include/CrtLibSupport.h | 16 ++++++++++++++++ CryptoPkg/Library/Include/arpa/inet.h | 9 +++++++++ CryptoPkg/Library/Include/arpa/nameser.h | 9 +++++++++ CryptoPkg/Library/Include/netinet/in.h | 9 +++++++++ CryptoPkg/Library/Include/sys/param.h | 9 +++++++++ CryptoPkg/Library/Include/sys/socket.h | 9 +++++++++ 6 files changed, 61 insertions(+) create mode 100644 CryptoPkg/Library/Include/arpa/inet.h create mode 100644 CryptoPkg/Library/Include/arpa/nameser.h create mode 100644 CryptoPkg/Library/Include/netinet/in.h create mode 100644 CryptoPkg/Library/Include/sys/param.h create mode 100644 CryptoPkg/Library/Include/sys/socket.h diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index b90da20ff7e..e603fad763f 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -74,20 +74,36 @@ SPDX-License-Identifier: BSD-2-Clause-Patent // Definitions for global constants used by CRT library routines // #define EINVAL 22 /* Invalid argument */ +#define EAFNOSUPPORT 47 /* Address family not supported by protocol family */ #define INT_MAX 0x7FFFFFFF /* Maximum (signed) int value */ #define LONG_MAX 0X7FFFFFFFL /* max value for a long */ #define LONG_MIN (-LONG_MAX-1) /* min value for a long */ #define ULONG_MAX 0xFFFFFFFF /* Maximum unsigned long value */ #define CHAR_BIT 8 /* Number of bits in a char */ +// +// Address families. +// +#define AF_INET 2 /* internetwork: UDP, TCP, etc. */ +#define AF_INET6 24 /* IP version 6 */ + +// +// Define constants based on RFC0883, RFC1034, RFC 1035 +// +#define NS_INT16SZ 2 /*%< #/bytes of data in a u_int16_t */ +#define NS_INADDRSZ 4 /*%< IPv4 T_A */ +#define NS_IN6ADDRSZ 16 /*%< IPv6 T_AAAA */ + // // Basic types mapping // typedef UINTN size_t; +typedef UINTN u_int; typedef INTN ssize_t; typedef INT32 time_t; typedef UINT8 __uint8_t; typedef UINT8 sa_family_t; +typedef UINT8 u_char; typedef UINT32 uid_t; typedef UINT32 gid_t; diff --git a/CryptoPkg/Library/Include/arpa/inet.h b/CryptoPkg/Library/Include/arpa/inet.h new file mode 100644 index 00000000000..988e4e0a73e --- /dev/null +++ b/CryptoPkg/Library/Include/arpa/inet.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building third-party standard C / BSD sockets code. + + Copyright (C) 2019, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include diff --git a/CryptoPkg/Library/Include/arpa/nameser.h b/CryptoPkg/Library/Include/arpa/nameser.h new file mode 100644 index 00000000000..988e4e0a73e --- /dev/null +++ b/CryptoPkg/Library/Include/arpa/nameser.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building third-party standard C / BSD sockets code. + + Copyright (C) 2019, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include diff --git a/CryptoPkg/Library/Include/netinet/in.h b/CryptoPkg/Library/Include/netinet/in.h new file mode 100644 index 00000000000..988e4e0a73e --- /dev/null +++ b/CryptoPkg/Library/Include/netinet/in.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building third-party standard C / BSD sockets code. + + Copyright (C) 2019, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include diff --git a/CryptoPkg/Library/Include/sys/param.h b/CryptoPkg/Library/Include/sys/param.h new file mode 100644 index 00000000000..988e4e0a73e --- /dev/null +++ b/CryptoPkg/Library/Include/sys/param.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building third-party standard C / BSD sockets code. + + Copyright (C) 2019, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include diff --git a/CryptoPkg/Library/Include/sys/socket.h b/CryptoPkg/Library/Include/sys/socket.h new file mode 100644 index 00000000000..988e4e0a73e --- /dev/null +++ b/CryptoPkg/Library/Include/sys/socket.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building third-party standard C / BSD sockets code. + + Copyright (C) 2019, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include From 8d16ef8269b2ff373d8da674e59992adfdc032d3 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 24 Oct 2019 15:20:18 +0200 Subject: [PATCH 012/384] CryptoPkg/Crt: import "inet_pton.c" (CVE-2019-14553) For TianoCore BZ#1734, StdLib has been moved from the edk2 project to the edk2-libc project, in commit 964f432b9b0a ("edk2: Remove AppPkg, StdLib, StdLibPrivateInternalFiles", 2019-04-29). We'd like to use the inet_pton() function in CryptoPkg. Resurrect the "inet_pton.c" file from just before the StdLib removal, as follows: $ git show \ 964f432b9b0a^:StdLib/BsdSocketLib/inet_pton.c \ > CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c The inet_pton() function is only intended for the DXE phase at this time, therefore only the "BaseCryptLib" instance INF file receives the new file. Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 Signed-off-by: Laszlo Ersek Reviewed-by: Jian J Wang Reviewed-by: Jiaxin Wu --- .../Library/BaseCryptLib/BaseCryptLib.inf | 1 + .../Library/BaseCryptLib/SysCall/inet_pton.c | 257 ++++++++++++++++++ CryptoPkg/Library/Include/CrtLibSupport.h | 1 + 3 files changed, 259 insertions(+) create mode 100644 CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index a98be2cd959..dc9e6e5d45f 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -58,6 +58,7 @@ SysCall/CrtWrapper.c SysCall/TimerWrapper.c SysCall/BaseMemAllocation.c + SysCall/inet_pton.c [Sources.Ia32] Rand/CryptRandTsc.c diff --git a/CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c b/CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c new file mode 100644 index 00000000000..32e1ab8690e --- /dev/null +++ b/CryptoPkg/Library/BaseCryptLib/SysCall/inet_pton.c @@ -0,0 +1,257 @@ +/* Copyright (c) 1996 by Internet Software Consortium. + * + * Permission to use, copy, modify, and distribute this software for any + * purpose with or without fee is hereby granted, provided that the above + * copyright notice and this permission notice appear in all copies. + * + * THE SOFTWARE IS PROVIDED "AS IS" AND INTERNET SOFTWARE CONSORTIUM DISCLAIMS + * ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES + * OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL INTERNET SOFTWARE + * CONSORTIUM BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL + * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR + * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS + * ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS + * SOFTWARE. + */ + +/* + * Portions copyright (c) 1999, 2000 + * Intel Corporation. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * 3. All advertising materials mentioning features or use of this software + * must display the following acknowledgement: + * + * This product includes software developed by Intel Corporation and + * its contributors. + * + * 4. Neither the name of Intel Corporation or its contributors may be + * used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY INTEL CORPORATION AND CONTRIBUTORS ``AS IS'' + * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL INTEL CORPORATION OR CONTRIBUTORS BE + * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + * THE POSSIBILITY OF SUCH DAMAGE. + * + */ + +#if defined(LIBC_SCCS) && !defined(lint) +static char rcsid[] = "$Id: inet_pton.c,v 1.1.1.1 2003/11/19 01:51:30 kyu3 Exp $"; +#endif /* LIBC_SCCS and not lint */ + +#include +#include +#include +#include +#include +#include +#include +#include + +/* + * WARNING: Don't even consider trying to compile this on a system where + * sizeof(int) < 4. sizeof(int) > 4 is fine; all the world's not a VAX. + */ + +static int inet_pton4 (const char *src, u_char *dst); +static int inet_pton6 (const char *src, u_char *dst); + +/* int + * inet_pton(af, src, dst) + * convert from presentation format (which usually means ASCII printable) + * to network format (which is usually some kind of binary format). + * return: + * 1 if the address was valid for the specified address family + * 0 if the address wasn't valid (`dst' is untouched in this case) + * -1 if some other error occurred (`dst' is untouched in this case, too) + * author: + * Paul Vixie, 1996. + */ +int +inet_pton( + int af, + const char *src, + void *dst + ) +{ + switch (af) { + case AF_INET: + return (inet_pton4(src, dst)); + case AF_INET6: + return (inet_pton6(src, dst)); + default: + errno = EAFNOSUPPORT; + return (-1); + } + /* NOTREACHED */ +} + +/* int + * inet_pton4(src, dst) + * like inet_aton() but without all the hexadecimal and shorthand. + * return: + * 1 if `src' is a valid dotted quad, else 0. + * notice: + * does not touch `dst' unless it's returning 1. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton4( + const char *src, + u_char *dst + ) +{ + static const char digits[] = "0123456789"; + int saw_digit, octets, ch; + u_char tmp[NS_INADDRSZ], *tp; + + saw_digit = 0; + octets = 0; + *(tp = tmp) = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr(digits, ch)) != NULL) { + u_int new = *tp * 10 + (u_int)(pch - digits); + + if (new > 255) + return (0); + *tp = (u_char)new; + if (! saw_digit) { + if (++octets > 4) + return (0); + saw_digit = 1; + } + } else if (ch == '.' && saw_digit) { + if (octets == 4) + return (0); + *++tp = 0; + saw_digit = 0; + } else + return (0); + } + if (octets < 4) + return (0); + + memcpy(dst, tmp, NS_INADDRSZ); + return (1); +} + +/* int + * inet_pton6(src, dst) + * convert presentation level address to network order binary form. + * return: + * 1 if `src' is a valid [RFC1884 2.2] address, else 0. + * notice: + * (1) does not touch `dst' unless it's returning 1. + * (2) :: in a full address is silently ignored. + * credit: + * inspired by Mark Andrews. + * author: + * Paul Vixie, 1996. + */ +static int +inet_pton6( + const char *src, + u_char *dst + ) +{ + static const char xdigits_l[] = "0123456789abcdef", + xdigits_u[] = "0123456789ABCDEF"; + u_char tmp[NS_IN6ADDRSZ], *tp, *endp, *colonp; + const char *xdigits, *curtok; + int ch, saw_xdigit; + u_int val; + + memset((tp = tmp), '\0', NS_IN6ADDRSZ); + endp = tp + NS_IN6ADDRSZ; + colonp = NULL; + /* Leading :: requires some special handling. */ + if (*src == ':') + if (*++src != ':') + return (0); + curtok = src; + saw_xdigit = 0; + val = 0; + while ((ch = *src++) != '\0') { + const char *pch; + + if ((pch = strchr((xdigits = xdigits_l), ch)) == NULL) + pch = strchr((xdigits = xdigits_u), ch); + if (pch != NULL) { + val <<= 4; + val |= (pch - xdigits); + if (val > 0xffff) + return (0); + saw_xdigit = 1; + continue; + } + if (ch == ':') { + curtok = src; + if (!saw_xdigit) { + if (colonp) + return (0); + colonp = tp; + continue; + } + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + saw_xdigit = 0; + val = 0; + continue; + } + if (ch == '.' && ((tp + NS_INADDRSZ) <= endp) && + inet_pton4(curtok, tp) > 0) { + tp += NS_INADDRSZ; + saw_xdigit = 0; + break; /* '\0' was seen by inet_pton4(). */ + } + return (0); + } + if (saw_xdigit) { + if (tp + NS_INT16SZ > endp) + return (0); + *tp++ = (u_char) (val >> 8) & 0xff; + *tp++ = (u_char) val & 0xff; + } + if (colonp != NULL) { + /* + * Since some memmove()'s erroneously fail to handle + * overlapping regions, we'll do the shift by hand. + */ + const int n = (int)(tp - colonp); + int i; + + for (i = 1; i <= n; i++) { + endp[- i] = colonp[n - i]; + colonp[n - i] = 0; + } + tp = endp; + } + if (tp != endp) + return (0); + memcpy(dst, tmp, NS_IN6ADDRSZ); + return (1); +} diff --git a/CryptoPkg/Library/Include/CrtLibSupport.h b/CryptoPkg/Library/Include/CrtLibSupport.h index e603fad763f..5a20ba636ff 100644 --- a/CryptoPkg/Library/Include/CrtLibSupport.h +++ b/CryptoPkg/Library/Include/CrtLibSupport.h @@ -192,6 +192,7 @@ void abort (void) __attribute__((__noreturn__)); #else void abort (void); #endif +int inet_pton (int, const char *, void *); // // Macros that directly map functions to BaseLib, BaseMemoryLib, and DebugLib functions From 1e72b1fb2ec597caedb5170079bb213f6d67f32a Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 24 Oct 2019 21:17:36 +0200 Subject: [PATCH 013/384] CryptoPkg/TlsLib: TlsSetVerifyHost: parse IP address literals as such (CVE-2019-14553) Using the inet_pton() function that we imported in the previous patches, recognize if "HostName" is an IP address literal, and then parse it into binary representation. Passing the latter to OpenSSL for server certificate validation is important, per RFC-2818 : > In some cases, the URI is specified as an IP address rather than a > hostname. In this case, the iPAddress subjectAltName must be present in > the certificate and must exactly match the IP in the URI. Note: we cannot use X509_VERIFY_PARAM_set1_ip_asc() because in the OpenSSL version that is currently consumed by edk2, said function depends on sscanf() for parsing IPv4 literals. In "CryptoPkg/Library/BaseCryptLib/SysCall/CrtWrapper.c", we only provide an empty -- always failing -- stub for sscanf(), however. Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 Suggested-by: David Woodhouse Signed-off-by: Laszlo Ersek Acked-by: Jian J Wang Reviewed-by: Jiaxin Wu --- CryptoPkg/Library/TlsLib/TlsConfig.c | 28 ++++++++++++++++++++++++---- 1 file changed, 24 insertions(+), 4 deletions(-) diff --git a/CryptoPkg/Library/TlsLib/TlsConfig.c b/CryptoPkg/Library/TlsLib/TlsConfig.c index 2bf5aee7c09..307eb57896d 100644 --- a/CryptoPkg/Library/TlsLib/TlsConfig.c +++ b/CryptoPkg/Library/TlsLib/TlsConfig.c @@ -517,7 +517,11 @@ TlsSetVerifyHost ( IN CHAR8 *HostName ) { - TLS_CONNECTION *TlsConn; + TLS_CONNECTION *TlsConn; + X509_VERIFY_PARAM *VerifyParam; + UINTN BinaryAddressSize; + UINT8 BinaryAddress[MAX (NS_INADDRSZ, NS_IN6ADDRSZ)]; + INTN ParamStatus; TlsConn = (TLS_CONNECTION *) Tls; if (TlsConn == NULL || TlsConn->Ssl == NULL || HostName == NULL) { @@ -526,11 +530,27 @@ TlsSetVerifyHost ( SSL_set_hostflags(TlsConn->Ssl, Flags); - if (SSL_set1_host(TlsConn->Ssl, HostName) == 0) { - return EFI_ABORTED; + VerifyParam = SSL_get0_param (TlsConn->Ssl); + ASSERT (VerifyParam != NULL); + + BinaryAddressSize = 0; + if (inet_pton (AF_INET6, HostName, BinaryAddress) == 1) { + BinaryAddressSize = NS_IN6ADDRSZ; + } else if (inet_pton (AF_INET, HostName, BinaryAddress) == 1) { + BinaryAddressSize = NS_INADDRSZ; } - return EFI_SUCCESS; + if (BinaryAddressSize > 0) { + DEBUG ((DEBUG_VERBOSE, "%a:%a: parsed \"%a\" as an IPv%c address " + "literal\n", gEfiCallerBaseName, __FUNCTION__, HostName, + (UINTN)((BinaryAddressSize == NS_IN6ADDRSZ) ? '6' : '4'))); + ParamStatus = X509_VERIFY_PARAM_set1_ip (VerifyParam, BinaryAddress, + BinaryAddressSize); + } else { + ParamStatus = X509_VERIFY_PARAM_set1_host (VerifyParam, HostName, 0); + } + + return (ParamStatus == 1) ? EFI_SUCCESS : EFI_ABORTED; } /** From 703e7ab21ff8fda9ababf7751d59bd28ad5da947 Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Fri, 27 Sep 2019 11:44:40 +0800 Subject: [PATCH 014/384] NetworkPkg/TlsDxe: Add the support of host validation to TlsDxe driver (CVE-2019-14553) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 The new data type named "EfiTlsVerifyHost" and the EFI_TLS_VERIFY_HOST_FLAG are supported in TLS protocol. Signed-off-by: Wu Jiaxin Reviewed-by: Ye Ting Reviewed-by: Long Qin Reviewed-by: Fu Siyuan Acked-by: Laszlo Ersek Message-Id: <20190927034441.3096-4-Jiaxin.wu@intel.com> Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Signed-off-by: Laszlo Ersek --- NetworkPkg/TlsDxe/TlsProtocol.c | 44 ++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/NetworkPkg/TlsDxe/TlsProtocol.c b/NetworkPkg/TlsDxe/TlsProtocol.c index a7a993fc6fc..001e5400d00 100644 --- a/NetworkPkg/TlsDxe/TlsProtocol.c +++ b/NetworkPkg/TlsDxe/TlsProtocol.c @@ -1,7 +1,7 @@ /** @file Implementation of EFI TLS Protocol Interfaces. - Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2018, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -56,12 +56,16 @@ TlsSetSessionData ( UINT16 *CipherId; CONST EFI_TLS_CIPHER *TlsCipherList; UINTN CipherCount; + CONST EFI_TLS_VERIFY_HOST *TlsVerifyHost; + EFI_TLS_VERIFY VerifyMethod; + UINTN VerifyMethodSize; UINTN Index; EFI_TPL OldTpl; - Status = EFI_SUCCESS; - CipherId = NULL; + Status = EFI_SUCCESS; + CipherId = NULL; + VerifyMethodSize = sizeof (EFI_TLS_VERIFY); if (This == NULL || Data == NULL || DataSize == 0) { return EFI_INVALID_PARAMETER; @@ -148,6 +152,40 @@ TlsSetSessionData ( } TlsSetVerify (Instance->TlsConn, *((UINT32 *) Data)); + break; + case EfiTlsVerifyHost: + if (DataSize != sizeof (EFI_TLS_VERIFY_HOST)) { + Status = EFI_INVALID_PARAMETER; + goto ON_EXIT; + } + + TlsVerifyHost = (CONST EFI_TLS_VERIFY_HOST *) Data; + + if ((TlsVerifyHost->Flags & EFI_TLS_VERIFY_FLAG_ALWAYS_CHECK_SUBJECT) != 0 && + (TlsVerifyHost->Flags & EFI_TLS_VERIFY_FLAG_NEVER_CHECK_SUBJECT) != 0) { + Status = EFI_INVALID_PARAMETER; + goto ON_EXIT; + } + + if ((TlsVerifyHost->Flags & EFI_TLS_VERIFY_FLAG_NO_WILDCARDS) != 0 && + ((TlsVerifyHost->Flags & EFI_TLS_VERIFY_FLAG_NO_PARTIAL_WILDCARDS) != 0 || + (TlsVerifyHost->Flags & EFI_TLS_VERIFY_FLAG_MULTI_LABEL_WILDCARDS) != 0)) { + Status = EFI_INVALID_PARAMETER; + goto ON_EXIT; + } + + Status = This->GetSessionData (This, EfiTlsVerifyMethod, &VerifyMethod, &VerifyMethodSize); + if (EFI_ERROR (Status)) { + goto ON_EXIT; + } + + if ((VerifyMethod & EFI_TLS_VERIFY_PEER) == 0) { + Status = EFI_INVALID_PARAMETER; + goto ON_EXIT; + } + + Status = TlsSetVerifyHost (Instance->TlsConn, TlsVerifyHost->Flags, TlsVerifyHost->HostName); + break; case EfiTlsSessionID: if (DataSize != sizeof (EFI_TLS_SESSION_ID)) { From e2fc50812895b17e8b23f5a9c43cde29531b200f Mon Sep 17 00:00:00 2001 From: "Wu, Jiaxin" Date: Fri, 27 Sep 2019 11:44:41 +0800 Subject: [PATCH 015/384] NetworkPkg/HttpDxe: Set the HostName for the verification (CVE-2019-14553) REF: https://bugzilla.tianocore.org/show_bug.cgi?id=960 CVE: CVE-2019-14553 Set the HostName by consuming TLS protocol to enable the host name check so as to avoid the potential Man-In-The-Middle attack. Signed-off-by: Wu Jiaxin Reviewed-by: Ye Ting Reviewed-by: Long Qin Reviewed-by: Fu Siyuan Acked-by: Laszlo Ersek Message-Id: <20190927034441.3096-5-Jiaxin.wu@intel.com> Cc: David Woodhouse Cc: Jian J Wang Cc: Jiaxin Wu Cc: Sivaraman Nainar Cc: Xiaoyu Lu Signed-off-by: Laszlo Ersek --- NetworkPkg/HttpDxe/HttpProto.h | 1 + NetworkPkg/HttpDxe/HttpsSupport.c | 21 +++++++++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/NetworkPkg/HttpDxe/HttpProto.h b/NetworkPkg/HttpDxe/HttpProto.h index 6e1f51748a7..34308e016d3 100644 --- a/NetworkPkg/HttpDxe/HttpProto.h +++ b/NetworkPkg/HttpDxe/HttpProto.h @@ -82,6 +82,7 @@ typedef struct { EFI_TLS_VERSION Version; EFI_TLS_CONNECTION_END ConnectionEnd; EFI_TLS_VERIFY VerifyMethod; + EFI_TLS_VERIFY_HOST VerifyHost; EFI_TLS_SESSION_STATE SessionState; } TLS_CONFIG_DATA; diff --git a/NetworkPkg/HttpDxe/HttpsSupport.c b/NetworkPkg/HttpDxe/HttpsSupport.c index 988bbcbce7d..5dfb13bd602 100644 --- a/NetworkPkg/HttpDxe/HttpsSupport.c +++ b/NetworkPkg/HttpDxe/HttpsSupport.c @@ -623,13 +623,16 @@ TlsConfigureSession ( // // TlsConfigData initialization // - HttpInstance->TlsConfigData.ConnectionEnd = EfiTlsClient; - HttpInstance->TlsConfigData.VerifyMethod = EFI_TLS_VERIFY_PEER; - HttpInstance->TlsConfigData.SessionState = EfiTlsSessionNotStarted; + HttpInstance->TlsConfigData.ConnectionEnd = EfiTlsClient; + HttpInstance->TlsConfigData.VerifyMethod = EFI_TLS_VERIFY_PEER; + HttpInstance->TlsConfigData.VerifyHost.Flags = EFI_TLS_VERIFY_FLAG_NO_WILDCARDS; + HttpInstance->TlsConfigData.VerifyHost.HostName = HttpInstance->RemoteHost; + HttpInstance->TlsConfigData.SessionState = EfiTlsSessionNotStarted; // // EfiTlsConnectionEnd, - // EfiTlsVerifyMethod + // EfiTlsVerifyMethod, + // EfiTlsVerifyHost, // EfiTlsSessionState // Status = HttpInstance->Tls->SetSessionData ( @@ -652,6 +655,16 @@ TlsConfigureSession ( return Status; } + Status = HttpInstance->Tls->SetSessionData ( + HttpInstance->Tls, + EfiTlsVerifyHost, + &HttpInstance->TlsConfigData.VerifyHost, + sizeof (EFI_TLS_VERIFY_HOST) + ); + if (EFI_ERROR (Status)) { + return Status; + } + Status = HttpInstance->Tls->SetSessionData ( HttpInstance->Tls, EfiTlsSessionState, From 5ae6c993ab75c694831547b7436543a41d60458a Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Sun, 20 Oct 2019 20:08:35 +0800 Subject: [PATCH 016/384] MdePkg/UefiDebugLibConOut: Pass the correct buffer size REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2302 The second argument of "UnicodeVSPrintAsciiFormat" is "BufferSize", which takes the size of the buffer in bytes. Replace the currently used MAX_DEBUG_MESSAGE_LENGTH usage, which is the buffer's length, with the actual buffer size. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Marvin Haeuser Reviewed-by: Liming Gao --- MdePkg/Library/UefiDebugLibConOut/DebugLib.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Library/UefiDebugLibConOut/DebugLib.c b/MdePkg/Library/UefiDebugLibConOut/DebugLib.c index cf168d05cf2..8ea38ea7cc7 100644 --- a/MdePkg/Library/UefiDebugLibConOut/DebugLib.c +++ b/MdePkg/Library/UefiDebugLibConOut/DebugLib.c @@ -104,9 +104,9 @@ DebugPrintMarker ( // Convert the DEBUG() message to a Unicode String // if (BaseListMarker == NULL) { - UnicodeVSPrintAsciiFormat (Buffer, MAX_DEBUG_MESSAGE_LENGTH, Format, VaListMarker); + UnicodeVSPrintAsciiFormat (Buffer, sizeof (Buffer), Format, VaListMarker); } else { - UnicodeBSPrintAsciiFormat (Buffer, MAX_DEBUG_MESSAGE_LENGTH, Format, BaseListMarker); + UnicodeBSPrintAsciiFormat (Buffer, sizeof (Buffer), Format, BaseListMarker); } From 787c4baace1c0c49fa1628990402be8997294d17 Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Mon, 21 Oct 2019 01:28:14 +0800 Subject: [PATCH 017/384] MdePkg/UefiDebugLibStdErr: Pass the correct buffer size REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2302 The second argument of "UnicodeVSPrintAsciiFormat" is "BufferSize", which takes the size of the buffer in bytes. Replace the currently used MAX_DEBUG_MESSAGE_LENGTH usage, which is the buffer's length, with the actual buffer size. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Marvin Haeuser Reviewed-by: Liming Gao --- MdePkg/Library/UefiDebugLibStdErr/DebugLib.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Library/UefiDebugLibStdErr/DebugLib.c b/MdePkg/Library/UefiDebugLibStdErr/DebugLib.c index 40eb697e7e2..fcfdafede08 100644 --- a/MdePkg/Library/UefiDebugLibStdErr/DebugLib.c +++ b/MdePkg/Library/UefiDebugLibStdErr/DebugLib.c @@ -106,9 +106,9 @@ DebugPrintMarker ( // Convert the DEBUG() message to a Unicode String // if (BaseListMarker == NULL) { - UnicodeVSPrintAsciiFormat (Buffer, MAX_DEBUG_MESSAGE_LENGTH, Format, VaListMarker); + UnicodeVSPrintAsciiFormat (Buffer, sizeof (Buffer), Format, VaListMarker); } else { - UnicodeBSPrintAsciiFormat (Buffer, MAX_DEBUG_MESSAGE_LENGTH, Format, BaseListMarker); + UnicodeBSPrintAsciiFormat (Buffer, sizeof (Buffer), Format, BaseListMarker); } // From 1009b59b6525c16724fe2684c344a6359af28b55 Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Sun, 20 Oct 2019 20:08:31 +0800 Subject: [PATCH 018/384] MdePkg/UefiFileHandleLib: Fix potential NULL dereference REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2293 Move the NULL check in FileHandleGetInfo() to directly after the allocation to prevent potential NULL dereferences. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Marvin Haeuser Reviewed-by: Liming Gao --- .../UefiFileHandleLib/UefiFileHandleLib.c | 28 ++++++++++--------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c index 96913c5c02b..5dc893833a4 100644 --- a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c +++ b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c @@ -68,19 +68,21 @@ FileHandleGetInfo ( // error is expected. getting size to allocate // FileInfo = AllocateZeroPool(FileInfoSize); - // - // now get the information - // - Status = FileHandle->GetInfo(FileHandle, - &gEfiFileInfoGuid, - &FileInfoSize, - FileInfo); - // - // if we got an error free the memory and return NULL - // - if (EFI_ERROR(Status) && (FileInfo != NULL)) { - FreePool(FileInfo); - FileInfo = NULL; + if (FileInfo != NULL) { + // + // now get the information + // + Status = FileHandle->GetInfo(FileHandle, + &gEfiFileInfoGuid, + &FileInfoSize, + FileInfo); + // + // if we got an error free the memory and return NULL + // + if (EFI_ERROR(Status)) { + FreePool(FileInfo); + FileInfo = NULL; + } } } return (FileInfo); From 6407186db9505f101ece4e1571eceed69b9fbdbe Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Sun, 20 Oct 2019 20:08:32 +0800 Subject: [PATCH 019/384] MdePkg/UefiFileHandleLib: Tolerate more Root handle FileNames REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2295 The current implementation of the FileHandleGetFileName() function assumes that the Root directory always has the FileName '\0'. However, the only requirement the UEFI specification defines is that a prepended '\\' must be supported to access files and folders relative to the Root directory. This patch removes this assumption and supports constructing valid paths for any value of FileName for the Root Directory. In practice, this fixes compatibility issues with File System drivers that report '\\' as the FileName of the Root directory, which currently is both generating an invalid path ("\\\\") and resulting in an EFI_NOT_FOUND result from the CurrentHandle->Open() call. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Marvin Haeuser Reviewed-by: Liming Gao Reviewed-by: Zhichao Gao --- .../UefiFileHandleLib/UefiFileHandleLib.c | 25 +++++++++++++------ 1 file changed, 18 insertions(+), 7 deletions(-) diff --git a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c index 5dc893833a4..28e28e5f67d 100644 --- a/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c +++ b/MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.c @@ -816,10 +816,25 @@ FileHandleGetFileName ( Status = EFI_OUT_OF_RESOURCES; break; } else { + // + // Prepare to move to the parent directory. + // Also determine whether CurrentHandle refers to the Root directory. + // + Status = CurrentHandle->Open (CurrentHandle, &NextHigherHandle, L"..", EFI_FILE_MODE_READ, 0); // // We got info... do we have a name? if yes precede the current path with it... // - if (StrLen (FileInfo->FileName) == 0) { + if ((StrLen (FileInfo->FileName) == 0) || EFI_ERROR (Status)) { + // + // Both FileInfo->FileName being '\0' and EFI_ERROR() suggest that + // CurrentHandle refers to the Root directory. As this loop ensures + // FullFileName is starting with '\\' at all times, signal success + // and exit the loop. + // While FileInfo->FileName could theoretically be a value other than + // '\0' or '\\', '\\' is guaranteed to be supported by the + // specification and hence its value can safely be ignored. + // + Status = EFI_SUCCESS; if (*FullFileName == NULL) { ASSERT((*FullFileName == NULL && Size == 0) || (*FullFileName != NULL)); *FullFileName = StrnCatGrowLeft(FullFileName, &Size, L"\\", 0); @@ -837,15 +852,11 @@ FileHandleGetFileName ( FreePool(FileInfo); } } + + FileHandleClose(CurrentHandle); // // Move to the parent directory // - Status = CurrentHandle->Open (CurrentHandle, &NextHigherHandle, L"..", EFI_FILE_MODE_READ, 0); - if (EFI_ERROR (Status)) { - break; - } - - FileHandleClose(CurrentHandle); CurrentHandle = NextHigherHandle; } } else if (Status == EFI_NOT_FOUND) { From b10ef8a4e75899cfad421dc60d0bbf93c53d37f4 Mon Sep 17 00:00:00 2001 From: Pierre Gondois Date: Wed, 30 Oct 2019 22:24:57 +0800 Subject: [PATCH 020/384] MdePkg: Add AML OpCode definition for ExternalOp The ACPI specification, version 6.3, January 2019, defines the Named Object Encoding for ExternalOp in section '20.2.5.2 Named Objects Encoding'. This patch adds the definition for ExternalOp to the list of Primary Opcode definitions. Signed-off-by: Pierre Gondois Reviewed-by: Liming Gao Reviewed-by: Sami Mujawar --- MdePkg/Include/IndustryStandard/AcpiAml.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdePkg/Include/IndustryStandard/AcpiAml.h b/MdePkg/Include/IndustryStandard/AcpiAml.h index 6919622af21..3dd5408b359 100644 --- a/MdePkg/Include/IndustryStandard/AcpiAml.h +++ b/MdePkg/Include/IndustryStandard/AcpiAml.h @@ -2,6 +2,7 @@ This file contains AML code definition in the latest ACPI spec. Copyright (c) 2011, Intel Corporation. All rights reserved.
+ Copyright (c) 2019, ARM Limited. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -30,6 +31,7 @@ #define AML_PACKAGE_OP 0x12 #define AML_VAR_PACKAGE_OP 0x13 #define AML_METHOD_OP 0x14 +#define AML_EXTERNAL_OP 0x15 #define AML_DUAL_NAME_PREFIX 0x2e #define AML_MULTI_NAME_PREFIX 0x2f #define AML_NAME_CHAR_A 0x41 From c18708d2f002a6ea43ed65d6c76dc4020687005c Mon Sep 17 00:00:00 2001 From: "Huang, Qing" Date: Wed, 30 Oct 2019 12:54:34 +0800 Subject: [PATCH 021/384] MdePkg-UefiSpec.h: Add UEFI 2.8 new memory attributes BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2309 Add EFI_MEMORY_SP and EFI_MEMORY_CPU_CRYPTO definition into UEFI specification header file. Signed-off-by: Qing Huang Cc: Liming Gao Reviewed-by: Liming Gao --- MdePkg/Include/Uefi/UefiSpec.h | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/MdePkg/Include/Uefi/UefiSpec.h b/MdePkg/Include/Uefi/UefiSpec.h index 44a0a6a7fa6..444aa35ecab 100644 --- a/MdePkg/Include/Uefi/UefiSpec.h +++ b/MdePkg/Include/Uefi/UefiSpec.h @@ -82,6 +82,26 @@ typedef enum { // If all memory has the same reliability, then this bit is not used. // #define EFI_MEMORY_MORE_RELIABLE 0x0000000000010000ULL + +// +// Note: UEFI spec 2.8 and following: +// +// Specific-purpose memory (SPM). The memory is earmarked for +// specific purposes such as for specific device drivers or applications. +// The SPM attribute serves as a hint to the OS to avoid allocating this +// memory for core OS data or code that can not be relocated. +// +#define EFI_MEMORY_SP 0x0000000000040000ULL +// +// If this flag is set, the memory region is capable of being +// protected with the CPU?s memory cryptographic +// capabilities. If this flag is clear, the memory region is not +// capable of being protected with the CPU?s memory +// cryptographic capabilities or the CPU does not support CPU +// memory cryptographic capabilities. +// +#define EFI_MEMORY_CPU_CRYPTO 0x0000000000080000ULL + // // Runtime memory attribute // From 2b23beb043a10dd3c00f43c1f7bb72f47554ff3a Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 14:46:26 +0800 Subject: [PATCH 022/384] MdeModulePkg/Oniguruma: Remove redundant IF statement The if statement is not necessary, so keep it to edk2 style. And this change has been merged to onigruma. REF:https://github.com/kkos/oniguruma/pull/158 Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- .../Oniguruma/unicode_fold1_key.c | 18 +++++++----------- .../Oniguruma/unicode_fold2_key.c | 17 ++++++----------- .../Oniguruma/unicode_fold3_key.c | 18 +++++++----------- .../Oniguruma/unicode_unfold_key.c | 17 ++++++----------- 4 files changed, 26 insertions(+), 44 deletions(-) diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold1_key.c b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold1_key.c index 7dbd6a5995b..0aa54ee172b 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold1_key.c +++ b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold1_key.c @@ -2983,17 +2983,13 @@ onigenc_unicode_fold1_key(OnigCodePoint codes[]) 4026 }; - if (0 == 0) - { - int key = hash(codes); - - if (key <= MAX_HASH_VALUE) - { - int index = wordlist[key]; - - if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds1 + index, 1) == 0) - return index; - } + int key = hash(codes); + if (key <= MAX_HASH_VALUE) { + int index = wordlist[key]; + if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds1 + index, 1) == 0) { + return index; + } } + return -1; } diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold2_key.c b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold2_key.c index 3d93e2417a2..44f8cb66007 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold2_key.c +++ b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold2_key.c @@ -211,17 +211,12 @@ onigenc_unicode_fold2_key(OnigCodePoint codes[]) 129 }; - if (0 == 0) - { - int key = hash(codes); - - if (key <= MAX_HASH_VALUE) - { - int index = wordlist[key]; - - if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds2 + index, 2) == 0) - return index; - } + int key = hash(codes); + if (key <= MAX_HASH_VALUE) { + int index = wordlist[key]; + if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds2 + index, 2) == 0) + return index; } + return -1; } diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold3_key.c b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold3_key.c index bdd5667c6ae..b36500b135e 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold3_key.c +++ b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_fold3_key.c @@ -121,17 +121,13 @@ onigenc_unicode_fold3_key(OnigCodePoint codes[]) 0 }; - if (0 == 0) - { - int key = hash(codes); - - if (key <= MAX_HASH_VALUE) - { - int index = wordlist[key]; - - if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds3 + index, 3) == 0) - return index; - } + int key = hash(codes); + if (key <= MAX_HASH_VALUE) { + int index = wordlist[key]; + if (index >= 0 && onig_codes_cmp(codes, OnigUnicodeFolds3 + index, 3) == 0) { + return index; + } } + return -1; } diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_unfold_key.c b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_unfold_key.c index 10f7889ea37..1f03b21cfe5 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_unfold_key.c +++ b/MdeModulePkg/Universal/RegularExpressionDxe/Oniguruma/unicode_unfold_key.c @@ -3288,17 +3288,12 @@ onigenc_unicode_unfold_key(OnigCodePoint code) {0x1e907, 4005, 1} }; - if (0 == 0) - { - int key = hash(&code); - - if (key <= MAX_HASH_VALUE) - { - OnigCodePoint gcode = wordlist[key].code; - - if (code == gcode && wordlist[key].index >= 0) - return &wordlist[key]; - } + int key = hash(&code); + if (key <= MAX_HASH_VALUE) { + OnigCodePoint gcode = wordlist[key].code; + if (code == gcode && wordlist[key].index >= 0) { + return &wordlist[key]; + } } return 0; } From 121955fd4f9a2a5da7e0e8fe0c47ad5570f18d32 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 14:45:44 +0800 Subject: [PATCH 023/384] MdeModulePkg/Variable/Pei: Update the condition in if statement IndexTable->Length is used as index in array IndexTable->Index[]. So IndexTable->Length needs to be checked, which should be less than the array size. Cc: Hao A Wu Cc: Liming Gao Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Universal/Variable/Pei/Variable.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Universal/Variable/Pei/Variable.c b/MdeModulePkg/Universal/Variable/Pei/Variable.c index 715802f33c2..f61465fc304 100644 --- a/MdeModulePkg/Universal/Variable/Pei/Variable.c +++ b/MdeModulePkg/Universal/Variable/Pei/Variable.c @@ -896,7 +896,7 @@ FindVariableEx ( // if ((IndexTable != NULL) && !StopRecord) { Offset = (UINTN) Variable - (UINTN) LastVariable; - if ((Offset > 0x0FFFF) || (IndexTable->Length == sizeof (IndexTable->Index) / sizeof (IndexTable->Index[0]))) { + if ((Offset > 0x0FFFF) || (IndexTable->Length >= sizeof (IndexTable->Index) / sizeof (IndexTable->Index[0]))) { // // Stop to record if the distance of two neighbouring VAR_ADDED variable is larger than the allowable scope(UINT16), // or the record buffer is full. From df50c2fcd85e24cbece9f03f2879fdcc96096ab1 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 14:27:32 +0800 Subject: [PATCH 024/384] MdeModulePkg/HiiDatabaseDxe: ASSERT "Private->Attribute >> 4" Foreground and background color are saved in a single byte. Bits 0..3 are the foreground color and bits 4..6 are the background color. If the Private->Attribute defined correctly, (Private->Attribute >> 4) must be less than 8. This commit uses ASSERT to assume "Attribute >> 4" is less than 8. Cc: Dandan Bi Cc: Eric Dong Signed-off-by: Shenglei Zhang Reviewed-by: Dandan Bi --- MdeModulePkg/Universal/HiiDatabaseDxe/Font.c | 1 + 1 file changed, 1 insertion(+) diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c b/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c index ca63df168c9..ee6c65287db 100644 --- a/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c +++ b/MdeModulePkg/Universal/HiiDatabaseDxe/Font.c @@ -999,6 +999,7 @@ GetSystemFont ( } Info->ForegroundColor = mHiiEfiColors[Private->Attribute & 0x0f]; + ASSERT ((Private->Attribute >> 4) < 8); Info->BackgroundColor = mHiiEfiColors[Private->Attribute >> 4]; Info->FontInfoMask = EFI_FONT_INFO_SYS_FONT | EFI_FONT_INFO_SYS_SIZE | EFI_FONT_INFO_SYS_STYLE; Info->FontInfo.FontStyle = 0; From d3eac77eebe995553e5d0ab5fbab54e5d5d9c95f Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 13:51:55 +0800 Subject: [PATCH 025/384] MdeModulePkg/SdBlockIoPei: Add check for DeviceIndex DeviceIndex is used as index in Slot[]. The max size of Slot[] is SD_PEIM_MAX_SLOTS. So DeviceIndex should be checked before used. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c index 8fa58d65b22..1d53fcd23e9 100644 --- a/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c +++ b/MdeModulePkg/Bus/Sd/SdBlockIoPei/SdBlockIoPei.c @@ -174,7 +174,7 @@ SdBlockIoPeimGetMediaInfo ( Private = GET_SD_PEIM_HC_PRIVATE_DATA_FROM_THIS (This); - if ((DeviceIndex == 0) || (DeviceIndex > Private->TotalBlkIoDevices)) { + if ((DeviceIndex == 0) || (DeviceIndex > Private->TotalBlkIoDevices) || (DeviceIndex > SD_PEIM_MAX_SLOTS)) { return EFI_INVALID_PARAMETER; } @@ -252,7 +252,7 @@ SdBlockIoPeimReadBlocks ( return EFI_SUCCESS; } - if ((DeviceIndex == 0) || (DeviceIndex > Private->TotalBlkIoDevices)) { + if ((DeviceIndex == 0) || (DeviceIndex > Private->TotalBlkIoDevices) || (DeviceIndex > SD_PEIM_MAX_SLOTS)) { return EFI_INVALID_PARAMETER; } From 7a2505bb0f64a266002737ea8446f14cc4095a22 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Wed, 9 Oct 2019 14:28:50 +0800 Subject: [PATCH 026/384] MdeModulePkg/EhciPei: Initialize the variable Map Map is used but not Initialized. Map is called by IoMmuMap, in which Mapping(Map) is called by IoMmu->Map. We can not assume Map is given an initial value at any step. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c index 7c6a6a5f971..995ccd2463d 100644 --- a/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c +++ b/MdeModulePkg/Bus/Pci/EhciPei/EhciUrb.c @@ -534,6 +534,8 @@ EhcCreateUrb ( PEI_URB *Urb; VOID *Map; + Map = NULL; + Urb = Ehc->Urb; Urb->Signature = EHC_URB_SIG; InitializeListHead (&Urb->UrbList); From a857ea4199ead1858e55b081fea38fcf0e721c8c Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 10:06:42 +0800 Subject: [PATCH 027/384] MdeModulePkg/UhciPei: Initialize the variable RequestMap RequestMap is used but not Initialized. RequestMap is called by UhciMapUserRequest, in which RequestMap(Map) is called by IoMmuMap, and is finally called by IoMmu->Map. We can not assume RequestMap is given an initial value at any step. Cc: Hao A Wu Cc: Ray Ni Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c index b897c3f82ce..a05834da3c4 100644 --- a/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c +++ b/MdeModulePkg/Bus/Pci/UhciPei/UhcPeim.c @@ -274,6 +274,8 @@ UhcControlTransfer ( PktID = INPUT_PACKET_ID; + RequestMap = NULL; + if (Request == NULL || TransferResult == NULL) { return EFI_INVALID_PARAMETER; } From 17efd446c00b414ddeb53ec00b85d780f2f09250 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 10:13:35 +0800 Subject: [PATCH 028/384] MdeModulePkg/Mem: Initialize the variable MapMemory MapMemory is not initialized by FindGuardedMemoryMap or CoreInternalAllocatePages which calls MapMemory. So we give a 0 to it. Cc: Dandan Bi Cc: Liming Gao Signed-off-by: Shenglei Zhang Reviewed-by: Dandan Bi --- MdeModulePkg/Core/Dxe/Mem/HeapGuard.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c index 9477b94044b..b4cb48843fb 100644 --- a/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c +++ b/MdeModulePkg/Core/Dxe/Mem/HeapGuard.c @@ -225,6 +225,8 @@ FindGuardedMemoryMap ( UINTN BitsToUnitEnd; EFI_STATUS Status; + MapMemory = 0; + // // Adjust current map table depth according to the address to access // From 106369fe26579c2c97131c3dd9e7c7332a5ec575 Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Sun, 20 Oct 2019 20:08:32 +0800 Subject: [PATCH 029/384] ShellPkg/Ls: Consider UEFI timezone may not be set REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2294 EFI_RUNTIME_SERVICES.GetTime() might return an unspecified Timezone, such as when SetTime() has not been called after the RTC was cut off power. Consider this case by not attempting Timezone translations for when it is invalid. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Marvin Haeuser Reviewed-by: Zhichao Gao --- ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c index adeb987e6ec..1a65f60c3b4 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c @@ -500,7 +500,7 @@ PrintLsOutput( // Change the file time to local time. // Status = gRT->GetTime(&LocalTime, NULL); - if (!EFI_ERROR (Status)) { + if (!EFI_ERROR (Status) && (LocalTime.TimeZone != EFI_UNSPECIFIED_TIMEZONE)) { if ((Node->Info->CreateTime.TimeZone != EFI_UNSPECIFIED_TIMEZONE) && (Node->Info->CreateTime.Month >= 1 && Node->Info->CreateTime.Month <= 12)) { // From 8d3f428109623096cb8845779cdf9dc44949b8e9 Mon Sep 17 00:00:00 2001 From: Marvin Haeuser Date: Sun, 20 Oct 2019 20:08:33 +0800 Subject: [PATCH 030/384] ShellPkg/Ls: Return empty content for all empty folders REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2296 Currently, when 'ls' is run on an entirely empty directory (this includes not having '.' and '..'), the output is always 'File not found'. For when not filtering its children, this patch rather displays the usual header and footer. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Marvin Haeuser Reviewed-by: Zhichao Gao --- .../Library/UefiShellLevel2CommandsLib/Ls.c | 33 ++++++++++++++++--- 1 file changed, 28 insertions(+), 5 deletions(-) diff --git a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c index 1a65f60c3b4..da2b1acab47 100644 --- a/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c +++ b/ShellPkg/Library/UefiShellLevel2CommandsLib/Ls.c @@ -417,6 +417,8 @@ FileTimeToLocalTime ( @param[in] Found Set to TRUE, if anyone were found. @param[in] Count The count of bits enabled in Attribs. @param[in] TimeZone The current time zone offset. + @param[in] ListUnfiltered TRUE to request listing the directory contents + unfiltered. @retval SHELL_SUCCESS the printing was sucessful. **/ @@ -429,7 +431,8 @@ PrintLsOutput( IN CONST CHAR16 *SearchString, IN BOOLEAN *Found, IN CONST UINTN Count, - IN CONST INT16 TimeZone + IN CONST INT16 TimeZone, + IN CONST BOOLEAN ListUnfiltered ) { EFI_STATUS Status; @@ -555,7 +558,7 @@ PrintLsOutput( HeaderPrinted = TRUE; } - if (!Sfo && ShellStatus != SHELL_ABORTED) { + if (!Sfo && ShellStatus != SHELL_ABORTED && HeaderPrinted) { PrintNonSfoFooter(FileCount, FileSize, DirCount); } } @@ -602,7 +605,8 @@ PrintLsOutput( SearchString, &FoundOne, Count, - TimeZone); + TimeZone, + FALSE); // // Since it's running recursively, we have to break immediately when returned SHELL_ABORTED @@ -619,7 +623,21 @@ PrintLsOutput( ShellCloseFileMetaArg(&ListHead); if (Found == NULL && !FoundOne) { - return (SHELL_NOT_FOUND); + if (ListUnfiltered) { + // + // When running "ls" without any filtering request, avoid outputing + // "File not found" when the directory is entirely empty, but print + // header and footer stating "0 File(s), 0 Dir(s)". + // + if (!Sfo) { + PrintNonSfoHeader (RootPath); + if (ShellStatus != SHELL_ABORTED) { + PrintNonSfoFooter (FileCount, FileSize, DirCount); + } + } + } else { + return (SHELL_NOT_FOUND); + } } if (Found != NULL) { @@ -662,6 +680,7 @@ ShellCommandRunLs ( UINTN Size; EFI_TIME TheTime; CHAR16 *SearchString; + BOOLEAN ListUnfiltered; Size = 0; FullPath = NULL; @@ -673,6 +692,7 @@ ShellCommandRunLs ( SearchString = NULL; CurDir = NULL; Count = 0; + ListUnfiltered = FALSE; // // initialize the shell lib (we must be in non-auto-init...) @@ -768,6 +788,7 @@ ShellCommandRunLs ( ShellStatus = SHELL_NOT_FOUND; ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_GEN_NO_CWD), gShellLevel2HiiHandle, L"ls"); } + ListUnfiltered = TRUE; // // Copy to the 2 strings for starting path and file search string // @@ -808,6 +829,7 @@ ShellCommandRunLs ( // // is listing ends with a directory, then we list all files in that directory // + ListUnfiltered = TRUE; StrnCatGrow(&SearchString, NULL, L"*", 0); } else { // @@ -839,7 +861,8 @@ ShellCommandRunLs ( SearchString, NULL, Count, - TheTime.TimeZone + TheTime.TimeZone, + ListUnfiltered ); if (ShellStatus == SHELL_NOT_FOUND) { ShellPrintHiiEx(-1, -1, NULL, STRING_TOKEN (STR_LS_FILE_NOT_FOUND), gShellLevel2HiiHandle, L"ls", FullPath); From 54d1e76f4e17255080f083b155cee8c6678d8175 Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Wed, 23 Oct 2019 14:23:38 +0800 Subject: [PATCH 031/384] UefiCpuPkg/MpInitLib: Set X2ApicEnable flag from BSP Today's logic sets X2ApicEnable flag in each AP's initialization path when InitFlag == ApInitConfig. Since all CPUs update the same global data, a spin-lock is used to avoid modifications from multiple CPUs happen at the same time. The spin-lock causes two problems: 1. Potential performance downgrade. 2. Undefined behavior when improper timer lib is used. For example we saw certain platforms used AcpiTimerLib from PcAtChipsetPkg and that library depends on retrieving PeiServices from idtr. But in fact AP's (idtr - 4) doesn't point to PeiServices. The patch simplifies the code to let BSP set the X2ApicEnable flag so the spin-lock acquisition from AP is not needed any more. Signed-off-by: Ray Ni Reviewed-by: Eric Dong Acked-by: Laszlo Ersek --- UefiCpuPkg/Library/MpInitLib/MpLib.c | 25 ++++++++++++++++--------- 1 file changed, 16 insertions(+), 9 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index 622b70ca3c4..8f62a8d9655 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -458,6 +458,7 @@ CollectProcessorCount ( ) { UINTN Index; + CPU_INFO_IN_HOB *CpuInfoInHob; // // Send 1st broadcast IPI to APs to wakeup APs @@ -474,12 +475,27 @@ CollectProcessorCount ( CpuPause (); } + + // + // Enable x2APIC mode if + // 1. Number of CPU is greater than 255; or + // 2. There are any logical processors reporting an Initial APIC ID of 255 or greater. + // if (CpuMpData->CpuCount > 255) { // // If there are more than 255 processor found, force to enable X2APIC // CpuMpData->X2ApicEnable = TRUE; + } else { + CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob; + for (Index = 0; Index < CpuMpData->CpuCount; Index++) { + if (CpuInfoInHob[Index].InitialApicId >= 0xFF) { + CpuMpData->X2ApicEnable = TRUE; + break; + } + } } + if (CpuMpData->X2ApicEnable) { DEBUG ((DEBUG_INFO, "Force x2APIC mode!\n")); // @@ -541,15 +557,6 @@ InitializeApData ( CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE; CpuMpData->CpuData[ProcessorNumber].CpuHealthy = (BistData == 0) ? TRUE : FALSE; - if (CpuInfoInHob[ProcessorNumber].InitialApicId >= 0xFF) { - // - // Set x2APIC mode if there are any logical processor reporting - // an Initial APIC ID of 255 or greater. - // - AcquireSpinLock(&CpuMpData->MpLock); - CpuMpData->X2ApicEnable = TRUE; - ReleaseSpinLock(&CpuMpData->MpLock); - } InitializeSpinLock(&CpuMpData->CpuData[ProcessorNumber].ApLock); SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle); From fe3ca5fd2518e63338c74df05f508fa81baab2d7 Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Wed, 23 Oct 2019 14:54:57 +0800 Subject: [PATCH 032/384] UefiCpuPkg/MpInitLib: Remove global variable X2ApicEnable MpInitLib sets X2ApicEnable in two places. 1. CollectProcessorCount() This function is called when MpInitLibInitialize() hasn't been called before. It sets X2ApicEnable and later in the same function it configures all CPUs to operate in X2 APIC mode. 2. MpInitLibInitialize() The X2ApicEnable setting happens when this function is called in second time. But after that setting, no code consumes that flag. With the above analysis and with the purpose of simplifying the code, the X2ApicEnable in #1 is changed to local variable and the #2 can be changed to remove the setting of X2ApicEnable. Signed-off-by: Ray Ni Reviewed-by: Eric Dong Reviewed-by: Laszlo Ersek --- UefiCpuPkg/Library/MpInitLib/MpLib.c | 14 ++++++-------- UefiCpuPkg/Library/MpInitLib/MpLib.h | 1 - 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index 8f62a8d9655..49be5d5385d 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -459,12 +459,12 @@ CollectProcessorCount ( { UINTN Index; CPU_INFO_IN_HOB *CpuInfoInHob; + BOOLEAN X2Apic; // // Send 1st broadcast IPI to APs to wakeup APs // - CpuMpData->InitFlag = ApInitConfig; - CpuMpData->X2ApicEnable = FALSE; + CpuMpData->InitFlag = ApInitConfig; WakeUpAP (CpuMpData, TRUE, 0, NULL, NULL, TRUE); CpuMpData->InitFlag = ApInitDone; ASSERT (CpuMpData->CpuCount <= PcdGet32 (PcdCpuMaxLogicalProcessorNumber)); @@ -481,22 +481,23 @@ CollectProcessorCount ( // 1. Number of CPU is greater than 255; or // 2. There are any logical processors reporting an Initial APIC ID of 255 or greater. // + X2Apic = FALSE; if (CpuMpData->CpuCount > 255) { // // If there are more than 255 processor found, force to enable X2APIC // - CpuMpData->X2ApicEnable = TRUE; + X2Apic = TRUE; } else { CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob; for (Index = 0; Index < CpuMpData->CpuCount; Index++) { if (CpuInfoInHob[Index].InitialApicId >= 0xFF) { - CpuMpData->X2ApicEnable = TRUE; + X2Apic = TRUE; break; } } } - if (CpuMpData->X2ApicEnable) { + if (X2Apic) { DEBUG ((DEBUG_INFO, "Force x2APIC mode!\n")); // // Wakeup all APs to enable x2APIC mode @@ -1780,9 +1781,6 @@ MpInitLibInitialize ( CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob; for (Index = 0; Index < CpuMpData->CpuCount; Index++) { InitializeSpinLock(&CpuMpData->CpuData[Index].ApLock); - if (CpuInfoInHob[Index].InitialApicId >= 255 || Index > 254) { - CpuMpData->X2ApicEnable = TRUE; - } CpuMpData->CpuData[Index].CpuHealthy = (CpuInfoInHob[Index].Health == 0)? TRUE:FALSE; CpuMpData->CpuData[Index].ApFunction = 0; CopyMem (&CpuMpData->CpuData[Index].VolatileRegisters, &VolatileRegisters, sizeof (CPU_VOLATILE_REGISTERS)); diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 107872b3679..8fa07b12c5e 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -227,7 +227,6 @@ struct _CPU_MP_DATA { UINTN **FailedCpuList; AP_INIT_STATE InitFlag; - BOOLEAN X2ApicEnable; BOOLEAN SwitchBspFlag; UINTN NewBspNumber; CPU_EXCHANGE_ROLE_INFO BSPInfo; From 1bcc65b9a1408cf445b7b3f9499b27d9c235db71 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Mon, 21 Oct 2019 15:53:42 +0800 Subject: [PATCH 033/384] CryptoPkg: Upgrade OpenSSL to 1.1.1d Upgrade openssl from 1.1.1b to 1.1.1d. Something needs to be noticed is that, there is a bug existing in the released 1_1_1d version(894da2fb7ed5d314ee5c2fc9fd2d9b8b74111596), which causes build failure. So we switch the code base to a usable version, which is 2 commits later than the stable tag. Now we use the version c3656cc594daac8167721dde7220f0e59ae146fc. This log is to fix the build failure. https://bugzilla.tianocore.org/show_bug.cgi?id=2226 Besides, the absense of "DSO_NONE" in dso_conf.h causes build failure in OvmfPkg. So update process_files.pl to generate information from "crypto/include/internal/dso_conf.h.in". shm.h and utsname.h are added to avoid GCC build failure. Cc: Jian J Wang Cc: Xiaoyu Lu Cc: Liming Gao Signed-off-by: Shenglei Zhang Reviewed-by: Jian J Wang Reviewed-by: Laszlo Ersek Tested-by: Laszlo Ersek --- CryptoPkg/Library/Include/internal/dso_conf.h | 16 ++++++++++++++++ CryptoPkg/Library/Include/sys/shm.h | 9 +++++++++ CryptoPkg/Library/Include/sys/utsname.h | 9 +++++++++ CryptoPkg/Library/OpensslLib/openssl | 2 +- CryptoPkg/Library/OpensslLib/process_files.pl | 17 +++++++++++++++-- 5 files changed, 50 insertions(+), 3 deletions(-) create mode 100644 CryptoPkg/Library/Include/sys/shm.h create mode 100644 CryptoPkg/Library/Include/sys/utsname.h diff --git a/CryptoPkg/Library/Include/internal/dso_conf.h b/CryptoPkg/Library/Include/internal/dso_conf.h index e69de29bb2d..43c891588bc 100644 --- a/CryptoPkg/Library/Include/internal/dso_conf.h +++ b/CryptoPkg/Library/Include/internal/dso_conf.h @@ -0,0 +1,16 @@ +/* WARNING: do not edit! */ +/* Generated from crypto/include/internal/dso_conf.h.in */ +/* + * Copyright 2016-2019 The OpenSSL Project Authors. All Rights Reserved. + * + * Licensed under the OpenSSL license (the "License"). You may not use + * this file except in compliance with the License. You can obtain a copy + * in the file LICENSE in the source distribution or at + * https://www.openssl.org/source/license.html + */ + +#ifndef HEADER_DSO_CONF_H +# define HEADER_DSO_CONF_H +# define DSO_NONE +# define DSO_EXTENSION ".so" +#endif diff --git a/CryptoPkg/Library/Include/sys/shm.h b/CryptoPkg/Library/Include/sys/shm.h new file mode 100644 index 00000000000..dc0b8e81c8b --- /dev/null +++ b/CryptoPkg/Library/Include/sys/shm.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building the third-party cryptographic library. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include diff --git a/CryptoPkg/Library/Include/sys/utsname.h b/CryptoPkg/Library/Include/sys/utsname.h new file mode 100644 index 00000000000..dc0b8e81c8b --- /dev/null +++ b/CryptoPkg/Library/Include/sys/utsname.h @@ -0,0 +1,9 @@ +/** @file + Include file to support building the third-party cryptographic library. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include diff --git a/CryptoPkg/Library/OpensslLib/openssl b/CryptoPkg/Library/OpensslLib/openssl index 50eaac9f333..c3656cc594d 160000 --- a/CryptoPkg/Library/OpensslLib/openssl +++ b/CryptoPkg/Library/OpensslLib/openssl @@ -1 +1 @@ -Subproject commit 50eaac9f3337667259de725451f201e784599687 +Subproject commit c3656cc594daac8167721dde7220f0e59ae146fc diff --git a/CryptoPkg/Library/OpensslLib/process_files.pl b/CryptoPkg/Library/OpensslLib/process_files.pl index 4fe54cd808a..bbcfa0d0e70 100755 --- a/CryptoPkg/Library/OpensslLib/process_files.pl +++ b/CryptoPkg/Library/OpensslLib/process_files.pl @@ -2,7 +2,7 @@ # # This script runs the OpenSSL Configure script, then processes the # resulting file list into our local OpensslLib[Crypto].inf and also -# takes a copy of opensslconf.h. +# takes copies of opensslconf.h and dso_conf.h. # # This only needs to be done once by a developer when updating to a # new version of OpenSSL (or changing options, etc.). Normal users @@ -106,6 +106,14 @@ BEGIN ) == 0 || die "Failed to generate opensslconf.h!\n"; + # Generate dso_conf.h per config data + system( + "perl -I. -Mconfigdata util/dofile.pl " . + "crypto/include/internal/dso_conf.h.in " . + "> include/internal/dso_conf.h" + ) == 0 || + die "Failed to generate dso_conf.h!\n"; + chdir($basedir) || die "Cannot change to base directory \"" . $basedir . "\""; @@ -249,12 +257,17 @@ BEGIN print "Done!"; # -# Copy opensslconf.h generated from OpenSSL Configuration +# Copy opensslconf.h and dso_conf.h generated from OpenSSL Configuration # print "\n--> Duplicating opensslconf.h into Include/openssl ... "; copy($OPENSSL_PATH . "/include/openssl/opensslconf.h", $OPENSSL_PATH . "/../../Include/openssl/") || die "Cannot copy opensslconf.h!"; +print "Done!"; +print "\n--> Duplicating dso_conf.h into Include/internal ... "; +copy($OPENSSL_PATH . "/include/internal/dso_conf.h", + $OPENSSL_PATH . "/../../Include/internal/") || + die "Cannot copy dso_conf.h!"; print "Done!\n"; print "\nProcessing Files Done!\n"; From dd6d07bda9e7ab3e4080d7be8bc140ded9a93eed Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 8 Oct 2019 13:58:18 +0800 Subject: [PATCH 034/384] ShellPkg/Shell/FileHandleWrappers.c: Add check for MemFile->Buffer Add check for MemFile->Buffer. Return EFI_OUT_OF_RESOURCES if MemFile->Buffer is NULL. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Shenglei Zhang Reviewed-by: Zhichao Gao --- ShellPkg/Application/Shell/FileHandleWrappers.c | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ShellPkg/Application/Shell/FileHandleWrappers.c b/ShellPkg/Application/Shell/FileHandleWrappers.c index 587556c4249..2d7bd7bec67 100644 --- a/ShellPkg/Application/Shell/FileHandleWrappers.c +++ b/ShellPkg/Application/Shell/FileHandleWrappers.c @@ -1644,6 +1644,9 @@ FileInterfaceMemWrite( // if ((UINTN)(MemFile->Position + (*BufferSize)) > (UINTN)(MemFile->BufferSize)) { MemFile->Buffer = ReallocatePool((UINTN)(MemFile->BufferSize), (UINTN)(MemFile->BufferSize) + (*BufferSize) + MEM_WRITE_REALLOC_OVERHEAD, MemFile->Buffer); + if (MemFile->Buffer == NULL){ + return EFI_OUT_OF_RESOURCES; + } MemFile->BufferSize += (*BufferSize) + MEM_WRITE_REALLOC_OVERHEAD; } CopyMem(((UINT8*)MemFile->Buffer) + MemFile->Position, Buffer, *BufferSize); @@ -1661,6 +1664,10 @@ FileInterfaceMemWrite( AsciiSPrint(AsciiBuffer, *BufferSize, "%S", Buffer); if ((UINTN)(MemFile->Position + AsciiStrSize(AsciiBuffer)) > (UINTN)(MemFile->BufferSize)) { MemFile->Buffer = ReallocatePool((UINTN)(MemFile->BufferSize), (UINTN)(MemFile->BufferSize) + AsciiStrSize(AsciiBuffer) + MEM_WRITE_REALLOC_OVERHEAD, MemFile->Buffer); + if (MemFile->Buffer == NULL){ + FreePool(AsciiBuffer); + return EFI_OUT_OF_RESOURCES; + } MemFile->BufferSize += AsciiStrSize(AsciiBuffer) + MEM_WRITE_REALLOC_OVERHEAD; } CopyMem(((UINT8*)MemFile->Buffer) + MemFile->Position, AsciiBuffer, AsciiStrSize(AsciiBuffer)); From e34022dcbe64996d0fc8be0b1b8e09ae7134216c Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 10:44:14 +0800 Subject: [PATCH 035/384] MdeModulePkg/HiiDatabaseDxe: ASSERT StringPtr The caller of CompareAndMergeDefaultString has checked that AltCfgResp must contain AltConfigHdr. So we add ASSERT to assume StringPtr is not NULL. Cc: Dandan Bi Cc: Eric Dong Signed-off-by: Shenglei Zhang Reviewed-by: Dandan Bi --- MdeModulePkg/Universal/HiiDatabaseDxe/ConfigRouting.c | 1 + 1 file changed, 1 insertion(+) diff --git a/MdeModulePkg/Universal/HiiDatabaseDxe/ConfigRouting.c b/MdeModulePkg/Universal/HiiDatabaseDxe/ConfigRouting.c index 71ea25bc19b..2cad6d29f45 100644 --- a/MdeModulePkg/Universal/HiiDatabaseDxe/ConfigRouting.c +++ b/MdeModulePkg/Universal/HiiDatabaseDxe/ConfigRouting.c @@ -909,6 +909,7 @@ CompareAndMergeDefaultString ( // To find the with AltConfigHdr in AltCfgResp, ignore other which follow it. // StringPtr = StrStr (*AltCfgResp, AltConfigHdr); + ASSERT (StringPtr != NULL); StringPtrNext = StrStr (StringPtr + 1, L"&GUID"); if (StringPtrNext != NULL) { TempCharA = *StringPtrNext; From 3fb7e094efc87c46fffb2d755183bbe70da09396 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 10:56:05 +0800 Subject: [PATCH 036/384] MdeModulePkg/EsrtDxe: Add check for EsrtRepository EsrtRepository might be NULL. So return EFI_OUT_OF_RESOURCES when it is NULL. Cc: Hao A Wu Cc: Liming Gao Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c b/MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c index f48125382db..fff17b98fa3 100644 --- a/MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c +++ b/MdeModulePkg/Universal/EsrtDxe/EsrtImpl.c @@ -239,6 +239,11 @@ DeleteEsrtEntry( goto EXIT; } + if (EsrtRepository == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + if ((RepositorySize % sizeof(EFI_SYSTEM_RESOURCE_ENTRY)) != 0) { DEBUG((EFI_D_ERROR, "Repository Corrupt. Need to rebuild Repository.\n")); // @@ -332,6 +337,11 @@ UpdateEsrtEntry( &RepositorySize ); + if (EsrtRepository == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + if (!EFI_ERROR(Status)) { // // if exist, update Esrt cache repository From 0c1541d457832d3f68158cf61d21c30fe32bb885 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 11:36:34 +0800 Subject: [PATCH 037/384] MdeModulePkg/SetupBrowserDxe: ASSERT GetBufferForValue(&Value) Before called by GetBufferForValue(), Value has already been called function IsTypeInBuffer to make sure the value must be buffer type. So GetBufferForValue can not return NULL. This commit adds ASSERT to assume (GetBufferForValue (&Value) is not NULL. Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Shenglei Zhang Reviewed-by: Dandan Bi --- MdeModulePkg/Universal/SetupBrowserDxe/Expression.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c b/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c index 7f4929c2fcd..d273d2aac3d 100644 --- a/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c +++ b/MdeModulePkg/Universal/SetupBrowserDxe/Expression.c @@ -1281,7 +1281,10 @@ IfrToUint ( Result->Type = EFI_IFR_TYPE_UNDEFINED; return EFI_SUCCESS; } + + ASSERT (GetBufferForValue (&Value) != NULL); Result->Value.u64 = *(UINT64*) GetBufferForValue (&Value); + if (Value.Type == EFI_IFR_TYPE_BUFFER) { FreePool (Value.Buffer); } From a7d69b6aafaae452e4b54d70c113de10c45dd54b Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Tue, 15 Oct 2019 10:30:27 +0800 Subject: [PATCH 038/384] MdeModulePkg/EbcDebugger: Add check for Entry and RetEntry Entry and RetEntry might be NULL before used. Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Shenglei Zhang Reviewed-by: Hao A Wu --- MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdSymbol.c | 2 +- MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbSymbol.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdSymbol.c b/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdSymbol.c index 8e305e4243a..7b453fa98c2 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdSymbol.c +++ b/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbCmdSymbol.c @@ -143,7 +143,7 @@ DebuggerDisplaySymbolAccrodingToAddress ( // Find the nearest symbol address // CandidateAddress = EbdFindSymbolAddress (Address, EdbMatchSymbolTypeNearestAddress, &Object, &Entry); - if (CandidateAddress == 0 || CandidateAddress == (UINTN) -1) { + if (CandidateAddress == 0 || CandidateAddress == (UINTN) -1 || Entry == NULL) { EDBPrint (L"Symbole at Address not found!\n"); return EFI_DEBUG_CONTINUE; } else if (Address != CandidateAddress) { diff --git a/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbSymbol.c b/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbSymbol.c index 85cc275c114..90a9b9fbd7e 100644 --- a/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbSymbol.c +++ b/MdeModulePkg/Universal/EbcDxe/EbcDebugger/EdbSymbol.c @@ -2062,7 +2062,7 @@ EdbPrintSource ( &RetObject, &RetEntry ); - if (SymbolAddress == 0) { + if (SymbolAddress == 0 || RetEntry == NULL) { return 0 ; } From 20a27a641b8d7632542e64749c355850a567421d Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 23 Sep 2019 17:32:07 -0700 Subject: [PATCH 039/384] MdeModulePkg/Variable: Consolidate common parsing functions This change moves the following functions into a dedicated file so they may be used in other variable files as needed. These are commonly needed for basic variable data structure parsing operations. The functions are grouped together in VariableParsing.c to support cohesiveness for these operations in the file. Furthermore, it reduces the overall size of the common Variable.c file. * DataSizeOfVariable () * FindVariableEx () * GetEndPointer () * GetNextVariablePtr () * GetStartPointer () * GetVariableDataOffset () * GetVariableDataPtr () * GetVariableHeaderSize () * GetVariableNamePtr () * GetVariableStoreStatus () * GetVendorGuidPtr () * IsValidVariableHeader () * NameSizeOfVariable () * SetDataSizeOfVariable () * SetNameSizeOfVariable () * UpdateVariableInfo () * VariableCompareTimeStampInternal () * VariableServiceGetNextVariableInternal () Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../Universal/Variable/RuntimeDxe/Variable.c | 726 +---------------- .../Universal/Variable/RuntimeDxe/Variable.h | 119 --- .../Variable/RuntimeDxe/VariableExLib.c | 3 +- .../Variable/RuntimeDxe/VariableParsing.c | 731 ++++++++++++++++++ .../Variable/RuntimeDxe/VariableParsing.h | 306 ++++++++ .../RuntimeDxe/VariableRuntimeDxe.inf | 2 + .../Variable/RuntimeDxe/VariableSmm.c | 1 + .../Variable/RuntimeDxe/VariableSmm.inf | 2 + .../RuntimeDxe/VariableStandaloneMm.inf | 2 + 9 files changed, 1047 insertions(+), 845 deletions(-) create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index f32c9c2808a..76536308e6a 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -23,6 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Variable.h" +#include "VariableParsing.h" VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal; @@ -92,131 +93,6 @@ AUTH_VAR_LIB_CONTEXT_IN mAuthContextIn = { AUTH_VAR_LIB_CONTEXT_OUT mAuthContextOut; -/** - Routine used to track statistical information about variable usage. - The data is stored in the EFI system table so it can be accessed later. - VariableInfo.efi can dump out the table. Only Boot Services variable - accesses are tracked by this code. The PcdVariableCollectStatistics - build flag controls if this feature is enabled. - - A read that hits in the cache will have Read and Cache true for - the transaction. Data is allocated by this routine, but never - freed. - - @param[in] VariableName Name of the Variable to track. - @param[in] VendorGuid Guid of the Variable to track. - @param[in] Volatile TRUE if volatile FALSE if non-volatile. - @param[in] Read TRUE if GetVariable() was called. - @param[in] Write TRUE if SetVariable() was called. - @param[in] Delete TRUE if deleted via SetVariable(). - @param[in] Cache TRUE for a cache hit. - -**/ -VOID -UpdateVariableInfo ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN BOOLEAN Volatile, - IN BOOLEAN Read, - IN BOOLEAN Write, - IN BOOLEAN Delete, - IN BOOLEAN Cache - ) -{ - VARIABLE_INFO_ENTRY *Entry; - - if (FeaturePcdGet (PcdVariableCollectStatistics)) { - - if (AtRuntime ()) { - // Don't collect statistics at runtime. - return; - } - - if (gVariableInfo == NULL) { - // - // On the first call allocate a entry and place a pointer to it in - // the EFI System Table. - // - gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); - ASSERT (gVariableInfo != NULL); - - CopyGuid (&gVariableInfo->VendorGuid, VendorGuid); - gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName)); - ASSERT (gVariableInfo->Name != NULL); - StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); - gVariableInfo->Volatile = Volatile; - } - - - for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) { - if (CompareGuid (VendorGuid, &Entry->VendorGuid)) { - if (StrCmp (VariableName, Entry->Name) == 0) { - if (Read) { - Entry->ReadCount++; - } - if (Write) { - Entry->WriteCount++; - } - if (Delete) { - Entry->DeleteCount++; - } - if (Cache) { - Entry->CacheCount++; - } - - return; - } - } - - if (Entry->Next == NULL) { - // - // If the entry is not in the table add it. - // Next iteration of the loop will fill in the data. - // - Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); - ASSERT (Entry->Next != NULL); - - CopyGuid (&Entry->Next->VendorGuid, VendorGuid); - Entry->Next->Name = AllocateZeroPool (StrSize (VariableName)); - ASSERT (Entry->Next->Name != NULL); - StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); - Entry->Next->Volatile = Volatile; - } - - } - } -} - - -/** - - This code checks if variable header is valid or not. - - @param Variable Pointer to the Variable Header. - @param VariableStoreEnd Pointer to the Variable Store End. - - @retval TRUE Variable header is valid. - @retval FALSE Variable header is not valid. - -**/ -BOOLEAN -IsValidVariableHeader ( - IN VARIABLE_HEADER *Variable, - IN VARIABLE_HEADER *VariableStoreEnd - ) -{ - if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) { - // - // Variable is NULL or has reached the end of variable store, - // or the StartId is not correct. - // - return FALSE; - } - - return TRUE; -} - - /** This function writes data to the FWH at the correct LBA even if the LBAs @@ -376,345 +252,6 @@ UpdateVariableStore ( return EFI_SUCCESS; } - -/** - - This code gets the current status of Variable Store. - - @param VarStoreHeader Pointer to the Variable Store Header. - - @retval EfiRaw Variable store status is raw. - @retval EfiValid Variable store status is valid. - @retval EfiInvalid Variable store status is invalid. - -**/ -VARIABLE_STORE_STATUS -GetVariableStoreStatus ( - IN VARIABLE_STORE_HEADER *VarStoreHeader - ) -{ - if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) || - CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) && - VarStoreHeader->Format == VARIABLE_STORE_FORMATTED && - VarStoreHeader->State == VARIABLE_STORE_HEALTHY - ) { - - return EfiValid; - } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff && - ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff && - ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff && - ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff && - VarStoreHeader->Size == 0xffffffff && - VarStoreHeader->Format == 0xff && - VarStoreHeader->State == 0xff - ) { - - return EfiRaw; - } else { - return EfiInvalid; - } -} - -/** - This code gets the size of variable header. - - @return Size of variable header in bytes in type UINTN. - -**/ -UINTN -GetVariableHeaderSize ( - VOID - ) -{ - UINTN Value; - - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - Value = sizeof (AUTHENTICATED_VARIABLE_HEADER); - } else { - Value = sizeof (VARIABLE_HEADER); - } - - return Value; -} - -/** - - This code gets the size of name of variable. - - @param Variable Pointer to the Variable Header. - - @return UINTN Size of variable in bytes. - -**/ -UINTN -NameSizeOfVariable ( - IN VARIABLE_HEADER *Variable - ) -{ - AUTHENTICATED_VARIABLE_HEADER *AuthVariable; - - AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - if (AuthVariable->State == (UINT8) (-1) || - AuthVariable->DataSize == (UINT32) (-1) || - AuthVariable->NameSize == (UINT32) (-1) || - AuthVariable->Attributes == (UINT32) (-1)) { - return 0; - } - return (UINTN) AuthVariable->NameSize; - } else { - if (Variable->State == (UINT8) (-1) || - Variable->DataSize == (UINT32) (-1) || - Variable->NameSize == (UINT32) (-1) || - Variable->Attributes == (UINT32) (-1)) { - return 0; - } - return (UINTN) Variable->NameSize; - } -} - -/** - This code sets the size of name of variable. - - @param[in] Variable Pointer to the Variable Header. - @param[in] NameSize Name size to set. - -**/ -VOID -SetNameSizeOfVariable ( - IN VARIABLE_HEADER *Variable, - IN UINTN NameSize - ) -{ - AUTHENTICATED_VARIABLE_HEADER *AuthVariable; - - AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - AuthVariable->NameSize = (UINT32) NameSize; - } else { - Variable->NameSize = (UINT32) NameSize; - } -} - -/** - - This code gets the size of variable data. - - @param Variable Pointer to the Variable Header. - - @return Size of variable in bytes. - -**/ -UINTN -DataSizeOfVariable ( - IN VARIABLE_HEADER *Variable - ) -{ - AUTHENTICATED_VARIABLE_HEADER *AuthVariable; - - AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - if (AuthVariable->State == (UINT8) (-1) || - AuthVariable->DataSize == (UINT32) (-1) || - AuthVariable->NameSize == (UINT32) (-1) || - AuthVariable->Attributes == (UINT32) (-1)) { - return 0; - } - return (UINTN) AuthVariable->DataSize; - } else { - if (Variable->State == (UINT8) (-1) || - Variable->DataSize == (UINT32) (-1) || - Variable->NameSize == (UINT32) (-1) || - Variable->Attributes == (UINT32) (-1)) { - return 0; - } - return (UINTN) Variable->DataSize; - } -} - -/** - This code sets the size of variable data. - - @param[in] Variable Pointer to the Variable Header. - @param[in] DataSize Data size to set. - -**/ -VOID -SetDataSizeOfVariable ( - IN VARIABLE_HEADER *Variable, - IN UINTN DataSize - ) -{ - AUTHENTICATED_VARIABLE_HEADER *AuthVariable; - - AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - AuthVariable->DataSize = (UINT32) DataSize; - } else { - Variable->DataSize = (UINT32) DataSize; - } -} - -/** - - This code gets the pointer to the variable name. - - @param Variable Pointer to the Variable Header. - - @return Pointer to Variable Name which is Unicode encoding. - -**/ -CHAR16 * -GetVariableNamePtr ( - IN VARIABLE_HEADER *Variable - ) -{ - return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ()); -} - -/** - This code gets the pointer to the variable guid. - - @param Variable Pointer to the Variable Header. - - @return A EFI_GUID* pointer to Vendor Guid. - -**/ -EFI_GUID * -GetVendorGuidPtr ( - IN VARIABLE_HEADER *Variable - ) -{ - AUTHENTICATED_VARIABLE_HEADER *AuthVariable; - - AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { - return &AuthVariable->VendorGuid; - } else { - return &Variable->VendorGuid; - } -} - -/** - - This code gets the pointer to the variable data. - - @param Variable Pointer to the Variable Header. - - @return Pointer to Variable Data. - -**/ -UINT8 * -GetVariableDataPtr ( - IN VARIABLE_HEADER *Variable - ) -{ - UINTN Value; - - // - // Be careful about pad size for alignment. - // - Value = (UINTN) GetVariableNamePtr (Variable); - Value += NameSizeOfVariable (Variable); - Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); - - return (UINT8 *) Value; -} - -/** - This code gets the variable data offset related to variable header. - - @param Variable Pointer to the Variable Header. - - @return Variable Data offset. - -**/ -UINTN -GetVariableDataOffset ( - IN VARIABLE_HEADER *Variable - ) -{ - UINTN Value; - - // - // Be careful about pad size for alignment - // - Value = GetVariableHeaderSize (); - Value += NameSizeOfVariable (Variable); - Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); - - return Value; -} - -/** - - This code gets the pointer to the next variable header. - - @param Variable Pointer to the Variable Header. - - @return Pointer to next variable header. - -**/ -VARIABLE_HEADER * -GetNextVariablePtr ( - IN VARIABLE_HEADER *Variable - ) -{ - UINTN Value; - - Value = (UINTN) GetVariableDataPtr (Variable); - Value += DataSizeOfVariable (Variable); - Value += GET_PAD_SIZE (DataSizeOfVariable (Variable)); - - // - // Be careful about pad size for alignment. - // - return (VARIABLE_HEADER *) HEADER_ALIGN (Value); -} - -/** - - Gets the pointer to the first variable header in given variable store area. - - @param VarStoreHeader Pointer to the Variable Store Header. - - @return Pointer to the first variable header. - -**/ -VARIABLE_HEADER * -GetStartPointer ( - IN VARIABLE_STORE_HEADER *VarStoreHeader - ) -{ - // - // The start of variable store. - // - return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1); -} - -/** - - Gets the pointer to the end of the variable storage area. - - This function gets pointer to the end of the variable storage - area, according to the input variable store header. - - @param VarStoreHeader Pointer to the Variable Store Header. - - @return Pointer to the end of the variable storage area. - -**/ -VARIABLE_HEADER * -GetEndPointer ( - IN VARIABLE_STORE_HEADER *VarStoreHeader - ) -{ - // - // The end of variable store - // - return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size); -} - /** Record variable error flag. @@ -1228,75 +765,6 @@ Reclaim ( return Status; } -/** - Find the variable in the specified variable store. - - @param[in] VariableName Name of the variable to be found - @param[in] VendorGuid Vendor GUID to be found. - @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute - check at runtime when searching variable. - @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. - - @retval EFI_SUCCESS Variable found successfully - @retval EFI_NOT_FOUND Variable not found -**/ -EFI_STATUS -FindVariableEx ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - IN BOOLEAN IgnoreRtCheck, - IN OUT VARIABLE_POINTER_TRACK *PtrTrack - ) -{ - VARIABLE_HEADER *InDeletedVariable; - VOID *Point; - - PtrTrack->InDeletedTransitionPtr = NULL; - - // - // Find the variable by walk through HOB, volatile and non-volatile variable store. - // - InDeletedVariable = NULL; - - for ( PtrTrack->CurrPtr = PtrTrack->StartPtr - ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr) - ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr) - ) { - if (PtrTrack->CurrPtr->State == VAR_ADDED || - PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) - ) { - if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { - if (VariableName[0] == 0) { - if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - InDeletedVariable = PtrTrack->CurrPtr; - } else { - PtrTrack->InDeletedTransitionPtr = InDeletedVariable; - return EFI_SUCCESS; - } - } else { - if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) { - Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr); - - ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0); - if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) { - if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - InDeletedVariable = PtrTrack->CurrPtr; - } else { - PtrTrack->InDeletedTransitionPtr = InDeletedVariable; - return EFI_SUCCESS; - } - } - } - } - } - } - } - - PtrTrack->CurrPtr = InDeletedVariable; - return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS; -} - - /** Finds variable in storage blocks of volatile and non-volatile storage areas. @@ -2078,38 +1546,6 @@ AutoUpdateLangVariable ( } } -/** - Compare two EFI_TIME data. - - - @param FirstTime A pointer to the first EFI_TIME data. - @param SecondTime A pointer to the second EFI_TIME data. - - @retval TRUE The FirstTime is not later than the SecondTime. - @retval FALSE The FirstTime is later than the SecondTime. - -**/ -BOOLEAN -VariableCompareTimeStampInternal ( - IN EFI_TIME *FirstTime, - IN EFI_TIME *SecondTime - ) -{ - if (FirstTime->Year != SecondTime->Year) { - return (BOOLEAN) (FirstTime->Year < SecondTime->Year); - } else if (FirstTime->Month != SecondTime->Month) { - return (BOOLEAN) (FirstTime->Month < SecondTime->Month); - } else if (FirstTime->Day != SecondTime->Day) { - return (BOOLEAN) (FirstTime->Day < SecondTime->Day); - } else if (FirstTime->Hour != SecondTime->Hour) { - return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour); - } else if (FirstTime->Minute != SecondTime->Minute) { - return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute); - } - - return (BOOLEAN) (FirstTime->Second <= SecondTime->Second); -} - /** Update the variable region with Variable information. If EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS is set, index of associated public key is needed. @@ -2885,166 +2321,6 @@ VariableServiceGetVariable ( return Status; } -/** - This code Finds the Next available variable. - - Caution: This function may receive untrusted input. - This function may be invoked in SMM mode. This function will do basic validation, before parse the data. - - @param[in] VariableName Pointer to variable name. - @param[in] VendorGuid Variable Vendor Guid. - @param[out] VariablePtr Pointer to variable header address. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_NOT_FOUND The next variable was not found. - @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. - @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and - GUID of an existing variable. - -**/ -EFI_STATUS -EFIAPI -VariableServiceGetNextVariableInternal ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - OUT VARIABLE_HEADER **VariablePtr - ) -{ - VARIABLE_STORE_TYPE Type; - VARIABLE_POINTER_TRACK Variable; - VARIABLE_POINTER_TRACK VariableInHob; - VARIABLE_POINTER_TRACK VariablePtrTrack; - EFI_STATUS Status; - VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; - - Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); - if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) { - // - // For VariableName is an empty string, FindVariable() will try to find and return - // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND) - // as no any variable is found, still go to return the error (EFI_NOT_FOUND). - // - if (VariableName[0] != 0) { - // - // For VariableName is not an empty string, and FindVariable() returns error as - // VariableName and VendorGuid are not a name and GUID of an existing variable, - // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER. - // - Status = EFI_INVALID_PARAMETER; - } - goto Done; - } - - if (VariableName[0] != 0) { - // - // If variable name is not NULL, get next variable. - // - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); - } - - // - // 0: Volatile, 1: HOB, 2: Non-Volatile. - // The index and attributes mapping must be kept in this order as FindVariable - // makes use of this mapping to implement search algorithm. - // - VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; - VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; - VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; - - while (TRUE) { - // - // Switch from Volatile to HOB, to Non-Volatile. - // - while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) { - // - // Find current storage index - // - for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) { - if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) { - break; - } - } - ASSERT (Type < VariableStoreTypeMax); - // - // Switch to next storage - // - for (Type++; Type < VariableStoreTypeMax; Type++) { - if (VariableStoreHeader[Type] != NULL) { - break; - } - } - // - // Capture the case that - // 1. current storage is the last one, or - // 2. no further storage - // - if (Type == VariableStoreTypeMax) { - Status = EFI_NOT_FOUND; - goto Done; - } - Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]); - Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]); - Variable.CurrPtr = Variable.StartPtr; - } - - // - // Variable is found - // - if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { - if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { - // - // If it is a IN_DELETED_TRANSITION variable, - // and there is also a same ADDED one at the same time, - // don't return it. - // - VariablePtrTrack.StartPtr = Variable.StartPtr; - VariablePtrTrack.EndPtr = Variable.EndPtr; - Status = FindVariableEx ( - GetVariableNamePtr (Variable.CurrPtr), - GetVendorGuidPtr (Variable.CurrPtr), - FALSE, - &VariablePtrTrack - ); - if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) { - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); - continue; - } - } - - // - // Don't return NV variable when HOB overrides it - // - if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && - (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv])) - ) { - VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]); - VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]); - Status = FindVariableEx ( - GetVariableNamePtr (Variable.CurrPtr), - GetVendorGuidPtr (Variable.CurrPtr), - FALSE, - &VariableInHob - ); - if (!EFI_ERROR (Status)) { - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); - continue; - } - } - - *VariablePtr = Variable.CurrPtr; - Status = EFI_SUCCESS; - goto Done; - } - } - - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); - } - -Done: - return Status; -} - /** This code Finds the Next available variable. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h index 9eac43759fd..fb574b2e328 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h @@ -179,89 +179,6 @@ FindVariable ( IN BOOLEAN IgnoreRtCheck ); -/** - - Gets the pointer to the end of the variable storage area. - - This function gets pointer to the end of the variable storage - area, according to the input variable store header. - - @param VarStoreHeader Pointer to the Variable Store Header. - - @return Pointer to the end of the variable storage area. - -**/ -VARIABLE_HEADER * -GetEndPointer ( - IN VARIABLE_STORE_HEADER *VarStoreHeader - ); - -/** - This code gets the size of variable header. - - @return Size of variable header in bytes in type UINTN. - -**/ -UINTN -GetVariableHeaderSize ( - VOID - ); - -/** - - This code gets the pointer to the variable name. - - @param Variable Pointer to the Variable Header. - - @return Pointer to Variable Name which is Unicode encoding. - -**/ -CHAR16 * -GetVariableNamePtr ( - IN VARIABLE_HEADER *Variable - ); - -/** - This code gets the pointer to the variable guid. - - @param Variable Pointer to the Variable Header. - - @return A EFI_GUID* pointer to Vendor Guid. - -**/ -EFI_GUID * -GetVendorGuidPtr ( - IN VARIABLE_HEADER *Variable - ); - -/** - - This code gets the pointer to the variable data. - - @param Variable Pointer to the Variable Header. - - @return Pointer to Variable Data. - -**/ -UINT8 * -GetVariableDataPtr ( - IN VARIABLE_HEADER *Variable - ); - -/** - - This code gets the size of variable data. - - @param Variable Pointer to the Variable Header. - - @return Size of variable in bytes. - -**/ -UINTN -DataSizeOfVariable ( - IN VARIABLE_HEADER *Variable - ); - /** This function is to check if the remaining variable space is enough to set all Variables from argument list successfully. The purpose of the check @@ -450,17 +367,6 @@ ReclaimForOS( VOID ); -/** - Get non-volatile maximum variable size. - - @return Non-volatile maximum variable size. - -**/ -UINTN -GetNonVolatileMaxVariableSize ( - VOID - ); - /** Get maximum variable size, covering both non-volatile and volatile variables. @@ -546,31 +452,6 @@ VariableServiceGetVariable ( OUT VOID *Data OPTIONAL ); -/** - This code Finds the Next available variable. - - Caution: This function may receive untrusted input. - This function may be invoked in SMM mode. This function will do basic validation, before parse the data. - - @param[in] VariableName Pointer to variable name. - @param[in] VendorGuid Variable Vendor Guid. - @param[out] VariablePtr Pointer to variable header address. - - @retval EFI_SUCCESS The function completed successfully. - @retval EFI_NOT_FOUND The next variable was not found. - @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. - @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and - GUID of an existing variable. - -**/ -EFI_STATUS -EFIAPI -VariableServiceGetNextVariableInternal ( - IN CHAR16 *VariableName, - IN EFI_GUID *VendorGuid, - OUT VARIABLE_HEADER **VariablePtr - ); - /** This code Finds the Next available variable. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c index cb6fcebe2d9..dc78f68fa9e 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c @@ -1,12 +1,13 @@ /** @file Provides variable driver extended services. -Copyright (c) 2015, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Variable.h" +#include "VariableParsing.h" /** Finds variable in storage blocks of volatile and non-volatile storage areas. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c new file mode 100644 index 00000000000..5698a1a5e42 --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c @@ -0,0 +1,731 @@ +/** @file + Functions in this module are associated with variable parsing operations and + are intended to be usable across variable driver source files. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "VariableParsing.h" + +/** + + This code checks if variable header is valid or not. + + @param[in] Variable Pointer to the Variable Header. + @param[in] VariableStoreEnd Pointer to the Variable Store End. + + @retval TRUE Variable header is valid. + @retval FALSE Variable header is not valid. + +**/ +BOOLEAN +IsValidVariableHeader ( + IN VARIABLE_HEADER *Variable, + IN VARIABLE_HEADER *VariableStoreEnd + ) +{ + if ((Variable == NULL) || (Variable >= VariableStoreEnd) || (Variable->StartId != VARIABLE_DATA)) { + // + // Variable is NULL or has reached the end of variable store, + // or the StartId is not correct. + // + return FALSE; + } + + return TRUE; +} + +/** + + This code gets the current status of Variable Store. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @retval EfiRaw Variable store status is raw. + @retval EfiValid Variable store status is valid. + @retval EfiInvalid Variable store status is invalid. + +**/ +VARIABLE_STORE_STATUS +GetVariableStoreStatus ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ) +{ + if ((CompareGuid (&VarStoreHeader->Signature, &gEfiAuthenticatedVariableGuid) || + CompareGuid (&VarStoreHeader->Signature, &gEfiVariableGuid)) && + VarStoreHeader->Format == VARIABLE_STORE_FORMATTED && + VarStoreHeader->State == VARIABLE_STORE_HEALTHY + ) { + + return EfiValid; + } else if (((UINT32 *)(&VarStoreHeader->Signature))[0] == 0xffffffff && + ((UINT32 *)(&VarStoreHeader->Signature))[1] == 0xffffffff && + ((UINT32 *)(&VarStoreHeader->Signature))[2] == 0xffffffff && + ((UINT32 *)(&VarStoreHeader->Signature))[3] == 0xffffffff && + VarStoreHeader->Size == 0xffffffff && + VarStoreHeader->Format == 0xff && + VarStoreHeader->State == 0xff + ) { + + return EfiRaw; + } else { + return EfiInvalid; + } +} + +/** + This code gets the size of variable header. + + @return Size of variable header in bytes in type UINTN. + +**/ +UINTN +GetVariableHeaderSize ( + VOID + ) +{ + UINTN Value; + + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + Value = sizeof (AUTHENTICATED_VARIABLE_HEADER); + } else { + Value = sizeof (VARIABLE_HEADER); + } + + return Value; +} + +/** + + This code gets the size of name of variable. + + @param Variable Pointer to the Variable Header. + + @return UINTN Size of variable in bytes. + +**/ +UINTN +NameSizeOfVariable ( + IN VARIABLE_HEADER *Variable + ) +{ + AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + + AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthVariable->State == (UINT8) (-1) || + AuthVariable->DataSize == (UINT32) (-1) || + AuthVariable->NameSize == (UINT32) (-1) || + AuthVariable->Attributes == (UINT32) (-1)) { + return 0; + } + return (UINTN) AuthVariable->NameSize; + } else { + if (Variable->State == (UINT8) (-1) || + Variable->DataSize == (UINT32) (-1) || + Variable->NameSize == (UINT32) (-1) || + Variable->Attributes == (UINT32) (-1)) { + return 0; + } + return (UINTN) Variable->NameSize; + } +} + +/** + This code sets the size of name of variable. + + @param[in] Variable Pointer to the Variable Header. + @param[in] NameSize Name size to set. + +**/ +VOID +SetNameSizeOfVariable ( + IN VARIABLE_HEADER *Variable, + IN UINTN NameSize + ) +{ + AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + + AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + AuthVariable->NameSize = (UINT32) NameSize; + } else { + Variable->NameSize = (UINT32) NameSize; + } +} + +/** + + This code gets the size of variable data. + + @param Variable Pointer to the Variable Header. + + @return Size of variable in bytes. + +**/ +UINTN +DataSizeOfVariable ( + IN VARIABLE_HEADER *Variable + ) +{ + AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + + AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthVariable->State == (UINT8) (-1) || + AuthVariable->DataSize == (UINT32) (-1) || + AuthVariable->NameSize == (UINT32) (-1) || + AuthVariable->Attributes == (UINT32) (-1)) { + return 0; + } + return (UINTN) AuthVariable->DataSize; + } else { + if (Variable->State == (UINT8) (-1) || + Variable->DataSize == (UINT32) (-1) || + Variable->NameSize == (UINT32) (-1) || + Variable->Attributes == (UINT32) (-1)) { + return 0; + } + return (UINTN) Variable->DataSize; + } +} + +/** + This code sets the size of variable data. + + @param[in] Variable Pointer to the Variable Header. + @param[in] DataSize Data size to set. + +**/ +VOID +SetDataSizeOfVariable ( + IN VARIABLE_HEADER *Variable, + IN UINTN DataSize + ) +{ + AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + + AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + AuthVariable->DataSize = (UINT32) DataSize; + } else { + Variable->DataSize = (UINT32) DataSize; + } +} + +/** + + This code gets the pointer to the variable name. + + @param Variable Pointer to the Variable Header. + + @return Pointer to Variable Name which is Unicode encoding. + +**/ +CHAR16 * +GetVariableNamePtr ( + IN VARIABLE_HEADER *Variable + ) +{ + return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ()); +} + +/** + This code gets the pointer to the variable guid. + + @param Variable Pointer to the Variable Header. + + @return A EFI_GUID* pointer to Vendor Guid. + +**/ +EFI_GUID * +GetVendorGuidPtr ( + IN VARIABLE_HEADER *Variable + ) +{ + AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + + AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; + if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + return &AuthVariable->VendorGuid; + } else { + return &Variable->VendorGuid; + } +} + +/** + + This code gets the pointer to the variable data. + + @param Variable Pointer to the Variable Header. + + @return Pointer to Variable Data. + +**/ +UINT8 * +GetVariableDataPtr ( + IN VARIABLE_HEADER *Variable + ) +{ + UINTN Value; + + // + // Be careful about pad size for alignment. + // + Value = (UINTN) GetVariableNamePtr (Variable); + Value += NameSizeOfVariable (Variable); + Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); + + return (UINT8 *) Value; +} + +/** + This code gets the variable data offset related to variable header. + + @param Variable Pointer to the Variable Header. + + @return Variable Data offset. + +**/ +UINTN +GetVariableDataOffset ( + IN VARIABLE_HEADER *Variable + ) +{ + UINTN Value; + + // + // Be careful about pad size for alignment + // + Value = GetVariableHeaderSize (); + Value += NameSizeOfVariable (Variable); + Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); + + return Value; +} + +/** + + This code gets the pointer to the next variable header. + + @param Variable Pointer to the Variable Header. + + @return Pointer to next variable header. + +**/ +VARIABLE_HEADER * +GetNextVariablePtr ( + IN VARIABLE_HEADER *Variable + ) +{ + UINTN Value; + + Value = (UINTN) GetVariableDataPtr (Variable); + Value += DataSizeOfVariable (Variable); + Value += GET_PAD_SIZE (DataSizeOfVariable (Variable)); + + // + // Be careful about pad size for alignment. + // + return (VARIABLE_HEADER *) HEADER_ALIGN (Value); +} + +/** + + Gets the pointer to the first variable header in given variable store area. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @return Pointer to the first variable header. + +**/ +VARIABLE_HEADER * +GetStartPointer ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ) +{ + // + // The start of variable store. + // + return (VARIABLE_HEADER *) HEADER_ALIGN (VarStoreHeader + 1); +} + +/** + + Gets the pointer to the end of the variable storage area. + + This function gets pointer to the end of the variable storage + area, according to the input variable store header. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @return Pointer to the end of the variable storage area. + +**/ +VARIABLE_HEADER * +GetEndPointer ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ) +{ + // + // The end of variable store + // + return (VARIABLE_HEADER *) HEADER_ALIGN ((UINTN) VarStoreHeader + VarStoreHeader->Size); +} + +/** + Compare two EFI_TIME data. + + + @param[in] FirstTime A pointer to the first EFI_TIME data. + @param[in] SecondTime A pointer to the second EFI_TIME data. + + @retval TRUE The FirstTime is not later than the SecondTime. + @retval FALSE The FirstTime is later than the SecondTime. + +**/ +BOOLEAN +VariableCompareTimeStampInternal ( + IN EFI_TIME *FirstTime, + IN EFI_TIME *SecondTime + ) +{ + if (FirstTime->Year != SecondTime->Year) { + return (BOOLEAN) (FirstTime->Year < SecondTime->Year); + } else if (FirstTime->Month != SecondTime->Month) { + return (BOOLEAN) (FirstTime->Month < SecondTime->Month); + } else if (FirstTime->Day != SecondTime->Day) { + return (BOOLEAN) (FirstTime->Day < SecondTime->Day); + } else if (FirstTime->Hour != SecondTime->Hour) { + return (BOOLEAN) (FirstTime->Hour < SecondTime->Hour); + } else if (FirstTime->Minute != SecondTime->Minute) { + return (BOOLEAN) (FirstTime->Minute < SecondTime->Minute); + } + + return (BOOLEAN) (FirstTime->Second <= SecondTime->Second); +} + +/** + Find the variable in the specified variable store. + + @param[in] VariableName Name of the variable to be found + @param[in] VendorGuid Vendor GUID to be found. + @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute + check at runtime when searching variable. + @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. + + @retval EFI_SUCCESS Variable found successfully + @retval EFI_NOT_FOUND Variable not found +**/ +EFI_STATUS +FindVariableEx ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN BOOLEAN IgnoreRtCheck, + IN OUT VARIABLE_POINTER_TRACK *PtrTrack + ) +{ + VARIABLE_HEADER *InDeletedVariable; + VOID *Point; + + PtrTrack->InDeletedTransitionPtr = NULL; + + // + // Find the variable by walk through HOB, volatile and non-volatile variable store. + // + InDeletedVariable = NULL; + + for ( PtrTrack->CurrPtr = PtrTrack->StartPtr + ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr) + ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr) + ) { + if (PtrTrack->CurrPtr->State == VAR_ADDED || + PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) + ) { + if (IgnoreRtCheck || !AtRuntime () || ((PtrTrack->CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { + if (VariableName[0] == 0) { + if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + InDeletedVariable = PtrTrack->CurrPtr; + } else { + PtrTrack->InDeletedTransitionPtr = InDeletedVariable; + return EFI_SUCCESS; + } + } else { + if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) { + Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr); + + ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0); + if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) { + if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + InDeletedVariable = PtrTrack->CurrPtr; + } else { + PtrTrack->InDeletedTransitionPtr = InDeletedVariable; + return EFI_SUCCESS; + } + } + } + } + } + } + } + + PtrTrack->CurrPtr = InDeletedVariable; + return (PtrTrack->CurrPtr == NULL) ? EFI_NOT_FOUND : EFI_SUCCESS; +} + +/** + This code Finds the Next available variable. + + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode. This function will do basic validation, before parse the data. + + @param[in] VariableName Pointer to variable name. + @param[in] VendorGuid Variable Vendor Guid. + @param[out] VariablePtr Pointer to variable header address. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_NOT_FOUND The next variable was not found. + @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. + @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and + GUID of an existing variable. + +**/ +EFI_STATUS +EFIAPI +VariableServiceGetNextVariableInternal ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + OUT VARIABLE_HEADER **VariablePtr + ) +{ + VARIABLE_STORE_TYPE Type; + VARIABLE_POINTER_TRACK Variable; + VARIABLE_POINTER_TRACK VariableInHob; + VARIABLE_POINTER_TRACK VariablePtrTrack; + EFI_STATUS Status; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; + + Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); + if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) { + // + // For VariableName is an empty string, FindVariable() will try to find and return + // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND) + // as no any variable is found, still go to return the error (EFI_NOT_FOUND). + // + if (VariableName[0] != 0) { + // + // For VariableName is not an empty string, and FindVariable() returns error as + // VariableName and VendorGuid are not a name and GUID of an existing variable, + // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER. + // + Status = EFI_INVALID_PARAMETER; + } + goto Done; + } + + if (VariableName[0] != 0) { + // + // If variable name is not NULL, get next variable. + // + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + } + + // + // 0: Volatile, 1: HOB, 2: Non-Volatile. + // The index and attributes mapping must be kept in this order as FindVariable + // makes use of this mapping to implement search algorithm. + // + VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; + + while (TRUE) { + // + // Switch from Volatile to HOB, to Non-Volatile. + // + while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) { + // + // Find current storage index + // + for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) { + if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) { + break; + } + } + ASSERT (Type < VariableStoreTypeMax); + // + // Switch to next storage + // + for (Type++; Type < VariableStoreTypeMax; Type++) { + if (VariableStoreHeader[Type] != NULL) { + break; + } + } + // + // Capture the case that + // 1. current storage is the last one, or + // 2. no further storage + // + if (Type == VariableStoreTypeMax) { + Status = EFI_NOT_FOUND; + goto Done; + } + Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]); + Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]); + Variable.CurrPtr = Variable.StartPtr; + } + + // + // Variable is found + // + if (Variable.CurrPtr->State == VAR_ADDED || Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + if (!AtRuntime () || ((Variable.CurrPtr->Attributes & EFI_VARIABLE_RUNTIME_ACCESS) != 0)) { + if (Variable.CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { + // + // If it is a IN_DELETED_TRANSITION variable, + // and there is also a same ADDED one at the same time, + // don't return it. + // + VariablePtrTrack.StartPtr = Variable.StartPtr; + VariablePtrTrack.EndPtr = Variable.EndPtr; + Status = FindVariableEx ( + GetVariableNamePtr (Variable.CurrPtr), + GetVendorGuidPtr (Variable.CurrPtr), + FALSE, + &VariablePtrTrack + ); + if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) { + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + continue; + } + } + + // + // Don't return NV variable when HOB overrides it + // + if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && + (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv])) + ) { + VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]); + VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]); + Status = FindVariableEx ( + GetVariableNamePtr (Variable.CurrPtr), + GetVendorGuidPtr (Variable.CurrPtr), + FALSE, + &VariableInHob + ); + if (!EFI_ERROR (Status)) { + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + continue; + } + } + + *VariablePtr = Variable.CurrPtr; + Status = EFI_SUCCESS; + goto Done; + } + } + + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + } + +Done: + return Status; +} + +/** + Routine used to track statistical information about variable usage. + The data is stored in the EFI system table so it can be accessed later. + VariableInfo.efi can dump out the table. Only Boot Services variable + accesses are tracked by this code. The PcdVariableCollectStatistics + build flag controls if this feature is enabled. + + A read that hits in the cache will have Read and Cache true for + the transaction. Data is allocated by this routine, but never + freed. + + @param[in] VariableName Name of the Variable to track. + @param[in] VendorGuid Guid of the Variable to track. + @param[in] Volatile TRUE if volatile FALSE if non-volatile. + @param[in] Read TRUE if GetVariable() was called. + @param[in] Write TRUE if SetVariable() was called. + @param[in] Delete TRUE if deleted via SetVariable(). + @param[in] Cache TRUE for a cache hit. + +**/ +VOID +UpdateVariableInfo ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN BOOLEAN Volatile, + IN BOOLEAN Read, + IN BOOLEAN Write, + IN BOOLEAN Delete, + IN BOOLEAN Cache + ) +{ + VARIABLE_INFO_ENTRY *Entry; + + if (FeaturePcdGet (PcdVariableCollectStatistics)) { + + if (AtRuntime ()) { + // Don't collect statistics at runtime. + return; + } + + if (gVariableInfo == NULL) { + // + // On the first call allocate a entry and place a pointer to it in + // the EFI System Table. + // + gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); + ASSERT (gVariableInfo != NULL); + + CopyGuid (&gVariableInfo->VendorGuid, VendorGuid); + gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName)); + ASSERT (gVariableInfo->Name != NULL); + StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); + gVariableInfo->Volatile = Volatile; + } + + + for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) { + if (CompareGuid (VendorGuid, &Entry->VendorGuid)) { + if (StrCmp (VariableName, Entry->Name) == 0) { + if (Read) { + Entry->ReadCount++; + } + if (Write) { + Entry->WriteCount++; + } + if (Delete) { + Entry->DeleteCount++; + } + if (Cache) { + Entry->CacheCount++; + } + + return; + } + } + + if (Entry->Next == NULL) { + // + // If the entry is not in the table add it. + // Next iteration of the loop will fill in the data. + // + Entry->Next = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); + ASSERT (Entry->Next != NULL); + + CopyGuid (&Entry->Next->VendorGuid, VendorGuid); + Entry->Next->Name = AllocateZeroPool (StrSize (VariableName)); + ASSERT (Entry->Next->Name != NULL); + StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); + Entry->Next->Volatile = Volatile; + } + + } + } +} diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h new file mode 100644 index 00000000000..b0d7f76bd8f --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h @@ -0,0 +1,306 @@ +/** @file + Functions in this module are associated with variable parsing operations and + are intended to be usable across variable driver source files. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _VARIABLE_PARSING_H_ +#define _VARIABLE_PARSING_H_ + +#include +#include "Variable.h" + +/** + + This code checks if variable header is valid or not. + + @param[in] Variable Pointer to the Variable Header. + @param[in] VariableStoreEnd Pointer to the Variable Store End. + + @retval TRUE Variable header is valid. + @retval FALSE Variable header is not valid. + +**/ +BOOLEAN +IsValidVariableHeader ( + IN VARIABLE_HEADER *Variable, + IN VARIABLE_HEADER *VariableStoreEnd + ); + +/** + + This code gets the current status of Variable Store. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @retval EfiRaw Variable store status is raw. + @retval EfiValid Variable store status is valid. + @retval EfiInvalid Variable store status is invalid. + +**/ +VARIABLE_STORE_STATUS +GetVariableStoreStatus ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ); + +/** + This code gets the size of variable header. + + @return Size of variable header in bytes in type UINTN. + +**/ +UINTN +GetVariableHeaderSize ( + VOID + ); + +/** + + This code gets the size of name of variable. + + @param Variable Pointer to the Variable Header. + + @return UINTN Size of variable in bytes. + +**/ +UINTN +NameSizeOfVariable ( + IN VARIABLE_HEADER *Variable + ); + +/** + This code sets the size of name of variable. + + @param[in] Variable Pointer to the Variable Header. + @param[in] NameSize Name size to set. + +**/ +VOID +SetNameSizeOfVariable ( + IN VARIABLE_HEADER *Variable, + IN UINTN NameSize + ); + +/** + + This code gets the size of variable data. + + @param Variable Pointer to the Variable Header. + + @return Size of variable in bytes. + +**/ +UINTN +DataSizeOfVariable ( + IN VARIABLE_HEADER *Variable + ); + +/** + This code sets the size of variable data. + + @param[in] Variable Pointer to the Variable Header. + @param[in] DataSize Data size to set. + +**/ +VOID +SetDataSizeOfVariable ( + IN VARIABLE_HEADER *Variable, + IN UINTN DataSize + ); + +/** + + This code gets the pointer to the variable name. + + @param Variable Pointer to the Variable Header. + + @return Pointer to Variable Name which is Unicode encoding. + +**/ +CHAR16 * +GetVariableNamePtr ( + IN VARIABLE_HEADER *Variable + ); + +/** + This code gets the pointer to the variable guid. + + @param Variable Pointer to the Variable Header. + + @return A EFI_GUID* pointer to Vendor Guid. + +**/ +EFI_GUID * +GetVendorGuidPtr ( + IN VARIABLE_HEADER *Variable + ); + +/** + + This code gets the pointer to the variable data. + + @param Variable Pointer to the Variable Header. + + @return Pointer to Variable Data. + +**/ +UINT8 * +GetVariableDataPtr ( + IN VARIABLE_HEADER *Variable + ); + +/** + This code gets the variable data offset related to variable header. + + @param Variable Pointer to the Variable Header. + + @return Variable Data offset. + +**/ +UINTN +GetVariableDataOffset ( + IN VARIABLE_HEADER *Variable + ); + +/** + + This code gets the pointer to the next variable header. + + @param Variable Pointer to the Variable Header. + + @return Pointer to next variable header. + +**/ +VARIABLE_HEADER * +GetNextVariablePtr ( + IN VARIABLE_HEADER *Variable + ); + +/** + + Gets the pointer to the first variable header in given variable store area. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @return Pointer to the first variable header. + +**/ +VARIABLE_HEADER * +GetStartPointer ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ); + +/** + + Gets the pointer to the end of the variable storage area. + + This function gets pointer to the end of the variable storage + area, according to the input variable store header. + + @param[in] VarStoreHeader Pointer to the Variable Store Header. + + @return Pointer to the end of the variable storage area. + +**/ +VARIABLE_HEADER * +GetEndPointer ( + IN VARIABLE_STORE_HEADER *VarStoreHeader + ); + +/** + Compare two EFI_TIME data. + + + @param[in] FirstTime A pointer to the first EFI_TIME data. + @param[in] SecondTime A pointer to the second EFI_TIME data. + + @retval TRUE The FirstTime is not later than the SecondTime. + @retval FALSE The FirstTime is later than the SecondTime. + +**/ +BOOLEAN +VariableCompareTimeStampInternal ( + IN EFI_TIME *FirstTime, + IN EFI_TIME *SecondTime + ); + +/** + Find the variable in the specified variable store. + + @param[in] VariableName Name of the variable to be found + @param[in] VendorGuid Vendor GUID to be found. + @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute + check at runtime when searching variable. + @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. + + @retval EFI_SUCCESS Variable found successfully + @retval EFI_NOT_FOUND Variable not found +**/ +EFI_STATUS +FindVariableEx ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN BOOLEAN IgnoreRtCheck, + IN OUT VARIABLE_POINTER_TRACK *PtrTrack + ); + +/** + This code Finds the Next available variable. + + Caution: This function may receive untrusted input. + This function may be invoked in SMM mode. This function will do basic validation, before parse the data. + + @param[in] VariableName Pointer to variable name. + @param[in] VendorGuid Variable Vendor Guid. + @param[out] VariablePtr Pointer to variable header address. + + @retval EFI_SUCCESS The function completed successfully. + @retval EFI_NOT_FOUND The next variable was not found. + @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. + @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and + GUID of an existing variable. + +**/ +EFI_STATUS +EFIAPI +VariableServiceGetNextVariableInternal ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + OUT VARIABLE_HEADER **VariablePtr + ); + +/** + Routine used to track statistical information about variable usage. + The data is stored in the EFI system table so it can be accessed later. + VariableInfo.efi can dump out the table. Only Boot Services variable + accesses are tracked by this code. The PcdVariableCollectStatistics + build flag controls if this feature is enabled. + + A read that hits in the cache will have Read and Cache true for + the transaction. Data is allocated by this routine, but never + freed. + + @param[in] VariableName Name of the Variable to track. + @param[in] VendorGuid Guid of the Variable to track. + @param[in] Volatile TRUE if volatile FALSE if non-volatile. + @param[in] Read TRUE if GetVariable() was called. + @param[in] Write TRUE if SetVariable() was called. + @param[in] Delete TRUE if deleted via SetVariable(). + @param[in] Cache TRUE for a cache hit. + +**/ +VOID +UpdateVariableInfo ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + IN BOOLEAN Volatile, + IN BOOLEAN Read, + IN BOOLEAN Write, + IN BOOLEAN Delete, + IN BOOLEAN Cache + ); + +#endif diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf index 641376c9c51..c35e5fe7878 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf @@ -36,6 +36,8 @@ Variable.c VariableDxe.c Variable.h + VariableParsing.c + VariableParsing.h PrivilegePolymorphic.h Measurement.c TcgMorLockDxe.c diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c index ec463d063ea..ce409f22a3e 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c @@ -30,6 +30,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "Variable.h" +#include "VariableParsing.h" BOOLEAN mAtRuntime = FALSE; UINT8 *mVariableBufferPayload = NULL; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf index 0a160d269d4..626738b9c77 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf @@ -45,6 +45,8 @@ Variable.c VariableTraditionalMm.c VariableSmm.c + VariableParsing.c + VariableParsing.h VarCheck.c Variable.h PrivilegePolymorphic.h diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf index 21bc81163b8..ff714b193a7 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf @@ -45,6 +45,8 @@ Variable.c VariableSmm.c VariableStandaloneMm.c + VariableParsing.c + VariableParsing.h VarCheck.c Variable.h PrivilegePolymorphic.h From f8ff4cca7c573ba72051a515d738095a3c5921ff Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 27 Sep 2019 14:41:47 -0700 Subject: [PATCH 040/384] MdeModulePkg/Variable: Parameterize GetNextVariableInternal () stores The majority of logic related to GetNextVariableName () is currently implemented in VariableServiceGetNextVariableInternal (). The list of variable stores to search for the given variable name and variable GUID is defined in the function body. This change adds a new parameter so that the caller must pass in the list of variable stores to be used in the variable search. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../Universal/Variable/RuntimeDxe/Variable.c | 12 ++- .../Variable/RuntimeDxe/VariableExLib.c | 6 ++ .../Variable/RuntimeDxe/VariableParsing.c | 82 +++++++++++-------- .../Variable/RuntimeDxe/VariableParsing.h | 13 +-- 4 files changed, 73 insertions(+), 40 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 76536308e6a..70af86db242 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -2358,6 +2358,7 @@ VariableServiceGetNextVariableName ( UINTN MaxLen; UINTN VarNameSize; VARIABLE_HEADER *VariablePtr; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) { return EFI_INVALID_PARAMETER; @@ -2377,7 +2378,16 @@ VariableServiceGetNextVariableName ( AcquireLockOnlyAtBootTime(&mVariableModuleGlobal->VariableGlobal.VariableServicesLock); - Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, &VariablePtr); + // + // 0: Volatile, 1: HOB, 2: Non-Volatile. + // The index and attributes mapping must be kept in this order as FindVariable + // makes use of this mapping to implement search algorithm. + // + VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; + + Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, VariableStoreHeader, &VariablePtr); if (!EFI_ERROR (Status)) { VarNameSize = NameSizeOfVariable (VariablePtr); ASSERT (VarNameSize != 0); diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c index dc78f68fa9e..c787ddba5bb 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c @@ -98,10 +98,16 @@ VariableExLibFindNextVariable ( EFI_STATUS Status; VARIABLE_HEADER *VariablePtr; AUTHENTICATED_VARIABLE_HEADER *AuthVariablePtr; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; + + VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; Status = VariableServiceGetNextVariableInternal ( VariableName, VendorGuid, + VariableStoreHeader, &VariablePtr ); if (EFI_ERROR (Status)) { diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c index 5698a1a5e42..d6bb916e68e 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c @@ -476,14 +476,16 @@ FindVariableEx ( } /** - This code Finds the Next available variable. + This code finds the next available variable. Caution: This function may receive untrusted input. This function may be invoked in SMM mode. This function will do basic validation, before parse the data. - @param[in] VariableName Pointer to variable name. - @param[in] VendorGuid Variable Vendor Guid. - @param[out] VariablePtr Pointer to variable header address. + @param[in] VariableName Pointer to variable name. + @param[in] VendorGuid Variable Vendor Guid. + @param[in] VariableStoreList A list of variable stores that should be used to get the next variable. + The maximum number of entries is the max value of VARIABLE_STORE_TYPE. + @param[out] VariablePtr Pointer to variable header address. @retval EFI_SUCCESS The function completed successfully. @retval EFI_NOT_FOUND The next variable was not found. @@ -497,26 +499,47 @@ EFIAPI VariableServiceGetNextVariableInternal ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, + IN VARIABLE_STORE_HEADER **VariableStoreList, OUT VARIABLE_HEADER **VariablePtr ) { - VARIABLE_STORE_TYPE Type; + EFI_STATUS Status; + VARIABLE_STORE_TYPE StoreType; VARIABLE_POINTER_TRACK Variable; VARIABLE_POINTER_TRACK VariableInHob; VARIABLE_POINTER_TRACK VariablePtrTrack; - EFI_STATUS Status; - VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; - Status = FindVariable (VariableName, VendorGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); + Status = EFI_NOT_FOUND; + + if (VariableStoreList == NULL) { + return EFI_INVALID_PARAMETER; + } + + // Check if the variable exists in the given variable store list + for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) { + if (VariableStoreList[StoreType] == NULL) { + continue; + } + + Variable.StartPtr = GetStartPointer (VariableStoreList[StoreType]); + Variable.EndPtr = GetEndPointer (VariableStoreList[StoreType]); + Variable.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile); + + Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable); + if (!EFI_ERROR (Status)) { + break; + } + } + if (Variable.CurrPtr == NULL || EFI_ERROR (Status)) { // - // For VariableName is an empty string, FindVariable() will try to find and return - // the first qualified variable, and if FindVariable() returns error (EFI_NOT_FOUND) + // For VariableName is an empty string, FindVariableEx() will try to find and return + // the first qualified variable, and if FindVariableEx() returns error (EFI_NOT_FOUND) // as no any variable is found, still go to return the error (EFI_NOT_FOUND). // if (VariableName[0] != 0) { // - // For VariableName is not an empty string, and FindVariable() returns error as + // For VariableName is not an empty string, and FindVariableEx() returns error as // VariableName and VendorGuid are not a name and GUID of an existing variable, // there is no way to get next variable, follow spec to return EFI_INVALID_PARAMETER. // @@ -527,39 +550,30 @@ VariableServiceGetNextVariableInternal ( if (VariableName[0] != 0) { // - // If variable name is not NULL, get next variable. + // If variable name is not empty, get next variable. // Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); } - // - // 0: Volatile, 1: HOB, 2: Non-Volatile. - // The index and attributes mapping must be kept in this order as FindVariable - // makes use of this mapping to implement search algorithm. - // - VariableStoreHeader[VariableStoreTypeVolatile] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; - VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; - VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; - while (TRUE) { // - // Switch from Volatile to HOB, to Non-Volatile. + // Switch to the next variable store if needed // while (!IsValidVariableHeader (Variable.CurrPtr, Variable.EndPtr)) { // // Find current storage index // - for (Type = (VARIABLE_STORE_TYPE) 0; Type < VariableStoreTypeMax; Type++) { - if ((VariableStoreHeader[Type] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreHeader[Type]))) { + for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) { + if ((VariableStoreList[StoreType] != NULL) && (Variable.StartPtr == GetStartPointer (VariableStoreList[StoreType]))) { break; } } - ASSERT (Type < VariableStoreTypeMax); + ASSERT (StoreType < VariableStoreTypeMax); // // Switch to next storage // - for (Type++; Type < VariableStoreTypeMax; Type++) { - if (VariableStoreHeader[Type] != NULL) { + for (StoreType++; StoreType < VariableStoreTypeMax; StoreType++) { + if (VariableStoreList[StoreType] != NULL) { break; } } @@ -568,12 +582,12 @@ VariableServiceGetNextVariableInternal ( // 1. current storage is the last one, or // 2. no further storage // - if (Type == VariableStoreTypeMax) { + if (StoreType == VariableStoreTypeMax) { Status = EFI_NOT_FOUND; goto Done; } - Variable.StartPtr = GetStartPointer (VariableStoreHeader[Type]); - Variable.EndPtr = GetEndPointer (VariableStoreHeader[Type]); + Variable.StartPtr = GetStartPointer (VariableStoreList[StoreType]); + Variable.EndPtr = GetEndPointer (VariableStoreList[StoreType]); Variable.CurrPtr = Variable.StartPtr; } @@ -605,11 +619,11 @@ VariableServiceGetNextVariableInternal ( // // Don't return NV variable when HOB overrides it // - if ((VariableStoreHeader[VariableStoreTypeHob] != NULL) && (VariableStoreHeader[VariableStoreTypeNv] != NULL) && - (Variable.StartPtr == GetStartPointer (VariableStoreHeader[VariableStoreTypeNv])) + if ((VariableStoreList[VariableStoreTypeHob] != NULL) && (VariableStoreList[VariableStoreTypeNv] != NULL) && + (Variable.StartPtr == GetStartPointer (VariableStoreList[VariableStoreTypeNv])) ) { - VariableInHob.StartPtr = GetStartPointer (VariableStoreHeader[VariableStoreTypeHob]); - VariableInHob.EndPtr = GetEndPointer (VariableStoreHeader[VariableStoreTypeHob]); + VariableInHob.StartPtr = GetStartPointer (VariableStoreList[VariableStoreTypeHob]); + VariableInHob.EndPtr = GetEndPointer (VariableStoreList[VariableStoreTypeHob]); Status = FindVariableEx ( GetVariableNamePtr (Variable.CurrPtr), GetVendorGuidPtr (Variable.CurrPtr), diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h index b0d7f76bd8f..6555316f52e 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h @@ -248,18 +248,20 @@ FindVariableEx ( ); /** - This code Finds the Next available variable. + This code finds the next available variable. Caution: This function may receive untrusted input. This function may be invoked in SMM mode. This function will do basic validation, before parse the data. - @param[in] VariableName Pointer to variable name. - @param[in] VendorGuid Variable Vendor Guid. - @param[out] VariablePtr Pointer to variable header address. + @param[in] VariableName Pointer to variable name. + @param[in] VendorGuid Variable Vendor Guid. + @param[in] VariableStoreList A list of variable stores that should be used to get the next variable. + The maximum number of entries is the max value of VARIABLE_STORE_TYPE. + @param[out] VariablePtr Pointer to variable header address. @retval EFI_SUCCESS The function completed successfully. @retval EFI_NOT_FOUND The next variable was not found. - @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. + @retval EFI_INVALID_PARAMETER If VariableName is nt an empty string, while VendorGuid is NULL. @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and GUID of an existing variable. @@ -269,6 +271,7 @@ EFIAPI VariableServiceGetNextVariableInternal ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, + IN VARIABLE_STORE_HEADER **VariableStoreList, OUT VARIABLE_HEADER **VariablePtr ); From 8d53adbee946e7fbcccddbd3f0fa8bb985ed03e2 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 27 Sep 2019 15:08:09 -0700 Subject: [PATCH 041/384] MdeModulePkg/Variable: Parameterize VARIABLE_INFO_ENTRY buffer UpdateVariableInfo () currently accepts parameters regarding updates to be made to a global variable of type VARIABLE_INFO_ENTRY. This change passes the structure by pointer to UpdateVariableInfo () so structures other than the fixed global variable can be updated. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../Universal/Variable/RuntimeDxe/Variable.c | 14 +++--- .../Variable/RuntimeDxe/VariableParsing.c | 43 ++++++++++--------- .../Variable/RuntimeDxe/VariableParsing.h | 18 ++++---- 3 files changed, 40 insertions(+), 35 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 70af86db242..5cc12c2ae08 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -1641,7 +1641,7 @@ UpdateVariable ( // go to delete this variable in variable HOB and // try to flush other variables from HOB to flash. // - UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, FALSE, TRUE, FALSE, &gVariableInfo); FlushHobVariableToFlash (VariableName, VendorGuid); return EFI_SUCCESS; } @@ -1758,7 +1758,7 @@ UpdateVariable ( &State ); if (!EFI_ERROR (Status)) { - UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, FALSE, TRUE, FALSE, &gVariableInfo); if (!Variable->Volatile) { CacheVariable->CurrPtr->State = State; FlushHobVariableToFlash (VariableName, VendorGuid); @@ -1777,7 +1777,7 @@ UpdateVariable ( // // Variable content unchanged and no need to update timestamp, just return. // - UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, Variable->Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo); Status = EFI_SUCCESS; goto Done; } else if ((CacheVariable->CurrPtr->State == VAR_ADDED) || @@ -2006,7 +2006,7 @@ UpdateVariable ( CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr)); CacheVariable->InDeletedTransitionPtr = NULL; } - UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, FALSE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo); FlushHobVariableToFlash (VariableName, VendorGuid); } else { if (IsCommonUserVariable && ((VarSize + mVariableModuleGlobal->CommonUserVariableTotalSize) > mVariableModuleGlobal->CommonMaxUserVariableSpace)) { @@ -2156,7 +2156,7 @@ UpdateVariable ( CacheVariable->CurrPtr = (VARIABLE_HEADER *)((UINTN) CacheVariable->StartPtr + ((UINTN) Variable->CurrPtr - (UINTN) Variable->StartPtr)); CacheVariable->InDeletedTransitionPtr = NULL; } - UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, TRUE, FALSE, TRUE, FALSE, FALSE, &gVariableInfo); } goto Done; } @@ -2227,7 +2227,7 @@ UpdateVariable ( } if (!EFI_ERROR (Status)) { - UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, Volatile, FALSE, TRUE, FALSE, FALSE, &gVariableInfo); if (!Volatile) { FlushHobVariableToFlash (VariableName, VendorGuid); } @@ -2306,7 +2306,7 @@ VariableServiceGetVariable ( } *DataSize = VarDataSize; - UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE); + UpdateVariableInfo (VariableName, VendorGuid, Variable.Volatile, TRUE, FALSE, FALSE, FALSE, &gVariableInfo); Status = EFI_SUCCESS; goto Done; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c index d6bb916e68e..870c9e3742c 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c @@ -660,13 +660,14 @@ VariableServiceGetNextVariableInternal ( the transaction. Data is allocated by this routine, but never freed. - @param[in] VariableName Name of the Variable to track. - @param[in] VendorGuid Guid of the Variable to track. - @param[in] Volatile TRUE if volatile FALSE if non-volatile. - @param[in] Read TRUE if GetVariable() was called. - @param[in] Write TRUE if SetVariable() was called. - @param[in] Delete TRUE if deleted via SetVariable(). - @param[in] Cache TRUE for a cache hit. + @param[in] VariableName Name of the Variable to track. + @param[in] VendorGuid Guid of the Variable to track. + @param[in] Volatile TRUE if volatile FALSE if non-volatile. + @param[in] Read TRUE if GetVariable() was called. + @param[in] Write TRUE if SetVariable() was called. + @param[in] Delete TRUE if deleted via SetVariable(). + @param[in] Cache TRUE for a cache hit. + @param[in,out] VariableInfo Pointer to a pointer of VARIABLE_INFO_ENTRY structures. **/ VOID @@ -677,35 +678,38 @@ UpdateVariableInfo ( IN BOOLEAN Read, IN BOOLEAN Write, IN BOOLEAN Delete, - IN BOOLEAN Cache + IN BOOLEAN Cache, + IN OUT VARIABLE_INFO_ENTRY **VariableInfo ) { VARIABLE_INFO_ENTRY *Entry; if (FeaturePcdGet (PcdVariableCollectStatistics)) { - + if (VariableName == NULL || VendorGuid == NULL || VariableInfo == NULL) { + return; + } if (AtRuntime ()) { // Don't collect statistics at runtime. return; } - if (gVariableInfo == NULL) { + if (*VariableInfo == NULL) { // // On the first call allocate a entry and place a pointer to it in // the EFI System Table. // - gVariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); - ASSERT (gVariableInfo != NULL); - - CopyGuid (&gVariableInfo->VendorGuid, VendorGuid); - gVariableInfo->Name = AllocateZeroPool (StrSize (VariableName)); - ASSERT (gVariableInfo->Name != NULL); - StrCpyS (gVariableInfo->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); - gVariableInfo->Volatile = Volatile; + *VariableInfo = AllocateZeroPool (sizeof (VARIABLE_INFO_ENTRY)); + ASSERT (*VariableInfo != NULL); + + CopyGuid (&(*VariableInfo)->VendorGuid, VendorGuid); + (*VariableInfo)->Name = AllocateZeroPool (StrSize (VariableName)); + ASSERT ((*VariableInfo)->Name != NULL); + StrCpyS ((*VariableInfo)->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); + (*VariableInfo)->Volatile = Volatile; } - for (Entry = gVariableInfo; Entry != NULL; Entry = Entry->Next) { + for (Entry = (*VariableInfo); Entry != NULL; Entry = Entry->Next) { if (CompareGuid (VendorGuid, &Entry->VendorGuid)) { if (StrCmp (VariableName, Entry->Name) == 0) { if (Read) { @@ -739,7 +743,6 @@ UpdateVariableInfo ( StrCpyS (Entry->Next->Name, StrSize(VariableName)/sizeof(CHAR16), VariableName); Entry->Next->Volatile = Volatile; } - } } } diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h index 6555316f52e..1777ce0e698 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h @@ -286,13 +286,14 @@ VariableServiceGetNextVariableInternal ( the transaction. Data is allocated by this routine, but never freed. - @param[in] VariableName Name of the Variable to track. - @param[in] VendorGuid Guid of the Variable to track. - @param[in] Volatile TRUE if volatile FALSE if non-volatile. - @param[in] Read TRUE if GetVariable() was called. - @param[in] Write TRUE if SetVariable() was called. - @param[in] Delete TRUE if deleted via SetVariable(). - @param[in] Cache TRUE for a cache hit. + @param[in] VariableName Name of the Variable to track. + @param[in] VendorGuid Guid of the Variable to track. + @param[in] Volatile TRUE if volatile FALSE if non-volatile. + @param[in] Read TRUE if GetVariable() was called. + @param[in] Write TRUE if SetVariable() was called. + @param[in] Delete TRUE if deleted via SetVariable(). + @param[in] Cache TRUE for a cache hit. + @param[in,out] VariableInfo Pointer to a pointer of VARIABLE_INFO_ENTRY structures. **/ VOID @@ -303,7 +304,8 @@ UpdateVariableInfo ( IN BOOLEAN Read, IN BOOLEAN Write, IN BOOLEAN Delete, - IN BOOLEAN Cache + IN BOOLEAN Cache, + IN OUT VARIABLE_INFO_ENTRY **VariableInfo ); #endif From 044010234e481e2d6167ff0d19f82a7ac863926c Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 27 Sep 2019 15:18:42 -0700 Subject: [PATCH 042/384] MdeModulePkg/Variable: Parameterize auth status in VariableParsing The file VariableParsing.c provides generic functionality related to parsing variable related structures and information. In order to calculate offsets for certain operations, the functions must know if authenticated variables are enabled as this increases the size of variable headers. This change removes linking against a global variable in an external file in favor of passing the authenticated variable status as a parameter to the variable parsing functions. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../Universal/Variable/RuntimeDxe/Variable.c | 258 ++++++++++++------ .../Variable/RuntimeDxe/VariableExLib.c | 15 +- .../Variable/RuntimeDxe/VariableParsing.c | 146 ++++++---- .../Variable/RuntimeDxe/VariableParsing.h | 82 ++++-- .../Variable/RuntimeDxe/VariableSmm.c | 5 +- 5 files changed, 339 insertions(+), 167 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 5cc12c2ae08..2e32905dfe8 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -311,7 +311,7 @@ RecordVarErrorFlag ( FALSE ); if (!EFI_ERROR (Status)) { - VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr); + VarErrFlag = (VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); TempFlag = *VarErrFlag; TempFlag &= Flag; if (TempFlag == *VarErrFlag) { @@ -369,7 +369,7 @@ InitializeVarErrorFlag ( FALSE ); if (!EFI_ERROR (Status)) { - VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr)); + VarErrFlag = *((VAR_ERROR_FLAG *) GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat)); if (VarErrFlag == Flag) { return; } @@ -410,7 +410,11 @@ IsUserVariable ( // then no need to check if the variable is user variable or not specially. // if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) { - if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) { + if (VarCheckLibVariablePropertyGet ( + GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), + GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), + &Property + ) == EFI_NOT_FOUND) { return TRUE; } } @@ -439,10 +443,14 @@ CalculateCommonUserVariableTotalSize ( if (mEndOfDxe && (mVariableModuleGlobal->CommonMaxUserVariableSpace != mVariableModuleGlobal->CommonVariableSpace)) { Variable = GetStartPointer (mNvVariableCache); while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat); VariableSize = (UINTN) NextVariable - (UINTN) Variable; if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) != EFI_VARIABLE_HARDWARE_ERROR_RECORD) { - if (VarCheckLibVariablePropertyGet (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &Property) == EFI_NOT_FOUND) { + if (VarCheckLibVariablePropertyGet ( + GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), + GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), + &Property + ) == EFI_NOT_FOUND) { // // No property, it is user variable. // @@ -518,7 +526,9 @@ Reclaim ( UINTN HwErrVariableTotalSize; VARIABLE_HEADER *UpdatingVariable; VARIABLE_HEADER *UpdatingInDeletedTransition; + BOOLEAN AuthFormat; + AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat; UpdatingVariable = NULL; UpdatingInDeletedTransition = NULL; if (UpdatingPtrTrack != NULL) { @@ -540,7 +550,7 @@ Reclaim ( MaximumBufferSize = sizeof (VARIABLE_STORE_HEADER); while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, AuthFormat); if ((Variable->State == VAR_ADDED || Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) && Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition @@ -590,7 +600,7 @@ Reclaim ( // Variable = GetStartPointer (VariableStoreHeader); while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, AuthFormat); if (Variable != UpdatingVariable && Variable->State == VAR_ADDED) { VariableSize = (UINTN) NextVariable - (UINTN) Variable; CopyMem (CurrPtr, (UINT8 *) Variable, VariableSize); @@ -612,7 +622,7 @@ Reclaim ( // Variable = GetStartPointer (VariableStoreHeader); while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, AuthFormat); if (Variable != UpdatingVariable && Variable != UpdatingInDeletedTransition && Variable->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { // @@ -624,13 +634,14 @@ Reclaim ( FoundAdded = FALSE; AddedVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) ValidBuffer); while (IsValidVariableHeader (AddedVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) ValidBuffer))) { - NextAddedVariable = GetNextVariablePtr (AddedVariable); - NameSize = NameSizeOfVariable (AddedVariable); - if (CompareGuid (GetVendorGuidPtr (AddedVariable), GetVendorGuidPtr (Variable)) && - NameSize == NameSizeOfVariable (Variable) - ) { - Point0 = (VOID *) GetVariableNamePtr (AddedVariable); - Point1 = (VOID *) GetVariableNamePtr (Variable); + NextAddedVariable = GetNextVariablePtr (AddedVariable, AuthFormat); + NameSize = NameSizeOfVariable (AddedVariable, AuthFormat); + if (CompareGuid ( + GetVendorGuidPtr (AddedVariable, AuthFormat), + GetVendorGuidPtr (Variable, AuthFormat) + ) && NameSize == NameSizeOfVariable (Variable, AuthFormat)) { + Point0 = (VOID *) GetVariableNamePtr (AddedVariable, AuthFormat); + Point1 = (VOID *) GetVariableNamePtr (Variable, AuthFormat); if (CompareMem (Point0, Point1, NameSize) == 0) { FoundAdded = TRUE; break; @@ -735,7 +746,7 @@ Reclaim ( mVariableModuleGlobal->CommonUserVariableTotalSize = 0; Variable = GetStartPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase); while (IsValidVariableHeader (Variable, GetEndPointer ((VARIABLE_STORE_HEADER *)(UINTN)VariableBase))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, AuthFormat); VariableSize = (UINTN) NextVariable - (UINTN) Variable; if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) { mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; @@ -829,7 +840,13 @@ FindVariable ( PtrTrack->EndPtr = GetEndPointer (VariableStoreHeader[Type]); PtrTrack->Volatile = (BOOLEAN) (Type == VariableStoreTypeVolatile); - Status = FindVariableEx (VariableName, VendorGuid, IgnoreRtCheck, PtrTrack); + Status = FindVariableEx ( + VariableName, + VendorGuid, + IgnoreRtCheck, + PtrTrack, + mVariableModuleGlobal->VariableGlobal.AuthFormat + ); if (!EFI_ERROR (Status)) { return Status; } @@ -1199,7 +1216,11 @@ CheckRemainingSpaceForConsistencyInternal ( VarNameSize += GET_PAD_SIZE (VarNameSize); VarDataSize = VariableEntry->VariableSize; VarDataSize += GET_PAD_SIZE (VarDataSize); - VariableEntry->VariableSize = HEADER_ALIGN (GetVariableHeaderSize () + VarNameSize + VarDataSize); + VariableEntry->VariableSize = HEADER_ALIGN ( + GetVariableHeaderSize ( + mVariableModuleGlobal->VariableGlobal.AuthFormat + ) + VarNameSize + VarDataSize + ); TotalNeededSize += VariableEntry->VariableSize; VariableEntry = VA_ARG (Args, VARIABLE_ENTRY_CONSISTENCY *); @@ -1232,13 +1253,14 @@ CheckRemainingSpaceForConsistencyInternal ( VariableEntry->Name, VariableEntry->Guid, FALSE, - &VariablePtrTrack + &VariablePtrTrack, + mVariableModuleGlobal->VariableGlobal.AuthFormat ); if (!EFI_ERROR (Status)) { // // Get size of Variable[Index]. // - NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr); + NextVariable = GetNextVariablePtr (VariablePtrTrack.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); OriginalVarSize = (UINTN) NextVariable - (UINTN) VariablePtrTrack.CurrPtr; // // Add the original size of Variable[Index] to remaining variable storage size. @@ -1410,8 +1432,8 @@ AutoUpdateLangVariable ( // Update Lang // VariableName = EFI_PLATFORM_LANG_VARIABLE_NAME; - Data = GetVariableDataPtr (Variable.CurrPtr); - DataSize = DataSizeOfVariable (Variable.CurrPtr); + Data = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + DataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); } else { Status = FindVariable (EFI_LANG_VARIABLE_NAME, &gEfiGlobalVariableGuid, &Variable, &mVariableModuleGlobal->VariableGlobal, FALSE); if (!EFI_ERROR (Status)) { @@ -1419,8 +1441,8 @@ AutoUpdateLangVariable ( // Update PlatformLang // VariableName = EFI_LANG_VARIABLE_NAME; - Data = GetVariableDataPtr (Variable.CurrPtr); - DataSize = DataSizeOfVariable (Variable.CurrPtr); + Data = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + DataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); } else { // // Neither PlatformLang nor Lang is set, directly return @@ -1598,6 +1620,7 @@ UpdateVariable ( BOOLEAN IsCommonVariable; BOOLEAN IsCommonUserVariable; AUTHENTICATED_VARIABLE_HEADER *AuthVariable; + BOOLEAN AuthFormat; if (mVariableModuleGlobal->FvbInstance == NULL && !mVariableModuleGlobal->VariableGlobal.EmuNvMode) { // @@ -1619,6 +1642,8 @@ UpdateVariable ( } } + AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat; + // // Check if CacheVariable points to the variable in variable HOB. // If yes, let CacheVariable points to the variable in NV variable cache. @@ -1630,7 +1655,7 @@ UpdateVariable ( CacheVariable->StartPtr = GetStartPointer (mNvVariableCache); CacheVariable->EndPtr = GetEndPointer (mNvVariableCache); CacheVariable->Volatile = FALSE; - Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable); + Status = FindVariableEx (VariableName, VendorGuid, FALSE, CacheVariable, AuthFormat); if (CacheVariable->CurrPtr == NULL || EFI_ERROR (Status)) { // // There is no matched variable in NV variable cache. @@ -1770,8 +1795,8 @@ UpdateVariable ( // If the variable is marked valid, and the same data has been passed in, // then return to the caller immediately. // - if (DataSizeOfVariable (CacheVariable->CurrPtr) == DataSize && - (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr), DataSize) == 0) && + if (DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) == DataSize && + (CompareMem (Data, GetVariableDataPtr (CacheVariable->CurrPtr, AuthFormat), DataSize) == 0) && ((Attributes & EFI_VARIABLE_APPEND_WRITE) == 0) && (TimeStamp == NULL)) { // @@ -1791,9 +1816,13 @@ UpdateVariable ( // NOTE: From 0 to DataOffset of NextVariable is reserved for Variable Header and Name. // From DataOffset of NextVariable is to save the existing variable data. // - DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr); + DataOffset = GetVariableDataOffset (CacheVariable->CurrPtr, AuthFormat); BufferForMerge = (UINT8 *) ((UINTN) NextVariable + DataOffset); - CopyMem (BufferForMerge, (UINT8 *) ((UINTN) CacheVariable->CurrPtr + DataOffset), DataSizeOfVariable (CacheVariable->CurrPtr)); + CopyMem ( + BufferForMerge, + (UINT8 *) ((UINTN) CacheVariable->CurrPtr + DataOffset), + DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + ); // // Set Max Auth/Non-Volatile/Volatile Variable Data Size as default MaxDataSize. @@ -1814,15 +1843,22 @@ UpdateVariable ( MaxDataSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - DataOffset; } - if (DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize > MaxDataSize) { + if (DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + DataSize > MaxDataSize) { // // Existing data size + new data size exceed maximum variable size limitation. // Status = EFI_INVALID_PARAMETER; goto Done; } - CopyMem ((UINT8*) ((UINTN) BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr)), Data, DataSize); - MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr) + DataSize; + CopyMem ( + (UINT8*) ( + (UINTN) BufferForMerge + DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + ), + Data, + DataSize + ); + MergedBufSize = DataSizeOfVariable (CacheVariable->CurrPtr, AuthFormat) + + DataSize; // // BufferForMerge(from DataOffset of NextVariable) has included the merged existing and new data. @@ -1925,7 +1961,7 @@ UpdateVariable ( // NextVariable->Attributes = Attributes & (~EFI_VARIABLE_APPEND_WRITE); - VarNameOffset = GetVariableHeaderSize (); + VarNameOffset = GetVariableHeaderSize (AuthFormat); VarNameSize = StrSize (VariableName); CopyMem ( (UINT8 *) ((UINTN) NextVariable + VarNameOffset), @@ -1946,14 +1982,18 @@ UpdateVariable ( ); } - CopyMem (GetVendorGuidPtr (NextVariable), VendorGuid, sizeof (EFI_GUID)); + CopyMem ( + GetVendorGuidPtr (NextVariable, AuthFormat), + VendorGuid, + sizeof (EFI_GUID) + ); // // There will be pad bytes after Data, the NextVariable->NameSize and // NextVariable->DataSize should not include pad size so that variable // service can get actual size in GetVariable. // - SetNameSizeOfVariable (NextVariable, VarNameSize); - SetDataSizeOfVariable (NextVariable, DataSize); + SetNameSizeOfVariable (NextVariable, VarNameSize, AuthFormat); + SetDataSizeOfVariable (NextVariable, DataSize, AuthFormat); // // The actual size of the variable that stores in storage should @@ -2036,7 +2076,7 @@ UpdateVariable ( TRUE, Fvb, mVariableModuleGlobal->NonVolatileLastVariableOffset, - (UINT32) GetVariableHeaderSize (), + (UINT32) GetVariableHeaderSize (AuthFormat), (UINT8 *) NextVariable ); @@ -2069,9 +2109,9 @@ UpdateVariable ( FALSE, TRUE, Fvb, - mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (), - (UINT32) (VarSize - GetVariableHeaderSize ()), - (UINT8 *) NextVariable + GetVariableHeaderSize () + mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (AuthFormat), + (UINT32) (VarSize - GetVariableHeaderSize (AuthFormat)), + (UINT8 *) NextVariable + GetVariableHeaderSize (AuthFormat) ); if (EFI_ERROR (Status)) { @@ -2291,7 +2331,7 @@ VariableServiceGetVariable ( // // Get data size // - VarDataSize = DataSizeOfVariable (Variable.CurrPtr); + VarDataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); ASSERT (VarDataSize != 0); if (*DataSize >= VarDataSize) { @@ -2300,7 +2340,7 @@ VariableServiceGetVariable ( goto Done; } - CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr), VarDataSize); + CopyMem (Data, GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), VarDataSize); if (Attributes != NULL) { *Attributes = Variable.CurrPtr->Attributes; } @@ -2357,6 +2397,7 @@ VariableServiceGetNextVariableName ( EFI_STATUS Status; UINTN MaxLen; UINTN VarNameSize; + BOOLEAN AuthFormat; VARIABLE_HEADER *VariablePtr; VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; @@ -2364,6 +2405,8 @@ VariableServiceGetNextVariableName ( return EFI_INVALID_PARAMETER; } + AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat; + // // Calculate the possible maximum length of name string, including the Null terminator. // @@ -2387,13 +2430,27 @@ VariableServiceGetNextVariableName ( VariableStoreHeader[VariableStoreTypeHob] = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; VariableStoreHeader[VariableStoreTypeNv] = mNvVariableCache; - Status = VariableServiceGetNextVariableInternal (VariableName, VendorGuid, VariableStoreHeader, &VariablePtr); + Status = VariableServiceGetNextVariableInternal ( + VariableName, + VendorGuid, + VariableStoreHeader, + &VariablePtr, + AuthFormat + ); if (!EFI_ERROR (Status)) { - VarNameSize = NameSizeOfVariable (VariablePtr); + VarNameSize = NameSizeOfVariable (VariablePtr, AuthFormat); ASSERT (VarNameSize != 0); if (VarNameSize <= *VariableNameSize) { - CopyMem (VariableName, GetVariableNamePtr (VariablePtr), VarNameSize); - CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr), sizeof (EFI_GUID)); + CopyMem ( + VariableName, + GetVariableNamePtr (VariablePtr, AuthFormat), + VarNameSize + ); + CopyMem ( + VendorGuid, + GetVendorGuidPtr (VariablePtr, AuthFormat), + sizeof (EFI_GUID) + ); Status = EFI_SUCCESS; } else { Status = EFI_BUFFER_TOO_SMALL; @@ -2446,6 +2503,9 @@ VariableServiceSetVariable ( VARIABLE_HEADER *NextVariable; EFI_PHYSICAL_ADDRESS Point; UINTN PayloadSize; + BOOLEAN AuthFormat; + + AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat; // // Check input parameters. @@ -2544,7 +2604,8 @@ VariableServiceSetVariable ( // bytes for HwErrRec#### variable. // if ((Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) { - if (StrSize (VariableName) + PayloadSize > PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize ()) { + if (StrSize (VariableName) + PayloadSize > + PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize (AuthFormat)) { return EFI_INVALID_PARAMETER; } } else { @@ -2553,7 +2614,9 @@ VariableServiceSetVariable ( // the DataSize is limited to maximum size of Max(Auth|Volatile)VariableSize bytes. // if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) { - if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize ()) { + if (StrSize (VariableName) + PayloadSize > + mVariableModuleGlobal->MaxAuthVariableSize - + GetVariableHeaderSize (AuthFormat)) { DEBUG ((DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", __FUNCTION__, VariableName, VendorGuid)); @@ -2562,12 +2625,13 @@ VariableServiceSetVariable ( "MaxAuthVariableSize(0x%x) - HeaderSize(0x%x)\n", StrSize (VariableName), PayloadSize, mVariableModuleGlobal->MaxAuthVariableSize, - GetVariableHeaderSize () + GetVariableHeaderSize (AuthFormat) )); return EFI_INVALID_PARAMETER; } } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) { - if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize ()) { + if (StrSize (VariableName) + PayloadSize > + mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize (AuthFormat)) { DEBUG ((DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", __FUNCTION__, VariableName, VendorGuid)); @@ -2576,12 +2640,13 @@ VariableServiceSetVariable ( "MaxVariableSize(0x%x) - HeaderSize(0x%x)\n", StrSize (VariableName), PayloadSize, mVariableModuleGlobal->MaxVariableSize, - GetVariableHeaderSize () + GetVariableHeaderSize (AuthFormat) )); return EFI_INVALID_PARAMETER; } } else { - if (StrSize (VariableName) + PayloadSize > mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize ()) { + if (StrSize (VariableName) + PayloadSize > + mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize (AuthFormat)) { DEBUG ((DEBUG_ERROR, "%a: Failed to set variable '%s' with Guid %g\n", __FUNCTION__, VariableName, VendorGuid)); @@ -2590,7 +2655,7 @@ VariableServiceSetVariable ( "MaxVolatileVariableSize(0x%x) - HeaderSize(0x%x)\n", StrSize (VariableName), PayloadSize, mVariableModuleGlobal->MaxVolatileVariableSize, - GetVariableHeaderSize () + GetVariableHeaderSize (AuthFormat) )); return EFI_INVALID_PARAMETER; } @@ -2629,7 +2694,7 @@ VariableServiceSetVariable ( // NextVariable = GetStartPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point); while (IsValidVariableHeader (NextVariable, GetEndPointer ((VARIABLE_STORE_HEADER *) (UINTN) Point))) { - NextVariable = GetNextVariablePtr (NextVariable); + NextVariable = GetNextVariablePtr (NextVariable, AuthFormat); } mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) NextVariable - (UINTN) Point; } @@ -2754,7 +2819,8 @@ VariableServiceQueryVariableInfoInternal ( // if ((Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { *MaximumVariableStorageSize = PcdGet32 (PcdHwErrStorageSize); - *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - GetVariableHeaderSize (); + *MaximumVariableSize = PcdGet32 (PcdMaxHardwareErrorVariableSize) - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); } else { if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) { if (AtRuntime ()) { @@ -2768,11 +2834,14 @@ VariableServiceQueryVariableInfoInternal ( // Let *MaximumVariableSize be Max(Auth|Volatile)VariableSize with the exception of the variable header size. // if ((Attributes & VARIABLE_ATTRIBUTE_AT_AW) != 0) { - *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize (); + *MaximumVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); } else if ((Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) { - *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - GetVariableHeaderSize (); + *MaximumVariableSize = mVariableModuleGlobal->MaxVariableSize - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); } else { - *MaximumVariableSize = mVariableModuleGlobal->MaxVolatileVariableSize - GetVariableHeaderSize (); + *MaximumVariableSize = mVariableModuleGlobal->MaxVolatileVariableSize - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); } } @@ -2785,7 +2854,7 @@ VariableServiceQueryVariableInfoInternal ( // Now walk through the related variable store. // while (IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat); VariableSize = (UINT64) (UINTN) NextVariable - (UINT64) (UINTN) Variable; if (AtRuntime ()) { @@ -2820,10 +2889,11 @@ VariableServiceQueryVariableInfoInternal ( VariablePtrTrack.StartPtr = GetStartPointer (VariableStoreHeader); VariablePtrTrack.EndPtr = GetEndPointer (VariableStoreHeader); Status = FindVariableEx ( - GetVariableNamePtr (Variable), - GetVendorGuidPtr (Variable), + GetVariableNamePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), + GetVendorGuidPtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat), FALSE, - &VariablePtrTrack + &VariablePtrTrack, + mVariableModuleGlobal->VariableGlobal.AuthFormat ); if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State != VAR_ADDED) { if ((Variable->Attributes & EFI_VARIABLE_HARDWARE_ERROR_RECORD) == EFI_VARIABLE_HARDWARE_ERROR_RECORD) { @@ -2851,10 +2921,13 @@ VariableServiceQueryVariableInfoInternal ( } } - if (*RemainingVariableStorageSize < GetVariableHeaderSize ()) { + if (*RemainingVariableStorageSize < GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) { *MaximumVariableSize = 0; - } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize ()) < *MaximumVariableSize) { - *MaximumVariableSize = *RemainingVariableStorageSize - GetVariableHeaderSize (); + } else if ((*RemainingVariableStorageSize - GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat)) < + *MaximumVariableSize + ) { + *MaximumVariableSize = *RemainingVariableStorageSize - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); } return EFI_SUCCESS; @@ -3331,7 +3404,7 @@ InitNonVolatileVariableStore ( // Variable = GetStartPointer (mNvVariableCache); while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) { - NextVariable = GetNextVariablePtr (Variable); + NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat); VariableSize = (UINTN) NextVariable - (UINTN) Variable; if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; @@ -3365,8 +3438,10 @@ FlushHobVariableToFlash ( VOID *VariableData; VARIABLE_POINTER_TRACK VariablePtrTrack; BOOLEAN ErrorFlag; + BOOLEAN AuthFormat; ErrorFlag = FALSE; + AuthFormat = mVariableModuleGlobal->VariableGlobal.AuthFormat; // // Flush the HOB variable to flash. @@ -3379,7 +3454,7 @@ FlushHobVariableToFlash ( mVariableModuleGlobal->VariableGlobal.HobVariableBase = 0; for ( Variable = GetStartPointer (VariableStoreHeader) ; IsValidVariableHeader (Variable, GetEndPointer (VariableStoreHeader)) - ; Variable = GetNextVariablePtr (Variable) + ; Variable = GetNextVariablePtr (Variable, AuthFormat) ) { if (Variable->State != VAR_ADDED) { // @@ -3389,22 +3464,33 @@ FlushHobVariableToFlash ( } ASSERT ((Variable->Attributes & EFI_VARIABLE_NON_VOLATILE) != 0); if (VendorGuid == NULL || VariableName == NULL || - !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable)) || - StrCmp (VariableName, GetVariableNamePtr (Variable)) != 0) { - VariableData = GetVariableDataPtr (Variable); - FindVariable (GetVariableNamePtr (Variable), GetVendorGuidPtr (Variable), &VariablePtrTrack, &mVariableModuleGlobal->VariableGlobal, FALSE); + !CompareGuid (VendorGuid, GetVendorGuidPtr (Variable, AuthFormat)) || + StrCmp (VariableName, GetVariableNamePtr (Variable, AuthFormat)) != 0) { + VariableData = GetVariableDataPtr (Variable, AuthFormat); + FindVariable ( + GetVariableNamePtr (Variable, AuthFormat), + GetVendorGuidPtr (Variable, AuthFormat), + &VariablePtrTrack, + &mVariableModuleGlobal->VariableGlobal, FALSE + ); Status = UpdateVariable ( - GetVariableNamePtr (Variable), - GetVendorGuidPtr (Variable), + GetVariableNamePtr (Variable, AuthFormat), + GetVendorGuidPtr (Variable, AuthFormat), VariableData, - DataSizeOfVariable (Variable), + DataSizeOfVariable (Variable, AuthFormat), Variable->Attributes, 0, 0, &VariablePtrTrack, NULL ); - DEBUG ((EFI_D_INFO, "Variable driver flush the HOB variable to flash: %g %s %r\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable), Status)); + DEBUG (( + DEBUG_INFO, + "Variable driver flush the HOB variable to flash: %g %s %r\n", + GetVendorGuidPtr (Variable, AuthFormat), + GetVariableNamePtr (Variable, AuthFormat), + Status + )); } else { // // The updated or deleted variable is matched with this HOB variable. @@ -3418,7 +3504,12 @@ FlushHobVariableToFlash ( // If set variable successful, or the updated or deleted variable is matched with the HOB variable, // set the HOB variable to DELETED state in local. // - DEBUG ((EFI_D_INFO, "Variable driver set the HOB variable to DELETED state in local: %g %s\n", GetVendorGuidPtr (Variable), GetVariableNamePtr (Variable))); + DEBUG (( + DEBUG_INFO, + "Variable driver set the HOB variable to DELETED state in local: %g %s\n", + GetVendorGuidPtr (Variable, AuthFormat), + GetVariableNamePtr (Variable, AuthFormat) + )); Variable->State &= VAR_DELETED; } else { ErrorFlag = TRUE; @@ -3495,7 +3586,8 @@ VariableWriteServiceInitialize ( // Authenticated variable initialize. // mAuthContextIn.StructSize = sizeof (AUTH_VAR_LIB_CONTEXT_IN); - mAuthContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - GetVariableHeaderSize (); + mAuthContextIn.MaxAuthVariableSize = mVariableModuleGlobal->MaxAuthVariableSize - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); Status = AuthVariableLibInitialize (&mAuthContextIn, &mAuthContextOut); if (!EFI_ERROR (Status)) { DEBUG ((EFI_D_INFO, "Variable driver will work with auth variable support!\n")); @@ -3574,7 +3666,7 @@ ConvertNormalVarStorageToAuthVarStorage ( AuthVarStroageSize += StartPtr->NameSize + GET_PAD_SIZE (StartPtr->NameSize); AuthVarStroageSize += StartPtr->DataSize + GET_PAD_SIZE (StartPtr->DataSize); } - StartPtr = GetNextVariablePtr (StartPtr); + StartPtr = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); } // @@ -3608,18 +3700,22 @@ ConvertNormalVarStorageToAuthVarStorage ( // Copy Variable Name // NextPtr = (UINT8 *) (AuthStartPtr + 1); - CopyMem (NextPtr, GetVariableNamePtr (StartPtr), AuthStartPtr->NameSize); + CopyMem ( + NextPtr, + GetVariableNamePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), + AuthStartPtr->NameSize + ); // // Copy Variable Data // NextPtr = NextPtr + AuthStartPtr->NameSize + GET_PAD_SIZE (AuthStartPtr->NameSize); - CopyMem (NextPtr, GetVariableDataPtr (StartPtr), AuthStartPtr->DataSize); + CopyMem (NextPtr, GetVariableDataPtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat), AuthStartPtr->DataSize); // // Go to next variable // AuthStartPtr = (AUTHENTICATED_VARIABLE_HEADER *) (NextPtr + AuthStartPtr->DataSize + GET_PAD_SIZE (AuthStartPtr->DataSize)); } - StartPtr = GetNextVariablePtr (StartPtr); + StartPtr = GetNextVariablePtr (StartPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); } // // Update Auth Storage Header diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c index c787ddba5bb..e865a089d17 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableExLib.c @@ -56,8 +56,8 @@ VariableExLibFindVariable ( return Status; } - AuthVariableInfo->DataSize = DataSizeOfVariable (Variable.CurrPtr); - AuthVariableInfo->Data = GetVariableDataPtr (Variable.CurrPtr); + AuthVariableInfo->DataSize = DataSizeOfVariable (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + AuthVariableInfo->Data = GetVariableDataPtr (Variable.CurrPtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); AuthVariableInfo->Attributes = Variable.CurrPtr->Attributes; if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable.CurrPtr; @@ -108,7 +108,8 @@ VariableExLibFindNextVariable ( VariableName, VendorGuid, VariableStoreHeader, - &VariablePtr + &VariablePtr, + mVariableModuleGlobal->VariableGlobal.AuthFormat ); if (EFI_ERROR (Status)) { AuthVariableInfo->VariableName = NULL; @@ -122,10 +123,10 @@ VariableExLibFindNextVariable ( return Status; } - AuthVariableInfo->VariableName = GetVariableNamePtr (VariablePtr); - AuthVariableInfo->VendorGuid = GetVendorGuidPtr (VariablePtr); - AuthVariableInfo->DataSize = DataSizeOfVariable (VariablePtr); - AuthVariableInfo->Data = GetVariableDataPtr (VariablePtr); + AuthVariableInfo->VariableName = GetVariableNamePtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + AuthVariableInfo->VendorGuid = GetVendorGuidPtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + AuthVariableInfo->DataSize = DataSizeOfVariable (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); + AuthVariableInfo->Data = GetVariableDataPtr (VariablePtr, mVariableModuleGlobal->VariableGlobal.AuthFormat); AuthVariableInfo->Attributes = VariablePtr->Attributes; if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { AuthVariablePtr = (AUTHENTICATED_VARIABLE_HEADER *) VariablePtr; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c index 870c9e3742c..d458f1c608f 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c @@ -78,17 +78,20 @@ GetVariableStoreStatus ( /** This code gets the size of variable header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. + @return Size of variable header in bytes in type UINTN. **/ UINTN GetVariableHeaderSize ( - VOID + IN BOOLEAN AuthFormat ) { UINTN Value; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { Value = sizeof (AUTHENTICATED_VARIABLE_HEADER); } else { Value = sizeof (VARIABLE_HEADER); @@ -101,20 +104,23 @@ GetVariableHeaderSize ( This code gets the size of name of variable. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the variable header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return UINTN Size of variable in bytes. **/ UINTN NameSizeOfVariable ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { AUTHENTICATED_VARIABLE_HEADER *AuthVariable; AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { if (AuthVariable->State == (UINT8) (-1) || AuthVariable->DataSize == (UINT32) (-1) || AuthVariable->NameSize == (UINT32) (-1) || @@ -136,20 +142,23 @@ NameSizeOfVariable ( /** This code sets the size of name of variable. - @param[in] Variable Pointer to the Variable Header. - @param[in] NameSize Name size to set. + @param[in] Variable Pointer to the Variable Header. + @param[in] NameSize Name size to set. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. **/ VOID SetNameSizeOfVariable ( IN VARIABLE_HEADER *Variable, - IN UINTN NameSize + IN UINTN NameSize, + IN BOOLEAN AuthFormat ) { AUTHENTICATED_VARIABLE_HEADER *AuthVariable; AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { AuthVariable->NameSize = (UINT32) NameSize; } else { Variable->NameSize = (UINT32) NameSize; @@ -160,20 +169,23 @@ SetNameSizeOfVariable ( This code gets the size of variable data. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Size of variable in bytes. **/ UINTN DataSizeOfVariable ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { AUTHENTICATED_VARIABLE_HEADER *AuthVariable; AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { if (AuthVariable->State == (UINT8) (-1) || AuthVariable->DataSize == (UINT32) (-1) || AuthVariable->NameSize == (UINT32) (-1) || @@ -197,18 +209,21 @@ DataSizeOfVariable ( @param[in] Variable Pointer to the Variable Header. @param[in] DataSize Data size to set. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. **/ VOID SetDataSizeOfVariable ( - IN VARIABLE_HEADER *Variable, - IN UINTN DataSize + IN VARIABLE_HEADER *Variable, + IN UINTN DataSize, + IN BOOLEAN AuthFormat ) { AUTHENTICATED_VARIABLE_HEADER *AuthVariable; AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { AuthVariable->DataSize = (UINT32) DataSize; } else { Variable->DataSize = (UINT32) DataSize; @@ -219,36 +234,42 @@ SetDataSizeOfVariable ( This code gets the pointer to the variable name. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to Variable Name which is Unicode encoding. **/ CHAR16 * GetVariableNamePtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { - return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize ()); + return (CHAR16 *) ((UINTN) Variable + GetVariableHeaderSize (AuthFormat)); } /** This code gets the pointer to the variable guid. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return A EFI_GUID* pointer to Vendor Guid. **/ EFI_GUID * GetVendorGuidPtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { AUTHENTICATED_VARIABLE_HEADER *AuthVariable; AuthVariable = (AUTHENTICATED_VARIABLE_HEADER *) Variable; - if (mVariableModuleGlobal->VariableGlobal.AuthFormat) { + if (AuthFormat) { return &AuthVariable->VendorGuid; } else { return &Variable->VendorGuid; @@ -259,14 +280,17 @@ GetVendorGuidPtr ( This code gets the pointer to the variable data. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to Variable Data. **/ UINT8 * GetVariableDataPtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { UINTN Value; @@ -274,9 +298,9 @@ GetVariableDataPtr ( // // Be careful about pad size for alignment. // - Value = (UINTN) GetVariableNamePtr (Variable); - Value += NameSizeOfVariable (Variable); - Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); + Value = (UINTN) GetVariableNamePtr (Variable, AuthFormat); + Value += NameSizeOfVariable (Variable, AuthFormat); + Value += GET_PAD_SIZE (NameSizeOfVariable (Variable, AuthFormat)); return (UINT8 *) Value; } @@ -284,14 +308,17 @@ GetVariableDataPtr ( /** This code gets the variable data offset related to variable header. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Variable Data offset. **/ UINTN GetVariableDataOffset ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { UINTN Value; @@ -299,9 +326,9 @@ GetVariableDataOffset ( // // Be careful about pad size for alignment // - Value = GetVariableHeaderSize (); - Value += NameSizeOfVariable (Variable); - Value += GET_PAD_SIZE (NameSizeOfVariable (Variable)); + Value = GetVariableHeaderSize (AuthFormat); + Value += NameSizeOfVariable (Variable, AuthFormat); + Value += GET_PAD_SIZE (NameSizeOfVariable (Variable, AuthFormat)); return Value; } @@ -310,21 +337,24 @@ GetVariableDataOffset ( This code gets the pointer to the next variable header. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to next variable header. **/ VARIABLE_HEADER * GetNextVariablePtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ) { UINTN Value; - Value = (UINTN) GetVariableDataPtr (Variable); - Value += DataSizeOfVariable (Variable); - Value += GET_PAD_SIZE (DataSizeOfVariable (Variable)); + Value = (UINTN) GetVariableDataPtr (Variable, AuthFormat); + Value += DataSizeOfVariable (Variable, AuthFormat); + Value += GET_PAD_SIZE (DataSizeOfVariable (Variable, AuthFormat)); // // Be careful about pad size for alignment. @@ -415,6 +445,8 @@ VariableCompareTimeStampInternal ( @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute check at runtime when searching variable. @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @retval EFI_SUCCESS Variable found successfully @retval EFI_NOT_FOUND Variable not found @@ -424,7 +456,8 @@ FindVariableEx ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, IN BOOLEAN IgnoreRtCheck, - IN OUT VARIABLE_POINTER_TRACK *PtrTrack + IN OUT VARIABLE_POINTER_TRACK *PtrTrack, + IN BOOLEAN AuthFormat ) { VARIABLE_HEADER *InDeletedVariable; @@ -439,7 +472,7 @@ FindVariableEx ( for ( PtrTrack->CurrPtr = PtrTrack->StartPtr ; IsValidVariableHeader (PtrTrack->CurrPtr, PtrTrack->EndPtr) - ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr) + ; PtrTrack->CurrPtr = GetNextVariablePtr (PtrTrack->CurrPtr, AuthFormat) ) { if (PtrTrack->CurrPtr->State == VAR_ADDED || PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED) @@ -453,11 +486,11 @@ FindVariableEx ( return EFI_SUCCESS; } } else { - if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr))) { - Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr); + if (CompareGuid (VendorGuid, GetVendorGuidPtr (PtrTrack->CurrPtr, AuthFormat))) { + Point = (VOID *) GetVariableNamePtr (PtrTrack->CurrPtr, AuthFormat); - ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr) != 0); - if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr)) == 0) { + ASSERT (NameSizeOfVariable (PtrTrack->CurrPtr, AuthFormat) != 0); + if (CompareMem (VariableName, Point, NameSizeOfVariable (PtrTrack->CurrPtr, AuthFormat)) == 0) { if (PtrTrack->CurrPtr->State == (VAR_IN_DELETED_TRANSITION & VAR_ADDED)) { InDeletedVariable = PtrTrack->CurrPtr; } else { @@ -486,6 +519,8 @@ FindVariableEx ( @param[in] VariableStoreList A list of variable stores that should be used to get the next variable. The maximum number of entries is the max value of VARIABLE_STORE_TYPE. @param[out] VariablePtr Pointer to variable header address. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @retval EFI_SUCCESS The function completed successfully. @retval EFI_NOT_FOUND The next variable was not found. @@ -500,7 +535,8 @@ VariableServiceGetNextVariableInternal ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, IN VARIABLE_STORE_HEADER **VariableStoreList, - OUT VARIABLE_HEADER **VariablePtr + OUT VARIABLE_HEADER **VariablePtr, + IN BOOLEAN AuthFormat ) { EFI_STATUS Status; @@ -525,7 +561,7 @@ VariableServiceGetNextVariableInternal ( Variable.EndPtr = GetEndPointer (VariableStoreList[StoreType]); Variable.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile); - Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable); + Status = FindVariableEx (VariableName, VendorGuid, FALSE, &Variable, AuthFormat); if (!EFI_ERROR (Status)) { break; } @@ -552,7 +588,7 @@ VariableServiceGetNextVariableInternal ( // // If variable name is not empty, get next variable. // - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat); } while (TRUE) { @@ -605,13 +641,14 @@ VariableServiceGetNextVariableInternal ( VariablePtrTrack.StartPtr = Variable.StartPtr; VariablePtrTrack.EndPtr = Variable.EndPtr; Status = FindVariableEx ( - GetVariableNamePtr (Variable.CurrPtr), - GetVendorGuidPtr (Variable.CurrPtr), + GetVariableNamePtr (Variable.CurrPtr, AuthFormat), + GetVendorGuidPtr (Variable.CurrPtr, AuthFormat), FALSE, - &VariablePtrTrack + &VariablePtrTrack, + AuthFormat ); if (!EFI_ERROR (Status) && VariablePtrTrack.CurrPtr->State == VAR_ADDED) { - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat); continue; } } @@ -625,13 +662,14 @@ VariableServiceGetNextVariableInternal ( VariableInHob.StartPtr = GetStartPointer (VariableStoreList[VariableStoreTypeHob]); VariableInHob.EndPtr = GetEndPointer (VariableStoreList[VariableStoreTypeHob]); Status = FindVariableEx ( - GetVariableNamePtr (Variable.CurrPtr), - GetVendorGuidPtr (Variable.CurrPtr), + GetVariableNamePtr (Variable.CurrPtr, AuthFormat), + GetVendorGuidPtr (Variable.CurrPtr, AuthFormat), FALSE, - &VariableInHob + &VariableInHob, + AuthFormat ); if (!EFI_ERROR (Status)) { - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat); continue; } } @@ -642,7 +680,7 @@ VariableServiceGetNextVariableInternal ( } } - Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr); + Variable.CurrPtr = GetNextVariablePtr (Variable.CurrPtr, AuthFormat); } Done: diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h index 1777ce0e698..92a729d1408 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.h @@ -49,53 +49,65 @@ GetVariableStoreStatus ( /** This code gets the size of variable header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. + @return Size of variable header in bytes in type UINTN. **/ UINTN GetVariableHeaderSize ( - VOID + IN BOOLEAN AuthFormat ); /** This code gets the size of name of variable. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the variable header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return UINTN Size of variable in bytes. **/ UINTN NameSizeOfVariable ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** This code sets the size of name of variable. - @param[in] Variable Pointer to the Variable Header. - @param[in] NameSize Name size to set. + @param[in] Variable Pointer to the Variable Header. + @param[in] NameSize Name size to set. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. **/ VOID SetNameSizeOfVariable ( IN VARIABLE_HEADER *Variable, - IN UINTN NameSize + IN UINTN NameSize, + IN BOOLEAN AuthFormat ); /** This code gets the size of variable data. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Size of variable in bytes. **/ UINTN DataSizeOfVariable ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** @@ -103,80 +115,98 @@ DataSizeOfVariable ( @param[in] Variable Pointer to the Variable Header. @param[in] DataSize Data size to set. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. **/ VOID SetDataSizeOfVariable ( - IN VARIABLE_HEADER *Variable, - IN UINTN DataSize + IN VARIABLE_HEADER *Variable, + IN UINTN DataSize, + IN BOOLEAN AuthFormat ); /** This code gets the pointer to the variable name. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to Variable Name which is Unicode encoding. **/ CHAR16 * GetVariableNamePtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** This code gets the pointer to the variable guid. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return A EFI_GUID* pointer to Vendor Guid. **/ EFI_GUID * GetVendorGuidPtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** This code gets the pointer to the variable data. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to Variable Data. **/ UINT8 * GetVariableDataPtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** This code gets the variable data offset related to variable header. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Variable Data offset. **/ UINTN GetVariableDataOffset ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** This code gets the pointer to the next variable header. - @param Variable Pointer to the Variable Header. + @param[in] Variable Pointer to the Variable Header. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @return Pointer to next variable header. **/ VARIABLE_HEADER * GetNextVariablePtr ( - IN VARIABLE_HEADER *Variable + IN VARIABLE_HEADER *Variable, + IN BOOLEAN AuthFormat ); /** @@ -235,6 +265,8 @@ VariableCompareTimeStampInternal ( @param[in] IgnoreRtCheck Ignore EFI_VARIABLE_RUNTIME_ACCESS attribute check at runtime when searching variable. @param[in, out] PtrTrack Variable Track Pointer structure that contains Variable Information. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @retval EFI_SUCCESS Variable found successfully @retval EFI_NOT_FOUND Variable not found @@ -244,7 +276,8 @@ FindVariableEx ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, IN BOOLEAN IgnoreRtCheck, - IN OUT VARIABLE_POINTER_TRACK *PtrTrack + IN OUT VARIABLE_POINTER_TRACK *PtrTrack, + IN BOOLEAN AuthFormat ); /** @@ -258,10 +291,12 @@ FindVariableEx ( @param[in] VariableStoreList A list of variable stores that should be used to get the next variable. The maximum number of entries is the max value of VARIABLE_STORE_TYPE. @param[out] VariablePtr Pointer to variable header address. + @param[in] AuthFormat TRUE indicates authenticated variables are used. + FALSE indicates authenticated variables are not used. @retval EFI_SUCCESS The function completed successfully. @retval EFI_NOT_FOUND The next variable was not found. - @retval EFI_INVALID_PARAMETER If VariableName is nt an empty string, while VendorGuid is NULL. + @retval EFI_INVALID_PARAMETER If VariableName is not an empty string, while VendorGuid is NULL. @retval EFI_INVALID_PARAMETER The input values of VariableName and VendorGuid are not a name and GUID of an existing variable. @@ -272,7 +307,8 @@ VariableServiceGetNextVariableInternal ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, IN VARIABLE_STORE_HEADER **VariableStoreList, - OUT VARIABLE_HEADER **VariablePtr + OUT VARIABLE_HEADER **VariablePtr, + IN BOOLEAN AuthFormat ); /** diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c index ce409f22a3e..5e24bc4a624 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c @@ -975,8 +975,9 @@ MmVariableServiceInitialize ( ); ASSERT_EFI_ERROR (Status); - mVariableBufferPayloadSize = GetMaxVariableSize () + - OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) - GetVariableHeaderSize (); + mVariableBufferPayloadSize = GetMaxVariableSize () + + OFFSET_OF (SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY, Name) - + GetVariableHeaderSize (mVariableModuleGlobal->VariableGlobal.AuthFormat); Status = gMmst->MmAllocatePool ( EfiRuntimeServicesData, From 6b0d7b013e5e58963db7cab7911c95ce06c509fa Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Fri, 27 Sep 2019 15:34:14 -0700 Subject: [PATCH 043/384] MdeModulePkg/Variable: Add a file for NV variable functions This change adds a dedicated file for variable operations specific to non-volatile variables. This decreases the overall length of the relatively large Variable.c file. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../Universal/Variable/RuntimeDxe/Variable.c | 317 +---------------- .../Variable/RuntimeDxe/VariableNonVolatile.c | 334 ++++++++++++++++++ .../Variable/RuntimeDxe/VariableNonVolatile.h | 67 ++++ .../RuntimeDxe/VariableRuntimeDxe.inf | 2 + .../Variable/RuntimeDxe/VariableSmm.inf | 2 + .../RuntimeDxe/VariableStandaloneMm.inf | 2 + 6 files changed, 408 insertions(+), 316 deletions(-) create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 2e32905dfe8..0bd2f22e1a6 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -23,6 +23,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Variable.h" +#include "VariableNonVolatile.h" #include "VariableParsing.h" VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal; @@ -3079,25 +3080,6 @@ ReclaimForOS( } } -/** - Get non-volatile maximum variable size. - - @return Non-volatile maximum variable size. - -**/ -UINTN -GetNonVolatileMaxVariableSize ( - VOID - ) -{ - if (PcdGet32 (PcdHwErrStorageSize) != 0) { - return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)), - PcdGet32 (PcdMaxHardwareErrorVariableSize)); - } else { - return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)); - } -} - /** Get maximum variable size, covering both non-volatile and volatile variables. @@ -3122,303 +3104,6 @@ GetMaxVariableSize ( return MaxVariableSize; } -/** - Init real non-volatile variable store. - - @param[out] VariableStoreBase Output pointer to real non-volatile variable store base. - - @retval EFI_SUCCESS Function successfully executed. - @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. - @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. - -**/ -EFI_STATUS -InitRealNonVolatileVariableStore ( - OUT EFI_PHYSICAL_ADDRESS *VariableStoreBase - ) -{ - EFI_FIRMWARE_VOLUME_HEADER *FvHeader; - VARIABLE_STORE_HEADER *VariableStore; - UINT32 VariableStoreLength; - EFI_HOB_GUID_TYPE *GuidHob; - EFI_PHYSICAL_ADDRESS NvStorageBase; - UINT8 *NvStorageData; - UINT32 NvStorageSize; - FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *FtwLastWriteData; - UINT32 BackUpOffset; - UINT32 BackUpSize; - UINT32 HwErrStorageSize; - UINT32 MaxUserNvVariableSpaceSize; - UINT32 BoottimeReservedNvVariableSpaceSize; - EFI_STATUS Status; - VOID *FtwProtocol; - - mVariableModuleGlobal->FvbInstance = NULL; - - // - // Allocate runtime memory used for a memory copy of the FLASH region. - // Keep the memory and the FLASH in sync as updates occur. - // - NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize); - NvStorageData = AllocateRuntimeZeroPool (NvStorageSize); - if (NvStorageData == NULL) { - return EFI_OUT_OF_RESOURCES; - } - - NvStorageBase = NV_STORAGE_VARIABLE_BASE; - ASSERT (NvStorageBase != 0); - - // - // Copy NV storage data to the memory buffer. - // - CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize); - - Status = GetFtwProtocol ((VOID **)&FtwProtocol); - // - // If FTW protocol has been installed, no need to check FTW last write data hob. - // - if (EFI_ERROR (Status)) { - // - // Check the FTW last write data hob. - // - GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid); - if (GuidHob != NULL) { - FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob); - if (FtwLastWriteData->TargetAddress == NvStorageBase) { - DEBUG ((EFI_D_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress)); - // - // Copy the backed up NV storage data to the memory buffer from spare block. - // - CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize); - } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) && - (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) { - // - // Flash NV storage from the Offset is backed up in spare block. - // - BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase); - BackUpSize = NvStorageSize - BackUpOffset; - DEBUG ((EFI_D_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress)); - // - // Copy the partial backed up NV storage data to the memory buffer from spare block. - // - CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize); - } - } - } - - FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData; - - // - // Check if the Firmware Volume is not corrupted - // - if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) { - FreePool (NvStorageData); - DEBUG ((EFI_D_ERROR, "Firmware Volume for Variable Store is corrupted\n")); - return EFI_VOLUME_CORRUPTED; - } - - VariableStore = (VARIABLE_STORE_HEADER *) ((UINTN) FvHeader + FvHeader->HeaderLength); - VariableStoreLength = NvStorageSize - FvHeader->HeaderLength; - ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength); - ASSERT (VariableStore->Size == VariableStoreLength); - - // - // Check if the Variable Store header is not corrupted - // - if (GetVariableStoreStatus (VariableStore) != EfiValid) { - FreePool (NvStorageData); - DEBUG((EFI_D_ERROR, "Variable Store header is corrupted\n")); - return EFI_VOLUME_CORRUPTED; - } - - mNvFvHeaderCache = FvHeader; - - *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore; - - HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize); - MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize); - BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize); - - // - // Note that in EdkII variable driver implementation, Hardware Error Record type variable - // is stored with common variable in the same NV region. So the platform integrator should - // ensure that the value of PcdHwErrStorageSize is less than the value of - // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). - // - ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); - // - // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of - // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize). - // - ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize)); - // - // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of - // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize). - // - ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize)); - - mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize); - mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace); - mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize; - - DEBUG ((EFI_D_INFO, "Variable driver common space: 0x%x 0x%x 0x%x\n", mVariableModuleGlobal->CommonVariableSpace, mVariableModuleGlobal->CommonMaxUserVariableSpace, mVariableModuleGlobal->CommonRuntimeVariableSpace)); - - // - // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). - // - ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); - - return EFI_SUCCESS; -} - -/** - Init emulated non-volatile variable store. - - @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base. - - @retval EFI_SUCCESS Function successfully executed. - @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. - -**/ -EFI_STATUS -InitEmuNonVolatileVariableStore ( - EFI_PHYSICAL_ADDRESS *VariableStoreBase - ) -{ - VARIABLE_STORE_HEADER *VariableStore; - UINT32 VariableStoreLength; - BOOLEAN FullyInitializeStore; - UINT32 HwErrStorageSize; - - FullyInitializeStore = TRUE; - - VariableStoreLength = PcdGet32 (PcdVariableStoreSize); - ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength); - - // - // Allocate memory for variable store. - // - if (PcdGet64 (PcdEmuVariableNvStoreReserved) == 0) { - VariableStore = (VARIABLE_STORE_HEADER *) AllocateRuntimePool (VariableStoreLength); - if (VariableStore == NULL) { - return EFI_OUT_OF_RESOURCES; - } - } else { - // - // A memory location has been reserved for the NV variable store. Certain - // platforms may be able to preserve a memory range across system resets, - // thereby providing better NV variable emulation. - // - VariableStore = - (VARIABLE_STORE_HEADER *)(VOID*)(UINTN) - PcdGet64 (PcdEmuVariableNvStoreReserved); - if ((VariableStore->Size == VariableStoreLength) && - (CompareGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid) || - CompareGuid (&VariableStore->Signature, &gEfiVariableGuid)) && - (VariableStore->Format == VARIABLE_STORE_FORMATTED) && - (VariableStore->State == VARIABLE_STORE_HEALTHY)) { - DEBUG(( - DEBUG_INFO, - "Variable Store reserved at %p appears to be valid\n", - VariableStore - )); - FullyInitializeStore = FALSE; - } - } - - if (FullyInitializeStore) { - SetMem (VariableStore, VariableStoreLength, 0xff); - // - // Use gEfiAuthenticatedVariableGuid for potential auth variable support. - // - CopyGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid); - VariableStore->Size = VariableStoreLength; - VariableStore->Format = VARIABLE_STORE_FORMATTED; - VariableStore->State = VARIABLE_STORE_HEALTHY; - VariableStore->Reserved = 0; - VariableStore->Reserved1 = 0; - } - - *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore; - - HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize); - - // - // Note that in EdkII variable driver implementation, Hardware Error Record type variable - // is stored with common variable in the same NV region. So the platform integrator should - // ensure that the value of PcdHwErrStorageSize is less than the value of - // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). - // - ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); - - mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize); - mVariableModuleGlobal->CommonMaxUserVariableSpace = mVariableModuleGlobal->CommonVariableSpace; - mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace; - - return EFI_SUCCESS; -} - -/** - Init non-volatile variable store. - - @retval EFI_SUCCESS Function successfully executed. - @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. - @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. - -**/ -EFI_STATUS -InitNonVolatileVariableStore ( - VOID - ) -{ - VARIABLE_HEADER *Variable; - VARIABLE_HEADER *NextVariable; - EFI_PHYSICAL_ADDRESS VariableStoreBase; - UINTN VariableSize; - EFI_STATUS Status; - - if (PcdGetBool (PcdEmuVariableNvModeEnable)) { - Status = InitEmuNonVolatileVariableStore (&VariableStoreBase); - if (EFI_ERROR (Status)) { - return Status; - } - mVariableModuleGlobal->VariableGlobal.EmuNvMode = TRUE; - DEBUG ((DEBUG_INFO, "Variable driver will work at emulated non-volatile variable mode!\n")); - } else { - Status = InitRealNonVolatileVariableStore (&VariableStoreBase); - if (EFI_ERROR (Status)) { - return Status; - } - mVariableModuleGlobal->VariableGlobal.EmuNvMode = FALSE; - } - - mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase; - mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase; - mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid)); - - mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize); - mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize); - - // - // Parse non-volatile variable data and get last variable offset. - // - Variable = GetStartPointer (mNvVariableCache); - while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) { - NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat); - VariableSize = (UINTN) NextVariable - (UINTN) Variable; - if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { - mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; - } else { - mVariableModuleGlobal->CommonVariableTotalSize += VariableSize; - } - - Variable = NextVariable; - } - mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) mNvVariableCache; - - return EFI_SUCCESS; -} - /** Flush the HOB variable to flash. diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c new file mode 100644 index 00000000000..0637a828b33 --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.c @@ -0,0 +1,334 @@ +/** @file + Common variable non-volatile store routines. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "VariableNonVolatile.h" +#include "VariableParsing.h" + +extern VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal; + +/** + Get non-volatile maximum variable size. + + @return Non-volatile maximum variable size. + +**/ +UINTN +GetNonVolatileMaxVariableSize ( + VOID + ) +{ + if (PcdGet32 (PcdHwErrStorageSize) != 0) { + return MAX (MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)), + PcdGet32 (PcdMaxHardwareErrorVariableSize)); + } else { + return MAX (PcdGet32 (PcdMaxVariableSize), PcdGet32 (PcdMaxAuthVariableSize)); + } +} + +/** + Init emulated non-volatile variable store. + + @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + +**/ +EFI_STATUS +InitEmuNonVolatileVariableStore ( + OUT EFI_PHYSICAL_ADDRESS *VariableStoreBase + ) +{ + VARIABLE_STORE_HEADER *VariableStore; + UINT32 VariableStoreLength; + BOOLEAN FullyInitializeStore; + UINT32 HwErrStorageSize; + + FullyInitializeStore = TRUE; + + VariableStoreLength = PcdGet32 (PcdVariableStoreSize); + ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength); + + // + // Allocate memory for variable store. + // + if (PcdGet64 (PcdEmuVariableNvStoreReserved) == 0) { + VariableStore = (VARIABLE_STORE_HEADER *) AllocateRuntimePool (VariableStoreLength); + if (VariableStore == NULL) { + return EFI_OUT_OF_RESOURCES; + } + } else { + // + // A memory location has been reserved for the NV variable store. Certain + // platforms may be able to preserve a memory range across system resets, + // thereby providing better NV variable emulation. + // + VariableStore = + (VARIABLE_STORE_HEADER *)(VOID*)(UINTN) + PcdGet64 (PcdEmuVariableNvStoreReserved); + if ((VariableStore->Size == VariableStoreLength) && + (CompareGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid) || + CompareGuid (&VariableStore->Signature, &gEfiVariableGuid)) && + (VariableStore->Format == VARIABLE_STORE_FORMATTED) && + (VariableStore->State == VARIABLE_STORE_HEALTHY)) { + DEBUG(( + DEBUG_INFO, + "Variable Store reserved at %p appears to be valid\n", + VariableStore + )); + FullyInitializeStore = FALSE; + } + } + + if (FullyInitializeStore) { + SetMem (VariableStore, VariableStoreLength, 0xff); + // + // Use gEfiAuthenticatedVariableGuid for potential auth variable support. + // + CopyGuid (&VariableStore->Signature, &gEfiAuthenticatedVariableGuid); + VariableStore->Size = VariableStoreLength; + VariableStore->Format = VARIABLE_STORE_FORMATTED; + VariableStore->State = VARIABLE_STORE_HEALTHY; + VariableStore->Reserved = 0; + VariableStore->Reserved1 = 0; + } + + *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore; + + HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize); + + // + // Note that in EdkII variable driver implementation, Hardware Error Record type variable + // is stored with common variable in the same NV region. So the platform integrator should + // ensure that the value of PcdHwErrStorageSize is less than the value of + // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). + // + ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); + + mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize); + mVariableModuleGlobal->CommonMaxUserVariableSpace = mVariableModuleGlobal->CommonVariableSpace; + mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace; + + return EFI_SUCCESS; +} + +/** + Init real non-volatile variable store. + + @param[out] VariableStoreBase Output pointer to real non-volatile variable store base. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. + +**/ +EFI_STATUS +InitRealNonVolatileVariableStore ( + OUT EFI_PHYSICAL_ADDRESS *VariableStoreBase + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + VARIABLE_STORE_HEADER *VariableStore; + UINT32 VariableStoreLength; + EFI_HOB_GUID_TYPE *GuidHob; + EFI_PHYSICAL_ADDRESS NvStorageBase; + UINT8 *NvStorageData; + UINT32 NvStorageSize; + FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *FtwLastWriteData; + UINT32 BackUpOffset; + UINT32 BackUpSize; + UINT32 HwErrStorageSize; + UINT32 MaxUserNvVariableSpaceSize; + UINT32 BoottimeReservedNvVariableSpaceSize; + EFI_STATUS Status; + VOID *FtwProtocol; + + mVariableModuleGlobal->FvbInstance = NULL; + + // + // Allocate runtime memory used for a memory copy of the FLASH region. + // Keep the memory and the FLASH in sync as updates occur. + // + NvStorageSize = PcdGet32 (PcdFlashNvStorageVariableSize); + NvStorageData = AllocateRuntimeZeroPool (NvStorageSize); + if (NvStorageData == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + NvStorageBase = NV_STORAGE_VARIABLE_BASE; + ASSERT (NvStorageBase != 0); + + // + // Copy NV storage data to the memory buffer. + // + CopyMem (NvStorageData, (UINT8 *) (UINTN) NvStorageBase, NvStorageSize); + + Status = GetFtwProtocol ((VOID **)&FtwProtocol); + // + // If FTW protocol has been installed, no need to check FTW last write data hob. + // + if (EFI_ERROR (Status)) { + // + // Check the FTW last write data hob. + // + GuidHob = GetFirstGuidHob (&gEdkiiFaultTolerantWriteGuid); + if (GuidHob != NULL) { + FtwLastWriteData = (FAULT_TOLERANT_WRITE_LAST_WRITE_DATA *) GET_GUID_HOB_DATA (GuidHob); + if (FtwLastWriteData->TargetAddress == NvStorageBase) { + DEBUG ((DEBUG_INFO, "Variable: NV storage is backed up in spare block: 0x%x\n", (UINTN) FtwLastWriteData->SpareAddress)); + // + // Copy the backed up NV storage data to the memory buffer from spare block. + // + CopyMem (NvStorageData, (UINT8 *) (UINTN) (FtwLastWriteData->SpareAddress), NvStorageSize); + } else if ((FtwLastWriteData->TargetAddress > NvStorageBase) && + (FtwLastWriteData->TargetAddress < (NvStorageBase + NvStorageSize))) { + // + // Flash NV storage from the Offset is backed up in spare block. + // + BackUpOffset = (UINT32) (FtwLastWriteData->TargetAddress - NvStorageBase); + BackUpSize = NvStorageSize - BackUpOffset; + DEBUG ((DEBUG_INFO, "Variable: High partial NV storage from offset: %x is backed up in spare block: 0x%x\n", BackUpOffset, (UINTN) FtwLastWriteData->SpareAddress)); + // + // Copy the partial backed up NV storage data to the memory buffer from spare block. + // + CopyMem (NvStorageData + BackUpOffset, (UINT8 *) (UINTN) FtwLastWriteData->SpareAddress, BackUpSize); + } + } + } + + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *) NvStorageData; + + // + // Check if the Firmware Volume is not corrupted + // + if ((FvHeader->Signature != EFI_FVH_SIGNATURE) || (!CompareGuid (&gEfiSystemNvDataFvGuid, &FvHeader->FileSystemGuid))) { + FreePool (NvStorageData); + DEBUG ((DEBUG_ERROR, "Firmware Volume for Variable Store is corrupted\n")); + return EFI_VOLUME_CORRUPTED; + } + + VariableStore = (VARIABLE_STORE_HEADER *) ((UINTN) FvHeader + FvHeader->HeaderLength); + VariableStoreLength = NvStorageSize - FvHeader->HeaderLength; + ASSERT (sizeof (VARIABLE_STORE_HEADER) <= VariableStoreLength); + ASSERT (VariableStore->Size == VariableStoreLength); + + // + // Check if the Variable Store header is not corrupted + // + if (GetVariableStoreStatus (VariableStore) != EfiValid) { + FreePool (NvStorageData); + DEBUG((DEBUG_ERROR, "Variable Store header is corrupted\n")); + return EFI_VOLUME_CORRUPTED; + } + + mNvFvHeaderCache = FvHeader; + + *VariableStoreBase = (EFI_PHYSICAL_ADDRESS) (UINTN) VariableStore; + + HwErrStorageSize = PcdGet32 (PcdHwErrStorageSize); + MaxUserNvVariableSpaceSize = PcdGet32 (PcdMaxUserNvVariableSpaceSize); + BoottimeReservedNvVariableSpaceSize = PcdGet32 (PcdBoottimeReservedNvVariableSpaceSize); + + // + // Note that in EdkII variable driver implementation, Hardware Error Record type variable + // is stored with common variable in the same NV region. So the platform integrator should + // ensure that the value of PcdHwErrStorageSize is less than the value of + // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). + // + ASSERT (HwErrStorageSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); + // + // Ensure that the value of PcdMaxUserNvVariableSpaceSize is less than the value of + // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize). + // + ASSERT (MaxUserNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize)); + // + // Ensure that the value of PcdBoottimeReservedNvVariableSpaceSize is less than the value of + // (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)) - PcdGet32 (PcdHwErrStorageSize). + // + ASSERT (BoottimeReservedNvVariableSpaceSize < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize)); + + mVariableModuleGlobal->CommonVariableSpace = ((UINTN) VariableStoreLength - sizeof (VARIABLE_STORE_HEADER) - HwErrStorageSize); + mVariableModuleGlobal->CommonMaxUserVariableSpace = ((MaxUserNvVariableSpaceSize != 0) ? MaxUserNvVariableSpaceSize : mVariableModuleGlobal->CommonVariableSpace); + mVariableModuleGlobal->CommonRuntimeVariableSpace = mVariableModuleGlobal->CommonVariableSpace - BoottimeReservedNvVariableSpaceSize; + + DEBUG (( + DEBUG_INFO, + "Variable driver common space: 0x%x 0x%x 0x%x\n", + mVariableModuleGlobal->CommonVariableSpace, + mVariableModuleGlobal->CommonMaxUserVariableSpace, + mVariableModuleGlobal->CommonRuntimeVariableSpace + )); + + // + // The max NV variable size should be < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER)). + // + ASSERT (GetNonVolatileMaxVariableSize () < (VariableStoreLength - sizeof (VARIABLE_STORE_HEADER))); + + return EFI_SUCCESS; +} + +/** + Init non-volatile variable store. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. + +**/ +EFI_STATUS +InitNonVolatileVariableStore ( + VOID + ) +{ + VARIABLE_HEADER *Variable; + VARIABLE_HEADER *NextVariable; + EFI_PHYSICAL_ADDRESS VariableStoreBase; + UINTN VariableSize; + EFI_STATUS Status; + + if (PcdGetBool (PcdEmuVariableNvModeEnable)) { + Status = InitEmuNonVolatileVariableStore (&VariableStoreBase); + if (EFI_ERROR (Status)) { + return Status; + } + mVariableModuleGlobal->VariableGlobal.EmuNvMode = TRUE; + DEBUG ((DEBUG_INFO, "Variable driver will work at emulated non-volatile variable mode!\n")); + } else { + Status = InitRealNonVolatileVariableStore (&VariableStoreBase); + if (EFI_ERROR (Status)) { + return Status; + } + mVariableModuleGlobal->VariableGlobal.EmuNvMode = FALSE; + } + + mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase = VariableStoreBase; + mNvVariableCache = (VARIABLE_STORE_HEADER *) (UINTN) VariableStoreBase; + mVariableModuleGlobal->VariableGlobal.AuthFormat = (BOOLEAN)(CompareGuid (&mNvVariableCache->Signature, &gEfiAuthenticatedVariableGuid)); + + mVariableModuleGlobal->MaxVariableSize = PcdGet32 (PcdMaxVariableSize); + mVariableModuleGlobal->MaxAuthVariableSize = ((PcdGet32 (PcdMaxAuthVariableSize) != 0) ? PcdGet32 (PcdMaxAuthVariableSize) : mVariableModuleGlobal->MaxVariableSize); + + // + // Parse non-volatile variable data and get last variable offset. + // + Variable = GetStartPointer (mNvVariableCache); + while (IsValidVariableHeader (Variable, GetEndPointer (mNvVariableCache))) { + NextVariable = GetNextVariablePtr (Variable, mVariableModuleGlobal->VariableGlobal.AuthFormat); + VariableSize = (UINTN) NextVariable - (UINTN) Variable; + if ((Variable->Attributes & (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) == (EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_HARDWARE_ERROR_RECORD)) { + mVariableModuleGlobal->HwErrVariableTotalSize += VariableSize; + } else { + mVariableModuleGlobal->CommonVariableTotalSize += VariableSize; + } + + Variable = NextVariable; + } + mVariableModuleGlobal->NonVolatileLastVariableOffset = (UINTN) Variable - (UINTN) mNvVariableCache; + + return EFI_SUCCESS; +} diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h new file mode 100644 index 00000000000..43653f27e6e --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableNonVolatile.h @@ -0,0 +1,67 @@ +/** @file + Common variable non-volatile store routines. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _VARIABLE_NON_VOLATILE_H_ +#define _VARIABLE_NON_VOLATILE_H_ + +#include "Variable.h" + +/** + Get non-volatile maximum variable size. + + @return Non-volatile maximum variable size. + +**/ +UINTN +GetNonVolatileMaxVariableSize ( + VOID + ); + +/** + Init emulated non-volatile variable store. + + @param[out] VariableStoreBase Output pointer to emulated non-volatile variable store base. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + +**/ +EFI_STATUS +InitEmuNonVolatileVariableStore ( + EFI_PHYSICAL_ADDRESS *VariableStoreBase + ); + +/** + Init real non-volatile variable store. + + @param[out] VariableStoreBase Output pointer to real non-volatile variable store base. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. + +**/ +EFI_STATUS +InitRealNonVolatileVariableStore ( + OUT EFI_PHYSICAL_ADDRESS *VariableStoreBase + ); + +/** + Init non-volatile variable store. + + @retval EFI_SUCCESS Function successfully executed. + @retval EFI_OUT_OF_RESOURCES Fail to allocate enough memory resource. + @retval EFI_VOLUME_CORRUPTED Variable Store or Firmware Volume for Variable Store is corrupted. + +**/ +EFI_STATUS +InitNonVolatileVariableStore ( + VOID + ); + +#endif diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf index c35e5fe7878..08a54907870 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf @@ -36,6 +36,8 @@ Variable.c VariableDxe.c Variable.h + VariableNonVolatile.c + VariableNonVolatile.h VariableParsing.c VariableParsing.h PrivilegePolymorphic.h diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf index 626738b9c77..6dc2721b816 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf @@ -45,6 +45,8 @@ Variable.c VariableTraditionalMm.c VariableSmm.c + VariableNonVolatile.c + VariableNonVolatile.h VariableParsing.c VariableParsing.h VarCheck.c diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf index ff714b193a7..f8a37429595 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf @@ -45,6 +45,8 @@ Variable.c VariableSmm.c VariableStandaloneMm.c + VariableNonVolatile.c + VariableNonVolatile.h VariableParsing.c VariableParsing.h VarCheck.c From 1747ab6c1c27033529a3b8aa1ccee64d12b35dcd Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 25 Sep 2019 14:58:45 -0700 Subject: [PATCH 044/384] MdeModulePkg VariableInfo: Always consider RT DXE and SMM stats REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220 The current VariableInfo application only checks for variable statistics from SMM if the variable information entries are not present in the UEFI System Configuration table as published by the DXE UEFI variable driver (VariableRuntimeDxe). This change first checks for variable information entries in the UEFI System Configuration but always checks for entries in SMM as well. If the SMM variable driver is not present, an instance of EFI_SMM_VARIABLE_PROTOCOL will not be found and the search for SMM variable statistics will be aborted (an SW SMI to get variable statistics will not be triggered). In the case variable statistics are provided by both a Runtime DXE driver (e.g. VariableSmmRuntimeDxe) and a SMM driver (VariableSmm), this change will clearly identify statistics from each respective driver. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Acked-by: Hao A Wu --- .../Application/VariableInfo/VariableInfo.c | 37 +++++++++---------- 1 file changed, 18 insertions(+), 19 deletions(-) diff --git a/MdeModulePkg/Application/VariableInfo/VariableInfo.c b/MdeModulePkg/Application/VariableInfo/VariableInfo.c index f213471e9ab..c04ba182132 100644 --- a/MdeModulePkg/Application/VariableInfo/VariableInfo.c +++ b/MdeModulePkg/Application/VariableInfo/VariableInfo.c @@ -3,7 +3,7 @@ this utility will print out the statistics information. You can use console redirection to capture the data. - Copyright (c) 2006 - 2016, Intel Corporation. All rights reserved.
+ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -126,7 +126,7 @@ PrintInfoFromSmm ( ASSERT (CommBuffer != NULL); ZeroMem (CommBuffer, RealCommSize); - Print (L"Non-Volatile SMM Variables:\n"); + Print (L"SMM Driver Non-Volatile Variables:\n"); do { CommSize = RealCommSize; Status = GetVariableStatisticsData (CommBuffer, &CommSize); @@ -155,7 +155,7 @@ PrintInfoFromSmm ( } } while (TRUE); - Print (L"Volatile SMM Variables:\n"); + Print (L"SMM Driver Volatile Variables:\n"); ZeroMem (CommBuffer, RealCommSize); do { CommSize = RealCommSize; @@ -207,24 +207,18 @@ UefiMain ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; + EFI_STATUS RuntimeDxeStatus; + EFI_STATUS SmmStatus; VARIABLE_INFO_ENTRY *VariableInfo; VARIABLE_INFO_ENTRY *Entry; - Status = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **)&Entry); - if (EFI_ERROR (Status) || (Entry == NULL)) { - Status = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **)&Entry); + RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiVariableGuid, (VOID **) &Entry); + if (EFI_ERROR (RuntimeDxeStatus) || (Entry == NULL)) { + RuntimeDxeStatus = EfiGetSystemConfigurationTable (&gEfiAuthenticatedVariableGuid, (VOID **) &Entry); } - if (EFI_ERROR (Status) || (Entry == NULL)) { - Status = PrintInfoFromSmm (); - if (!EFI_ERROR (Status)) { - return Status; - } - } - - if (!EFI_ERROR (Status) && (Entry != NULL)) { - Print (L"Non-Volatile EFI Variables:\n"); + if (!EFI_ERROR (RuntimeDxeStatus) && (Entry != NULL)) { + Print (L"Runtime DXE Driver Non-Volatile EFI Variables:\n"); VariableInfo = Entry; do { if (!VariableInfo->Volatile) { @@ -242,7 +236,7 @@ UefiMain ( VariableInfo = VariableInfo->Next; } while (VariableInfo != NULL); - Print (L"Volatile EFI Variables:\n"); + Print (L"Runtime DXE Driver Volatile EFI Variables:\n"); VariableInfo = Entry; do { if (VariableInfo->Volatile) { @@ -258,14 +252,19 @@ UefiMain ( } VariableInfo = VariableInfo->Next; } while (VariableInfo != NULL); + } + + SmmStatus = PrintInfoFromSmm (); - } else { + if (EFI_ERROR (RuntimeDxeStatus) && EFI_ERROR (SmmStatus)) { Print (L"Warning: Variable Dxe/Smm driver doesn't enable the feature of statistical information!\n"); Print (L"If you want to see this info, please:\n"); Print (L" 1. Set PcdVariableCollectStatistics as TRUE\n"); Print (L" 2. Rebuild Variable Dxe/Smm driver\n"); Print (L" 3. Run \"VariableInfo\" cmd again\n"); + + return EFI_NOT_FOUND; } - return Status; + return EFI_SUCCESS; } From aab3b9b9a1e5e1f3fa966fb1667fc3e6c47e7706 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 23 Sep 2019 16:48:09 -0700 Subject: [PATCH 045/384] MdeModulePkg/Variable: Add RT GetVariable() cache support REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2220 This change reduces SMIs for GetVariable () by maintaining a UEFI variable cache in Runtime DXE in addition to the pre- existing cache in SMRAM. When the Runtime Service GetVariable() is invoked, a Runtime DXE cache is used instead of triggering an SMI to VariableSmm. This can improve overall system performance by servicing variable read requests without rendezvousing all cores into SMM. The runtime cache can be disabled with by setting the FeaturePCD gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache to FALSE. If the PCD is set to FALSE, the runtime cache will not be used and an SMI will be triggered for Runtime Service GetVariable () and GetNextVariableName () invocations. The following are important points regarding the behavior of the variable drivers when the variable runtime cache is enabled. 1. All of the non-volatile storage contents are loaded into the cache upon driver load. This one time load operation from storage is preferred as opposed to building the cache on demand. An on- demand cache would require a fallback SMI to load data into the cache as variables are requested. 2. SetVariable () requests will continue to always trigger an SMI. This occurs regardless of whether the variable is volatile or non-volatile. 3. Both volatile and non-volatile variables are cached in a runtime buffer. As is the case in the current EDK II variable driver, they continue to be cached in separate buffers. 4. The cache in Runtime DXE and SMM are intended to be exact copies of one another. All SMM variable accesses only return data from the SMM cache. The runtime caches are only updated after the variable I/O operation is successful in SMM. The runtime caches are only updated from SMM. 5. Synchronization mechanisms are in place to ensure the runtime cache content integrity with the SMM cache. These may result in updates to runtime cache that are the same in content but different in offset and size from updates to the SMM cache. When using SMM variables with runtime cache enabled, two caches will now be present. 1. "Runtime Cache" - Maintained in VariableSmmRuntimeDxe. Used to service Runtime Services GetVariable () and GetNextVariableName () callers. 2. "SMM Cache" - Maintained in VariableSmm to service SMM GetVariable () and GetNextVariableName () callers. a. This cache is retained so SMM modules do not operate on data outside SMRAM. Because a race condition can occur if an SMI occurs during the execution of runtime code reading from the runtime cache, a runtime cache read lock is introduced that explicitly moves pending updates from SMM to the runtime cache if an SMM update occurs while the runtime cache is locked. Note that it is not expected a Runtime services call will interrupt SMM processing since all CPU cores rendezvous in SMM. It is possible to view UEFI variable read and write statistics by setting the gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics FeaturePcd to TRUE and using the VariableInfo UEFI application in MdeModulePkg to dump variable statistics to the console. By doing so, a user can view the number of GetVariable () hits from the Runtime DXE variable driver (Runtime Cache hits) and the SMM variable driver (SMM Cache hits). SMM Cache hits for GetVariable () will occur when SMM modules invoke GetVariable (). Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang --- MdeModulePkg/Include/Guid/SmmVariableCommon.h | 29 +- MdeModulePkg/MdeModulePkg.dec | 12 + .../Universal/Variable/RuntimeDxe/Variable.c | 50 +- .../Universal/Variable/RuntimeDxe/Variable.h | 32 +- .../RuntimeDxe/VariableRuntimeCache.c | 153 ++++++ .../RuntimeDxe/VariableRuntimeCache.h | 51 ++ .../RuntimeDxe/VariableRuntimeDxe.inf | 2 + .../Variable/RuntimeDxe/VariableSmm.c | 189 ++++++- .../Variable/RuntimeDxe/VariableSmm.inf | 2 + .../RuntimeDxe/VariableSmmRuntimeDxe.c | 512 +++++++++++++++++- .../RuntimeDxe/VariableSmmRuntimeDxe.inf | 18 +- .../RuntimeDxe/VariableStandaloneMm.inf | 2 + 12 files changed, 1011 insertions(+), 41 deletions(-) create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c create mode 100644 MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h diff --git a/MdeModulePkg/Include/Guid/SmmVariableCommon.h b/MdeModulePkg/Include/Guid/SmmVariableCommon.h index c527a598913..ceef44dfd2d 100644 --- a/MdeModulePkg/Include/Guid/SmmVariableCommon.h +++ b/MdeModulePkg/Include/Guid/SmmVariableCommon.h @@ -1,7 +1,7 @@ /** @file The file defined some common structures used for communicating between SMM variable module and SMM variable wrapper module. -Copyright (c) 2011 - 2015, Intel Corporation. All rights reserved.
+Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -9,6 +9,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #ifndef _SMM_VARIABLE_COMMON_H_ #define _SMM_VARIABLE_COMMON_H_ +#include #include #define EFI_SMM_VARIABLE_WRITE_GUID \ @@ -66,6 +67,16 @@ typedef struct { #define SMM_VARIABLE_FUNCTION_VAR_CHECK_VARIABLE_PROPERTY_GET 10 #define SMM_VARIABLE_FUNCTION_GET_PAYLOAD_SIZE 11 +// +// The payload for this function is SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT +// +#define SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT 12 + +#define SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE 13 +// +// The payload for this function is SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO +// +#define SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO 14 /// /// Size of SMM communicate header, without including the payload. @@ -120,4 +131,20 @@ typedef struct { UINTN VariablePayloadSize; } SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE; +typedef struct { + BOOLEAN *ReadLock; + BOOLEAN *PendingUpdate; + BOOLEAN *HobFlushComplete; + VARIABLE_STORE_HEADER *RuntimeHobCache; + VARIABLE_STORE_HEADER *RuntimeNvCache; + VARIABLE_STORE_HEADER *RuntimeVolatileCache; +} SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT; + +typedef struct { + UINTN TotalHobStorageSize; + UINTN TotalNvStorageSize; + UINTN TotalVolatileStorageSize; + BOOLEAN AuthenticatedVariableUsage; +} SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO; + #endif // _SMM_VARIABLE_COMMON_H_ diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index d6bac974da9..3ef8fe7644d 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -641,6 +641,18 @@ # @Prompt Enable Device Path From Text support. gEfiMdeModulePkgTokenSpaceGuid.PcdDevicePathSupportDevicePathFromText|TRUE|BOOLEAN|0x00010038 + ## Indicates if the UEFI variable runtime cache should be enabled. + # This setting only applies if SMM variables are enabled. When enabled, all variable + # data for Runtime Service GetVariable () and GetNextVariableName () calls is retrieved + # from a runtime data buffer referred to as the "runtime cache". An SMI is not triggered + # at all for these requests. Variables writes still trigger an SMI. This can greatly + # reduce overall system SMM usage as most boots tend to issue far more variable reads + # than writes.

+ # TRUE - The UEFI variable runtime cache is enabled.
+ # FALSE - The UEFI variable runtime cache is disabled.
+ # @Prompt Enable the UEFI variable runtime cache. + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE|BOOLEAN|0x00010039 + ## Indicates if the statistics about variable usage will be collected. This information is # stored as a vendor configuration table into the EFI system table. # Set this PCD to TRUE to use VariableInfo application in MdeModulePkg\Application directory to get diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 0bd2f22e1a6..29d6aca9938 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -25,6 +25,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "Variable.h" #include "VariableNonVolatile.h" #include "VariableParsing.h" +#include "VariableRuntimeCache.h" VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal; @@ -332,6 +333,12 @@ RecordVarErrorFlag ( // Update the data in NV cache. // *VarErrFlag = TempFlag; + Status = SynchronizeRuntimeVariableCache ( + &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache, + (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, + sizeof (TempFlag) + ); + ASSERT_EFI_ERROR (Status); } } } @@ -766,12 +773,24 @@ Reclaim ( Done: if (IsVolatile || mVariableModuleGlobal->VariableGlobal.EmuNvMode) { + Status = SynchronizeRuntimeVariableCache ( + &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache, + 0, + VariableStoreHeader->Size + ); + ASSERT_EFI_ERROR (Status); FreePool (ValidBuffer); } else { // // For NV variable reclaim, we use mNvVariableCache as the buffer, so copy the data back. // - CopyMem (mNvVariableCache, (UINT8 *)(UINTN)VariableBase, VariableStoreHeader->Size); + CopyMem (mNvVariableCache, (UINT8 *) (UINTN) VariableBase, VariableStoreHeader->Size); + Status = SynchronizeRuntimeVariableCache ( + &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache, + 0, + VariableStoreHeader->Size + ); + ASSERT_EFI_ERROR (Status); } return Status; @@ -1614,6 +1633,7 @@ UpdateVariable ( VARIABLE_POINTER_TRACK *Variable; VARIABLE_POINTER_TRACK NvVariable; VARIABLE_STORE_HEADER *VariableStoreHeader; + VARIABLE_RUNTIME_CACHE *VolatileCacheInstance; UINT8 *BufferForMerge; UINTN MergedBufSize; BOOLEAN DataReady; @@ -2275,6 +2295,23 @@ UpdateVariable ( } Done: + if (!EFI_ERROR (Status)) { + if (Variable->Volatile) { + VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache); + } else { + VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache); + } + + if (VolatileCacheInstance->Store != NULL) { + Status = SynchronizeRuntimeVariableCache ( + VolatileCacheInstance, + 0, + VolatileCacheInstance->Store->Size + ); + ASSERT_EFI_ERROR (Status); + } + } + return Status; } @@ -3200,6 +3237,14 @@ FlushHobVariableToFlash ( ErrorFlag = TRUE; } } + if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store != NULL) { + Status = SynchronizeRuntimeVariableCache ( + &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache, + 0, + mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeHobCache.Store->Size + ); + ASSERT_EFI_ERROR (Status); + } if (ErrorFlag) { // // We still have HOB variable(s) not flushed in flash. @@ -3210,6 +3255,9 @@ FlushHobVariableToFlash ( // All HOB variables have been flushed in flash. // DEBUG ((EFI_D_INFO, "Variable driver: all HOB variables have been flushed in flash.\n")); + if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete != NULL) { + *(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.HobFlushComplete) = TRUE; + } if (!AtRuntime ()) { FreePool ((VOID *) VariableStoreHeader); } diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h index fb574b2e328..0b2bb6ae664 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h @@ -64,6 +64,21 @@ typedef enum { VariableStoreTypeMax } VARIABLE_STORE_TYPE; +typedef struct { + UINT32 PendingUpdateOffset; + UINT32 PendingUpdateLength; + VARIABLE_STORE_HEADER *Store; +} VARIABLE_RUNTIME_CACHE; + +typedef struct { + BOOLEAN *ReadLock; + BOOLEAN *PendingUpdate; + BOOLEAN *HobFlushComplete; + VARIABLE_RUNTIME_CACHE VariableRuntimeHobCache; + VARIABLE_RUNTIME_CACHE VariableRuntimeNvCache; + VARIABLE_RUNTIME_CACHE VariableRuntimeVolatileCache; +} VARIABLE_RUNTIME_CACHE_CONTEXT; + typedef struct { VARIABLE_HEADER *CurrPtr; // @@ -79,14 +94,15 @@ typedef struct { } VARIABLE_POINTER_TRACK; typedef struct { - EFI_PHYSICAL_ADDRESS HobVariableBase; - EFI_PHYSICAL_ADDRESS VolatileVariableBase; - EFI_PHYSICAL_ADDRESS NonVolatileVariableBase; - EFI_LOCK VariableServicesLock; - UINT32 ReentrantState; - BOOLEAN AuthFormat; - BOOLEAN AuthSupport; - BOOLEAN EmuNvMode; + EFI_PHYSICAL_ADDRESS HobVariableBase; + EFI_PHYSICAL_ADDRESS VolatileVariableBase; + EFI_PHYSICAL_ADDRESS NonVolatileVariableBase; + VARIABLE_RUNTIME_CACHE_CONTEXT VariableRuntimeCacheContext; + EFI_LOCK VariableServicesLock; + UINT32 ReentrantState; + BOOLEAN AuthFormat; + BOOLEAN AuthSupport; + BOOLEAN EmuNvMode; } VARIABLE_GLOBAL; typedef struct { diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c new file mode 100644 index 00000000000..bc93cc07d21 --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.c @@ -0,0 +1,153 @@ +/** @file + Functions related to managing the UEFI variable runtime cache. This file should only include functions + used by the SMM UEFI variable driver. + + Caution: This module requires additional review when modified. + This driver will have external input - variable data. They may be input in SMM mode. + This external input must be validated carefully to avoid security issue like + buffer overflow, integer overflow. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include "VariableParsing.h" +#include "VariableRuntimeCache.h" + +extern VARIABLE_MODULE_GLOBAL *mVariableModuleGlobal; +extern VARIABLE_STORE_HEADER *mNvVariableCache; + +/** + Copies any pending updates to runtime variable caches. + + @retval EFI_UNSUPPORTED The volatile store to be updated is not initialized properly. + @retval EFI_SUCCESS The volatile store was updated successfully. + +**/ +EFI_STATUS +FlushPendingRuntimeVariableCacheUpdates ( + VOID + ) +{ + VARIABLE_RUNTIME_CACHE_CONTEXT *VariableRuntimeCacheContext; + + VariableRuntimeCacheContext = &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext; + + if (VariableRuntimeCacheContext->VariableRuntimeNvCache.Store == NULL || + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.Store == NULL || + VariableRuntimeCacheContext->PendingUpdate == NULL) { + return EFI_UNSUPPORTED; + } + + if (*(VariableRuntimeCacheContext->PendingUpdate)) { + if (VariableRuntimeCacheContext->VariableRuntimeHobCache.Store != NULL && + mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) { + CopyMem ( + (VOID *) ( + ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeHobCache.Store) + + VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset + ), + (VOID *) ( + ((UINT8 *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase) + + VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset + ), + VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateLength + ); + VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateLength = 0; + VariableRuntimeCacheContext->VariableRuntimeHobCache.PendingUpdateOffset = 0; + } + + CopyMem ( + (VOID *) ( + ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeNvCache.Store) + + VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset + ), + (VOID *) ( + ((UINT8 *) (UINTN) mNvVariableCache) + + VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset + ), + VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateLength + ); + VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateLength = 0; + VariableRuntimeCacheContext->VariableRuntimeNvCache.PendingUpdateOffset = 0; + + CopyMem ( + (VOID *) ( + ((UINT8 *) (UINTN) VariableRuntimeCacheContext->VariableRuntimeVolatileCache.Store) + + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset + ), + (VOID *) ( + ((UINT8 *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase) + + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset + ), + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength + ); + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength = 0; + VariableRuntimeCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset = 0; + *(VariableRuntimeCacheContext->PendingUpdate) = FALSE; + } + + return EFI_SUCCESS; +} + +/** + Synchronizes the runtime variable caches with all pending updates outside runtime. + + Ensures all conditions are met to maintain coherency for runtime cache updates. This function will attempt + to write the given update (and any other pending updates) if the ReadLock is available. Otherwise, the + update is added as a pending update for the given variable store and it will be flushed to the runtime cache + at the next opportunity the ReadLock is available. + + @param[in] VariableRuntimeCache Variable runtime cache structure for the runtime cache being synchronized. + @param[in] Offset Offset in bytes to apply the update. + @param[in] Length Length of data in bytes of the update. + + @retval EFI_SUCCESS The update was added as a pending update successfully. If the variable runtime + cache ReadLock was available, the runtime cache was updated successfully. + @retval EFI_UNSUPPORTED The volatile store to be updated is not initialized properly. + +**/ +EFI_STATUS +SynchronizeRuntimeVariableCache ( + IN VARIABLE_RUNTIME_CACHE *VariableRuntimeCache, + IN UINTN Offset, + IN UINTN Length + ) +{ + if (VariableRuntimeCache == NULL) { + return EFI_INVALID_PARAMETER; + } else if (VariableRuntimeCache->Store == NULL) { + // The runtime cache may not be active or allocated yet. + // In either case, return EFI_SUCCESS instead of EFI_NOT_AVAILABLE_YET. + return EFI_SUCCESS; + } + + if (mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate == NULL || + mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.ReadLock == NULL) { + return EFI_UNSUPPORTED; + } + + if (*(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) && + VariableRuntimeCache->PendingUpdateLength > 0) { + VariableRuntimeCache->PendingUpdateLength = + (UINT32) ( + MAX ( + (UINTN) (VariableRuntimeCache->PendingUpdateOffset + VariableRuntimeCache->PendingUpdateLength), + Offset + Length + ) - MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset, Offset) + ); + VariableRuntimeCache->PendingUpdateOffset = + (UINT32) MIN ((UINTN) VariableRuntimeCache->PendingUpdateOffset, Offset); + } else { + VariableRuntimeCache->PendingUpdateLength = (UINT32) Length; + VariableRuntimeCache->PendingUpdateOffset = (UINT32) Offset; + } + *(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.PendingUpdate) = TRUE; + + if (*(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.ReadLock) == FALSE) { + return FlushPendingRuntimeVariableCacheUpdates (); + } + + return EFI_SUCCESS; +} diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h new file mode 100644 index 00000000000..f9804a1d692 --- /dev/null +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeCache.h @@ -0,0 +1,51 @@ +/** @file + The common variable volatile store routines shared by the DXE_RUNTIME variable + module and the DXE_SMM variable module. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _VARIABLE_RUNTIME_CACHE_H_ +#define _VARIABLE_RUNTIME_CACHE_H_ + +#include "Variable.h" + +/** + Copies any pending updates to runtime variable caches. + + @retval EFI_UNSUPPORTED The volatile store to be updated is not initialized properly. + @retval EFI_SUCCESS The volatile store was updated successfully. + +**/ +EFI_STATUS +FlushPendingRuntimeVariableCacheUpdates ( + VOID + ); + +/** + Synchronizes the runtime variable caches with all pending updates outside runtime. + + Ensures all conditions are met to maintain coherency for runtime cache updates. This function will attempt + to write the given update (and any other pending updates) if the ReadLock is available. Otherwise, the + update is added as a pending update for the given variable store and it will be flushed to the runtime cache + at the next opportunity the ReadLock is available. + + @param[in] VariableRuntimeCache Variable runtime cache structure for the runtime cache being synchronized. + @param[in] Offset Offset in bytes to apply the update. + @param[in] Length Length of data in bytes of the update. + + @retval EFI_SUCCESS The update was added as a pending update successfully. If the variable runtime + cache ReadLock was available, the runtime cache was updated successfully. + @retval EFI_UNSUPPORTED The volatile store to be updated is not initialized properly. + +**/ +EFI_STATUS +SynchronizeRuntimeVariableCache ( + IN VARIABLE_RUNTIME_CACHE *VariableRuntimeCache, + IN UINTN Offset, + IN UINTN Length + ); + +#endif diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf index 08a54907870..ceea5d1ff9a 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf @@ -40,6 +40,8 @@ VariableNonVolatile.h VariableParsing.c VariableParsing.h + VariableRuntimeCache.c + VariableRuntimeCache.h PrivilegePolymorphic.h Measurement.c TcgMorLockDxe.c diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c index 5e24bc4a624..caca5c32411 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.c @@ -31,6 +31,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "Variable.h" #include "VariableParsing.h" +#include "VariableRuntimeCache.h" + +extern VARIABLE_STORE_HEADER *mNvVariableCache; BOOLEAN mAtRuntime = FALSE; UINT8 *mVariableBufferPayload = NULL; @@ -451,25 +454,29 @@ SmmVariableGetStatistics ( EFI_STATUS EFIAPI SmmVariableHandler ( - IN EFI_HANDLE DispatchHandle, - IN CONST VOID *RegisterContext, - IN OUT VOID *CommBuffer, - IN OUT UINTN *CommBufferSize + IN EFI_HANDLE DispatchHandle, + IN CONST VOID *RegisterContext, + IN OUT VOID *CommBuffer, + IN OUT UINTN *CommBufferSize ) { - EFI_STATUS Status; - SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; - SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *SmmVariableHeader; - SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME *GetNextVariableName; - SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO *QueryVariableInfo; - SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE *GetPayloadSize; - VARIABLE_INFO_ENTRY *VariableInfo; - SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE *VariableToLock; - SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *CommVariableProperty; - UINTN InfoSize; - UINTN NameBufferSize; - UINTN CommBufferPayloadSize; - UINTN TempCommBufferSize; + EFI_STATUS Status; + SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; + SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE *SmmVariableHeader; + SMM_VARIABLE_COMMUNICATE_GET_NEXT_VARIABLE_NAME *GetNextVariableName; + SMM_VARIABLE_COMMUNICATE_QUERY_VARIABLE_INFO *QueryVariableInfo; + SMM_VARIABLE_COMMUNICATE_GET_PAYLOAD_SIZE *GetPayloadSize; + SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *RuntimeVariableCacheContext; + SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *GetRuntimeCacheInfo; + SMM_VARIABLE_COMMUNICATE_LOCK_VARIABLE *VariableToLock; + SMM_VARIABLE_COMMUNICATE_VAR_CHECK_VARIABLE_PROPERTY *CommVariableProperty; + VARIABLE_INFO_ENTRY *VariableInfo; + VARIABLE_RUNTIME_CACHE_CONTEXT *VariableCacheContext; + VARIABLE_STORE_HEADER *VariableCache; + UINTN InfoSize; + UINTN NameBufferSize; + UINTN CommBufferPayloadSize; + UINTN TempCommBufferSize; // // If input is invalid, stop processing this SMI @@ -789,6 +796,154 @@ SmmVariableHandler ( ); CopyMem (SmmVariableFunctionHeader->Data, mVariableBufferPayload, CommBufferPayloadSize); break; + case SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT: + if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT)) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: SMM communication buffer size invalid!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (mEndOfDxe) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Cannot init context after end of DXE!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + + // + // Copy the input communicate buffer payload to the pre-allocated SMM variable payload buffer. + // + CopyMem (mVariableBufferPayload, SmmVariableFunctionHeader->Data, CommBufferPayloadSize); + RuntimeVariableCacheContext = (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *) mVariableBufferPayload; + + // + // Verify required runtime cache buffers are provided. + // + if (RuntimeVariableCacheContext->RuntimeVolatileCache == NULL || + RuntimeVariableCacheContext->RuntimeNvCache == NULL || + RuntimeVariableCacheContext->PendingUpdate == NULL || + RuntimeVariableCacheContext->ReadLock == NULL || + RuntimeVariableCacheContext->HobFlushComplete == NULL) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Required runtime cache buffer is NULL!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + + // + // Verify minimum size requirements for the runtime variable store buffers. + // + if ((RuntimeVariableCacheContext->RuntimeHobCache != NULL && + RuntimeVariableCacheContext->RuntimeHobCache->Size < sizeof (VARIABLE_STORE_HEADER)) || + RuntimeVariableCacheContext->RuntimeVolatileCache->Size < sizeof (VARIABLE_STORE_HEADER) || + RuntimeVariableCacheContext->RuntimeNvCache->Size < sizeof (VARIABLE_STORE_HEADER)) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: A runtime cache buffer size is invalid!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + + // + // Verify runtime buffers do not overlap with SMRAM ranges. + // + if (RuntimeVariableCacheContext->RuntimeHobCache != NULL && + !VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->RuntimeHobCache, + (UINTN) RuntimeVariableCacheContext->RuntimeHobCache->Size)) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime HOB cache buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (!VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache, + (UINTN) RuntimeVariableCacheContext->RuntimeVolatileCache->Size)) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime volatile cache buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (!VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->RuntimeNvCache, + (UINTN) RuntimeVariableCacheContext->RuntimeNvCache->Size)) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime non-volatile cache buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (!VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->PendingUpdate, + sizeof (*(RuntimeVariableCacheContext->PendingUpdate)))) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache pending update buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (!VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->ReadLock, + sizeof (*(RuntimeVariableCacheContext->ReadLock)))) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache read lock buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + if (!VariableSmmIsBufferOutsideSmmValid ( + (UINTN) RuntimeVariableCacheContext->HobFlushComplete, + sizeof (*(RuntimeVariableCacheContext->HobFlushComplete)))) { + DEBUG ((DEBUG_ERROR, "InitRuntimeVariableCacheContext: Runtime cache HOB flush complete buffer in SMRAM or overflow!\n")); + Status = EFI_ACCESS_DENIED; + goto EXIT; + } + + VariableCacheContext = &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext; + VariableCacheContext->VariableRuntimeHobCache.Store = RuntimeVariableCacheContext->RuntimeHobCache; + VariableCacheContext->VariableRuntimeVolatileCache.Store = RuntimeVariableCacheContext->RuntimeVolatileCache; + VariableCacheContext->VariableRuntimeNvCache.Store = RuntimeVariableCacheContext->RuntimeNvCache; + VariableCacheContext->PendingUpdate = RuntimeVariableCacheContext->PendingUpdate; + VariableCacheContext->ReadLock = RuntimeVariableCacheContext->ReadLock; + VariableCacheContext->HobFlushComplete = RuntimeVariableCacheContext->HobFlushComplete; + + // Set up the intial pending request since the RT cache needs to be in sync with SMM cache + VariableCacheContext->VariableRuntimeHobCache.PendingUpdateOffset = 0; + VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength = 0; + if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0 && + VariableCacheContext->VariableRuntimeHobCache.Store != NULL) { + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + VariableCacheContext->VariableRuntimeHobCache.PendingUpdateLength = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache); + CopyGuid (&(VariableCacheContext->VariableRuntimeHobCache.Store->Signature), &(VariableCache->Signature)); + } + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + VariableCacheContext->VariableRuntimeVolatileCache.PendingUpdateOffset = 0; + VariableCacheContext->VariableRuntimeVolatileCache.PendingUpdateLength = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache); + CopyGuid (&(VariableCacheContext->VariableRuntimeVolatileCache.Store->Signature), &(VariableCache->Signature)); + + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mNvVariableCache; + VariableCacheContext->VariableRuntimeNvCache.PendingUpdateOffset = 0; + VariableCacheContext->VariableRuntimeNvCache.PendingUpdateLength = (UINT32) ((UINTN) GetEndPointer (VariableCache) - (UINTN) VariableCache); + CopyGuid (&(VariableCacheContext->VariableRuntimeNvCache.Store->Signature), &(VariableCache->Signature)); + + *(VariableCacheContext->PendingUpdate) = TRUE; + *(VariableCacheContext->ReadLock) = FALSE; + *(VariableCacheContext->HobFlushComplete) = FALSE; + + Status = EFI_SUCCESS; + break; + case SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE: + Status = FlushPendingRuntimeVariableCacheUpdates (); + break; + case SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO: + if (CommBufferPayloadSize < sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO)) { + DEBUG ((DEBUG_ERROR, "GetRuntimeCacheInfo: SMM communication buffer size invalid!\n")); + return EFI_SUCCESS; + } + GetRuntimeCacheInfo = (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *) SmmVariableFunctionHeader->Data; + + if (mVariableModuleGlobal->VariableGlobal.HobVariableBase > 0) { + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.HobVariableBase; + GetRuntimeCacheInfo->TotalHobStorageSize = VariableCache->Size; + } else { + GetRuntimeCacheInfo->TotalHobStorageSize = 0; + } + + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mVariableModuleGlobal->VariableGlobal.VolatileVariableBase; + GetRuntimeCacheInfo->TotalVolatileStorageSize = VariableCache->Size; + VariableCache = (VARIABLE_STORE_HEADER *) (UINTN) mNvVariableCache; + GetRuntimeCacheInfo->TotalNvStorageSize = (UINTN) VariableCache->Size; + GetRuntimeCacheInfo->AuthenticatedVariableUsage = mVariableModuleGlobal->VariableGlobal.AuthFormat; + + Status = EFI_SUCCESS; + break; default: Status = EFI_UNSUPPORTED; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf index 6dc2721b816..bc3033588d4 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmm.inf @@ -49,6 +49,8 @@ VariableNonVolatile.h VariableParsing.c VariableParsing.h + VariableRuntimeCache.c + VariableRuntimeCache.h VarCheck.c Variable.h PrivilegePolymorphic.h diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c index 0a1888e5ef6..3dee05fded0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c @@ -13,7 +13,7 @@ InitCommunicateBuffer() is really function to check the variable data size. -Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
+Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -39,6 +39,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include "PrivilegePolymorphic.h" +#include "VariableParsing.h" EFI_HANDLE mHandle = NULL; EFI_SMM_VARIABLE_PROTOCOL *mSmmVariable = NULL; @@ -46,8 +47,19 @@ EFI_EVENT mVirtualAddressChangeEvent = NULL; EFI_SMM_COMMUNICATION_PROTOCOL *mSmmCommunication = NULL; UINT8 *mVariableBuffer = NULL; UINT8 *mVariableBufferPhysical = NULL; +VARIABLE_INFO_ENTRY *mVariableInfo = NULL; +VARIABLE_STORE_HEADER *mVariableRuntimeHobCacheBuffer = NULL; +VARIABLE_STORE_HEADER *mVariableRuntimeNvCacheBuffer = NULL; +VARIABLE_STORE_HEADER *mVariableRuntimeVolatileCacheBuffer = NULL; UINTN mVariableBufferSize; +UINTN mVariableRuntimeHobCacheBufferSize; +UINTN mVariableRuntimeNvCacheBufferSize; +UINTN mVariableRuntimeVolatileCacheBufferSize; UINTN mVariableBufferPayloadSize; +BOOLEAN mVariableRuntimeCachePendingUpdate; +BOOLEAN mVariableRuntimeCacheReadLock; +BOOLEAN mVariableAuthFormat; +BOOLEAN mHobFlushComplete; EFI_LOCK mVariableServicesLock; EDKII_VARIABLE_LOCK_PROTOCOL mVariableLock; EDKII_VAR_CHECK_PROTOCOL mVarCheck; @@ -107,6 +119,72 @@ ReleaseLockOnlyAtBootTime ( } } +/** + Return TRUE if ExitBootServices () has been called. + + @retval TRUE If ExitBootServices () has been called. FALSE if ExitBootServices () has not been called. +**/ +BOOLEAN +AtRuntime ( + VOID + ) +{ + return EfiAtRuntime (); +} + +/** + Initialize the variable cache buffer as an empty variable store. + + @param[out] VariableCacheBuffer A pointer to pointer of a cache variable store. + @param[in,out] TotalVariableCacheSize On input, the minimum size needed for the UEFI variable store cache + buffer that is allocated. On output, the actual size of the buffer allocated. + If TotalVariableCacheSize is zero, a buffer will not be allocated and the + function will return with EFI_SUCCESS. + + @retval EFI_SUCCESS The variable cache was allocated and initialized successfully. + @retval EFI_INVALID_PARAMETER A given pointer is NULL or an invalid variable store size was specified. + @retval EFI_OUT_OF_RESOURCES Insufficient resources are available to allocate the variable store cache buffer. + +**/ +EFI_STATUS +InitVariableCache ( + OUT VARIABLE_STORE_HEADER **VariableCacheBuffer, + IN OUT UINTN *TotalVariableCacheSize + ) +{ + VARIABLE_STORE_HEADER *VariableCacheStorePtr; + + if (TotalVariableCacheSize == NULL) { + return EFI_INVALID_PARAMETER; + } + if (*TotalVariableCacheSize == 0) { + return EFI_SUCCESS; + } + if (VariableCacheBuffer == NULL || *TotalVariableCacheSize < sizeof (VARIABLE_STORE_HEADER)) { + return EFI_INVALID_PARAMETER; + } + *TotalVariableCacheSize = ALIGN_VALUE (*TotalVariableCacheSize, sizeof (UINT32)); + + // + // Allocate NV Storage Cache and initialize it to all 1's (like an erased FV) + // + *VariableCacheBuffer = (VARIABLE_STORE_HEADER *) AllocateRuntimePages ( + EFI_SIZE_TO_PAGES (*TotalVariableCacheSize) + ); + if (*VariableCacheBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + VariableCacheStorePtr = *VariableCacheBuffer; + SetMem32 ((VOID *) VariableCacheStorePtr, *TotalVariableCacheSize, (UINT32) 0xFFFFFFFF); + + ZeroMem ((VOID *) VariableCacheStorePtr, sizeof (VARIABLE_STORE_HEADER)); + VariableCacheStorePtr->Size = (UINT32) *TotalVariableCacheSize; + VariableCacheStorePtr->Format = VARIABLE_STORE_FORMATTED; + VariableCacheStorePtr->State = VARIABLE_STORE_HEALTHY; + + return EFI_SUCCESS; +} + /** Initialize the communicate buffer using DataSize and Function. @@ -425,7 +503,56 @@ VarCheckVariablePropertyGet ( } /** - This code finds variable in storage blocks (Volatile or Non-Volatile). + Signals SMM to synchronize any pending variable updates with the runtime cache(s). + +**/ +VOID +SyncRuntimeCache ( + VOID + ) +{ + // + // Init the communicate buffer. The buffer data size is: + // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE. + // + InitCommunicateBuffer (NULL, 0, SMM_VARIABLE_FUNCTION_SYNC_RUNTIME_CACHE); + + // + // Send data to SMM. + // + SendCommunicateBuffer (0); +} + +/** + Check whether a SMI must be triggered to retrieve pending cache updates. + + If the variable HOB was finished being flushed since the last check for a runtime cache update, this function + will prevent the HOB cache from being used for future runtime cache hits. + +**/ +VOID +CheckForRuntimeCacheSync ( + VOID + ) +{ + if (mVariableRuntimeCachePendingUpdate) { + SyncRuntimeCache (); + } + ASSERT (!mVariableRuntimeCachePendingUpdate); + + // + // The HOB variable data may have finished being flushed in the runtime cache sync update + // + if (mHobFlushComplete && mVariableRuntimeHobCacheBuffer != NULL) { + if (!EfiAtRuntime ()) { + FreePages (mVariableRuntimeHobCacheBuffer, EFI_SIZE_TO_PAGES (mVariableRuntimeHobCacheBufferSize)); + } + mVariableRuntimeHobCacheBuffer = NULL; + } +} + +/** + Finds the given variable in a runtime cache variable store. Caution: This function may receive untrusted input. The data size is external input, so this function will validate it carefully to avoid buffer overflow. @@ -437,20 +564,131 @@ VarCheckVariablePropertyGet ( data, this value contains the required size. @param[out] Data Data pointer. + @retval EFI_SUCCESS Found the specified variable. @retval EFI_INVALID_PARAMETER Invalid parameter. - @retval EFI_SUCCESS Find the specified variable. - @retval EFI_NOT_FOUND Not found. - @retval EFI_BUFFER_TO_SMALL DataSize is too small for the result. + @retval EFI_NOT_FOUND The specified variable could not be found. **/ EFI_STATUS -EFIAPI -RuntimeServiceGetVariable ( +FindVariableInRuntimeCache ( IN CHAR16 *VariableName, IN EFI_GUID *VendorGuid, OUT UINT32 *Attributes OPTIONAL, IN OUT UINTN *DataSize, - OUT VOID *Data + OUT VOID *Data OPTIONAL + ) +{ + EFI_STATUS Status; + UINTN TempDataSize; + VARIABLE_POINTER_TRACK RtPtrTrack; + VARIABLE_STORE_TYPE StoreType; + VARIABLE_STORE_HEADER *VariableStoreList[VariableStoreTypeMax]; + + Status = EFI_NOT_FOUND; + + if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // The UEFI specification restricts Runtime Services callers from invoking the same or certain other Runtime Service + // functions prior to completion and return from a previous Runtime Service call. These restrictions prevent + // a GetVariable () or GetNextVariable () call from being issued until a prior call has returned. The runtime + // cache read lock should always be free when entering this function. + // + ASSERT (!mVariableRuntimeCacheReadLock); + + mVariableRuntimeCacheReadLock = TRUE; + CheckForRuntimeCacheSync (); + + if (!mVariableRuntimeCachePendingUpdate) { + // + // 0: Volatile, 1: HOB, 2: Non-Volatile. + // The index and attributes mapping must be kept in this order as FindVariable + // makes use of this mapping to implement search algorithm. + // + VariableStoreList[VariableStoreTypeVolatile] = mVariableRuntimeVolatileCacheBuffer; + VariableStoreList[VariableStoreTypeHob] = mVariableRuntimeHobCacheBuffer; + VariableStoreList[VariableStoreTypeNv] = mVariableRuntimeNvCacheBuffer; + + for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) { + if (VariableStoreList[StoreType] == NULL) { + continue; + } + + RtPtrTrack.StartPtr = GetStartPointer (VariableStoreList[StoreType]); + RtPtrTrack.EndPtr = GetEndPointer (VariableStoreList[StoreType]); + RtPtrTrack.Volatile = (BOOLEAN) (StoreType == VariableStoreTypeVolatile); + + Status = FindVariableEx (VariableName, VendorGuid, FALSE, &RtPtrTrack, mVariableAuthFormat); + if (!EFI_ERROR (Status)) { + break; + } + } + + if (!EFI_ERROR (Status)) { + // + // Get data size + // + TempDataSize = DataSizeOfVariable (RtPtrTrack.CurrPtr, mVariableAuthFormat); + ASSERT (TempDataSize != 0); + + if (*DataSize >= TempDataSize) { + if (Data == NULL) { + Status = EFI_INVALID_PARAMETER; + goto Done; + } + + CopyMem (Data, GetVariableDataPtr (RtPtrTrack.CurrPtr, mVariableAuthFormat), TempDataSize); + if (Attributes != NULL) { + *Attributes = RtPtrTrack.CurrPtr->Attributes; + } + + *DataSize = TempDataSize; + + UpdateVariableInfo (VariableName, VendorGuid, RtPtrTrack.Volatile, TRUE, FALSE, FALSE, TRUE, &mVariableInfo); + + Status = EFI_SUCCESS; + goto Done; + } else { + *DataSize = TempDataSize; + Status = EFI_BUFFER_TOO_SMALL; + goto Done; + } + } + } + +Done: + mVariableRuntimeCacheReadLock = FALSE; + + return Status; +} + +/** + Finds the given variable in a variable store in SMM. + + Caution: This function may receive untrusted input. + The data size is external input, so this function will validate it carefully to avoid buffer overflow. + + @param[in] VariableName Name of Variable to be found. + @param[in] VendorGuid Variable vendor GUID. + @param[out] Attributes Attribute value of the variable found. + @param[in, out] DataSize Size of Data found. If size is less than the + data, this value contains the required size. + @param[out] Data Data pointer. + + @retval EFI_SUCCESS Found the specified variable. + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_NOT_FOUND The specified variable could not be found. + +**/ +EFI_STATUS +FindVariableInSmm ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + OUT UINT32 *Attributes OPTIONAL, + IN OUT UINTN *DataSize, + OUT VOID *Data OPTIONAL ) { EFI_STATUS Status; @@ -474,8 +712,6 @@ RuntimeServiceGetVariable ( return EFI_INVALID_PARAMETER; } - AcquireLockOnlyAtBootTime(&mVariableServicesLock); - // // Init the communicate buffer. The buffer data size is: // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize. @@ -488,7 +724,7 @@ RuntimeServiceGetVariable ( } PayloadSize = OFFSET_OF (SMM_VARIABLE_COMMUNICATE_ACCESS_VARIABLE, Name) + VariableNameSize + TempDataSize; - Status = InitCommunicateBuffer ((VOID **)&SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE); + Status = InitCommunicateBuffer ((VOID **) &SmmVariableHeader, PayloadSize, SMM_VARIABLE_FUNCTION_GET_VARIABLE); if (EFI_ERROR (Status)) { goto Done; } @@ -534,10 +770,57 @@ RuntimeServiceGetVariable ( } Done: - ReleaseLockOnlyAtBootTime (&mVariableServicesLock); return Status; } +/** + This code finds variable in storage blocks (Volatile or Non-Volatile). + + Caution: This function may receive untrusted input. + The data size is external input, so this function will validate it carefully to avoid buffer overflow. + + @param[in] VariableName Name of Variable to be found. + @param[in] VendorGuid Variable vendor GUID. + @param[out] Attributes Attribute value of the variable found. + @param[in, out] DataSize Size of Data found. If size is less than the + data, this value contains the required size. + @param[out] Data Data pointer. + + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_SUCCESS Find the specified variable. + @retval EFI_NOT_FOUND Not found. + @retval EFI_BUFFER_TO_SMALL DataSize is too small for the result. + +**/ +EFI_STATUS +EFIAPI +RuntimeServiceGetVariable ( + IN CHAR16 *VariableName, + IN EFI_GUID *VendorGuid, + OUT UINT32 *Attributes OPTIONAL, + IN OUT UINTN *DataSize, + OUT VOID *Data + ) +{ + EFI_STATUS Status; + + if (VariableName == NULL || VendorGuid == NULL || DataSize == NULL) { + return EFI_INVALID_PARAMETER; + } + if (VariableName[0] == 0) { + return EFI_NOT_FOUND; + } + + AcquireLockOnlyAtBootTime (&mVariableServicesLock); + if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) { + Status = FindVariableInRuntimeCache (VariableName, VendorGuid, Attributes, DataSize, Data); + } else { + Status = FindVariableInSmm (VariableName, VendorGuid, Attributes, DataSize, Data); + } + ReleaseLockOnlyAtBootTime (&mVariableServicesLock); + + return Status; +} /** This code Finds the Next available variable. @@ -870,6 +1153,17 @@ OnReadyToBoot ( // SendCommunicateBuffer (0); + // + // Install the system configuration table for variable info data captured + // + if (FeaturePcdGet (PcdEnableVariableRuntimeCache) && FeaturePcdGet (PcdVariableCollectStatistics)) { + if (mVariableAuthFormat) { + gBS->InstallConfigurationTable (&gEfiAuthenticatedVariableGuid, mVariableInfo); + } else { + gBS->InstallConfigurationTable (&gEfiVariableGuid, mVariableInfo); + } + } + gBS->CloseEvent (Event); } @@ -893,6 +1187,9 @@ VariableAddressChangeEvent ( { EfiConvertPointer (0x0, (VOID **) &mVariableBuffer); EfiConvertPointer (0x0, (VOID **) &mSmmCommunication); + EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeHobCacheBuffer); + EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeNvCacheBuffer); + EfiConvertPointer (EFI_OPTIONAL_PTR, (VOID **) &mVariableRuntimeVolatileCacheBuffer); } /** @@ -969,6 +1266,159 @@ GetVariablePayloadSize ( return Status; } +/** + This code gets information needed from SMM for runtime cache initialization. + + @param[out] TotalHobStorageSize Output pointer for the total HOB storage size in bytes. + @param[out] TotalNvStorageSize Output pointer for the total non-volatile storage size in bytes. + @param[out] TotalVolatileStorageSize Output pointer for the total volatile storage size in bytes. + @param[out] AuthenticatedVariableUsage Output pointer that indicates if authenticated variables are to be used. + + @retval EFI_SUCCESS Retrieved the size successfully. + @retval EFI_INVALID_PARAMETER TotalNvStorageSize parameter is NULL. + @retval EFI_OUT_OF_RESOURCES The memory resources needed for a CommBuffer are not available. + @retval Others Could not retrieve the size successfully. + +**/ +EFI_STATUS +GetRuntimeCacheInfo ( + OUT UINTN *TotalHobStorageSize, + OUT UINTN *TotalNvStorageSize, + OUT UINTN *TotalVolatileStorageSize, + OUT BOOLEAN *AuthenticatedVariableUsage + ) +{ + EFI_STATUS Status; + SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *SmmGetRuntimeCacheInfo; + EFI_SMM_COMMUNICATE_HEADER *SmmCommunicateHeader; + SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; + UINTN CommSize; + UINT8 *CommBuffer; + + SmmGetRuntimeCacheInfo = NULL; + CommBuffer = mVariableBuffer; + + if (TotalHobStorageSize == NULL || TotalNvStorageSize == NULL || TotalVolatileStorageSize == NULL || AuthenticatedVariableUsage == NULL) { + return EFI_INVALID_PARAMETER; + } + + if (CommBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + AcquireLockOnlyAtBootTime (&mVariableServicesLock); + + CommSize = SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO); + ZeroMem (CommBuffer, CommSize); + + SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer; + CopyGuid (&SmmCommunicateHeader->HeaderGuid, &gEfiSmmVariableProtocolGuid); + SmmCommunicateHeader->MessageLength = SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO); + + SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) SmmCommunicateHeader->Data; + SmmVariableFunctionHeader->Function = SMM_VARIABLE_FUNCTION_GET_RUNTIME_CACHE_INFO; + SmmGetRuntimeCacheInfo = (SMM_VARIABLE_COMMUNICATE_GET_RUNTIME_CACHE_INFO *) SmmVariableFunctionHeader->Data; + + // + // Send data to SMM. + // + Status = mSmmCommunication->Communicate (mSmmCommunication, CommBuffer, &CommSize); + ASSERT_EFI_ERROR (Status); + if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) { + Status = EFI_BAD_BUFFER_SIZE; + goto Done; + } + + Status = SmmVariableFunctionHeader->ReturnStatus; + if (EFI_ERROR (Status)) { + goto Done; + } + + // + // Get data from SMM. + // + *TotalHobStorageSize = SmmGetRuntimeCacheInfo->TotalHobStorageSize; + *TotalNvStorageSize = SmmGetRuntimeCacheInfo->TotalNvStorageSize; + *TotalVolatileStorageSize = SmmGetRuntimeCacheInfo->TotalVolatileStorageSize; + *AuthenticatedVariableUsage = SmmGetRuntimeCacheInfo->AuthenticatedVariableUsage; + +Done: + ReleaseLockOnlyAtBootTime (&mVariableServicesLock); + return Status; +} + +/** + Sends the runtime variable cache context information to SMM. + + @retval EFI_SUCCESS Retrieved the size successfully. + @retval EFI_INVALID_PARAMETER TotalNvStorageSize parameter is NULL. + @retval EFI_OUT_OF_RESOURCES The memory resources needed for a CommBuffer are not available. + @retval Others Could not retrieve the size successfully.; + +**/ +EFI_STATUS +SendRuntimeVariableCacheContextToSmm ( + VOID + ) +{ + EFI_STATUS Status; + SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *SmmRuntimeVarCacheContext; + EFI_SMM_COMMUNICATE_HEADER *SmmCommunicateHeader; + SMM_VARIABLE_COMMUNICATE_HEADER *SmmVariableFunctionHeader; + UINTN CommSize; + UINT8 *CommBuffer; + + SmmRuntimeVarCacheContext = NULL; + CommBuffer = mVariableBuffer; + + if (CommBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + AcquireLockOnlyAtBootTime (&mVariableServicesLock); + + // + // Init the communicate buffer. The buffer data size is: + // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT); + // + CommSize = SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT); + ZeroMem (CommBuffer, CommSize); + + SmmCommunicateHeader = (EFI_SMM_COMMUNICATE_HEADER *) CommBuffer; + CopyGuid (&SmmCommunicateHeader->HeaderGuid, &gEfiSmmVariableProtocolGuid); + SmmCommunicateHeader->MessageLength = SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + sizeof (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT); + + SmmVariableFunctionHeader = (SMM_VARIABLE_COMMUNICATE_HEADER *) SmmCommunicateHeader->Data; + SmmVariableFunctionHeader->Function = SMM_VARIABLE_FUNCTION_INIT_RUNTIME_VARIABLE_CACHE_CONTEXT; + SmmRuntimeVarCacheContext = (SMM_VARIABLE_COMMUNICATE_RUNTIME_VARIABLE_CACHE_CONTEXT *) SmmVariableFunctionHeader->Data; + + SmmRuntimeVarCacheContext->RuntimeHobCache = mVariableRuntimeHobCacheBuffer; + SmmRuntimeVarCacheContext->RuntimeVolatileCache = mVariableRuntimeVolatileCacheBuffer; + SmmRuntimeVarCacheContext->RuntimeNvCache = mVariableRuntimeNvCacheBuffer; + SmmRuntimeVarCacheContext->PendingUpdate = &mVariableRuntimeCachePendingUpdate; + SmmRuntimeVarCacheContext->ReadLock = &mVariableRuntimeCacheReadLock; + SmmRuntimeVarCacheContext->HobFlushComplete = &mHobFlushComplete; + + // + // Send data to SMM. + // + Status = mSmmCommunication->Communicate (mSmmCommunication, CommBuffer, &CommSize); + ASSERT_EFI_ERROR (Status); + if (CommSize <= SMM_VARIABLE_COMMUNICATE_HEADER_SIZE) { + Status = EFI_BAD_BUFFER_SIZE; + goto Done; + } + + Status = SmmVariableFunctionHeader->ReturnStatus; + if (EFI_ERROR (Status)) { + goto Done; + } + +Done: + ReleaseLockOnlyAtBootTime (&mVariableServicesLock); + return Status; +} + /** Initialize variable service and install Variable Architectural protocol. @@ -985,7 +1435,7 @@ SmmVariableReady ( { EFI_STATUS Status; - Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **)&mSmmVariable); + Status = gBS->LocateProtocol (&gEfiSmmVariableProtocolGuid, NULL, (VOID **) &mSmmVariable); if (EFI_ERROR (Status)) { return; } @@ -1007,6 +1457,42 @@ SmmVariableReady ( // mVariableBufferPhysical = mVariableBuffer; + if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) { + DEBUG ((DEBUG_INFO, "Variable driver runtime cache is enabled.\n")); + // + // Allocate runtime variable cache memory buffers. + // + Status = GetRuntimeCacheInfo ( + &mVariableRuntimeHobCacheBufferSize, + &mVariableRuntimeNvCacheBufferSize, + &mVariableRuntimeVolatileCacheBufferSize, + &mVariableAuthFormat + ); + if (!EFI_ERROR (Status)) { + Status = InitVariableCache (&mVariableRuntimeHobCacheBuffer, &mVariableRuntimeHobCacheBufferSize); + if (!EFI_ERROR (Status)) { + Status = InitVariableCache (&mVariableRuntimeNvCacheBuffer, &mVariableRuntimeNvCacheBufferSize); + if (!EFI_ERROR (Status)) { + Status = InitVariableCache (&mVariableRuntimeVolatileCacheBuffer, &mVariableRuntimeVolatileCacheBufferSize); + if (!EFI_ERROR (Status)) { + Status = SendRuntimeVariableCacheContextToSmm (); + if (!EFI_ERROR (Status)) { + SyncRuntimeCache (); + } + } + } + } + if (EFI_ERROR (Status)) { + mVariableRuntimeHobCacheBuffer = NULL; + mVariableRuntimeNvCacheBuffer = NULL; + mVariableRuntimeVolatileCacheBuffer = NULL; + } + } + ASSERT_EFI_ERROR (Status); + } else { + DEBUG ((DEBUG_INFO, "Variable driver runtime cache is disabled.\n")); + } + gRT->GetVariable = RuntimeServiceGetVariable; gRT->GetNextVariableName = RuntimeServiceGetNextVariableName; gRT->SetVariable = RuntimeServiceSetVariable; diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf index 14894e6f138..a250533a534 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf @@ -13,7 +13,7 @@ # may not be modified without authorization. If platform fails to protect these resources, # the authentication service provided in this driver will be broken, and the behavior is undefined. # -# Copyright (c) 2010 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2010 - 2019, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -39,6 +39,8 @@ VariableSmmRuntimeDxe.c PrivilegePolymorphic.h Measurement.c + VariableParsing.c + VariableParsing.h [Packages] MdePkg/MdePkg.dec @@ -65,7 +67,21 @@ gEdkiiVariableLockProtocolGuid ## PRODUCES gEdkiiVarCheckProtocolGuid ## PRODUCES +[FeaturePcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache ## CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdVariableCollectStatistics ## CONSUMES + [Guids] + ## PRODUCES ## GUID # Signature of Variable store header + ## CONSUMES ## GUID # Signature of Variable store header + ## SOMETIMES_PRODUCES ## SystemTable + gEfiAuthenticatedVariableGuid + + ## PRODUCES ## GUID # Signature of Variable store header + ## CONSUMES ## GUID # Signature of Variable store header + ## SOMETIMES_PRODUCES ## SystemTable + gEfiVariableGuid + gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event gEfiEventExitBootServicesGuid ## CONSUMES ## Event ## CONSUMES ## GUID # Locate protocol diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf index f8a37429595..6e17f6cdf58 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableStandaloneMm.inf @@ -49,6 +49,8 @@ VariableNonVolatile.h VariableParsing.c VariableParsing.h + VariableRuntimeCache.c + VariableRuntimeCache.h VarCheck.c Variable.h PrivilegePolymorphic.h From 6f9838f32ff4c3b747c0c47540c34b4ec089642b Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 23 Sep 2019 18:49:37 -0700 Subject: [PATCH 046/384] MdeModulePkg/Variable: Add RT GetNextVariableName() cache support https://bugzilla.tianocore.org/show_bug.cgi?id=2220 This change implements the Runtime Service GetNextVariableName() using the runtime cache in VariableSmmRuntimeDxe. Runtime Service calls to GetNextVariableName() will no longer trigger a SW SMI when gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache is set to TRUE (default value). Overall system performance and stability will be improved by eliminating an SMI for these calls as they typically result in a relatively large number of invocations to retrieve all variable names in all variable stores present. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- .../RuntimeDxe/VariableSmmRuntimeDxe.c | 137 ++++++++++++++++-- 1 file changed, 128 insertions(+), 9 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c index 3dee05fded0..d525998ae30 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c @@ -823,7 +823,7 @@ RuntimeServiceGetVariable ( } /** - This code Finds the Next available variable. + Finds the next available variable in a runtime cache variable store. @param[in, out] VariableNameSize Size of the variable name. @param[in, out] VariableName Pointer to variable name. @@ -836,8 +836,81 @@ RuntimeServiceGetVariable ( **/ EFI_STATUS -EFIAPI -RuntimeServiceGetNextVariableName ( +GetNextVariableNameInRuntimeCache ( + IN OUT UINTN *VariableNameSize, + IN OUT CHAR16 *VariableName, + IN OUT EFI_GUID *VendorGuid + ) +{ + EFI_STATUS Status; + UINTN VarNameSize; + VARIABLE_HEADER *VariablePtr; + VARIABLE_STORE_HEADER *VariableStoreHeader[VariableStoreTypeMax]; + + Status = EFI_NOT_FOUND; + + // + // The UEFI specification restricts Runtime Services callers from invoking the same or certain other Runtime Service + // functions prior to completion and return from a previous Runtime Service call. These restrictions prevent + // a GetVariable () or GetNextVariable () call from being issued until a prior call has returned. The runtime + // cache read lock should always be free when entering this function. + // + ASSERT (!mVariableRuntimeCacheReadLock); + + CheckForRuntimeCacheSync (); + + mVariableRuntimeCacheReadLock = TRUE; + if (!mVariableRuntimeCachePendingUpdate) { + // + // 0: Volatile, 1: HOB, 2: Non-Volatile. + // The index and attributes mapping must be kept in this order as FindVariable + // makes use of this mapping to implement search algorithm. + // + VariableStoreHeader[VariableStoreTypeVolatile] = mVariableRuntimeVolatileCacheBuffer; + VariableStoreHeader[VariableStoreTypeHob] = mVariableRuntimeHobCacheBuffer; + VariableStoreHeader[VariableStoreTypeNv] = mVariableRuntimeNvCacheBuffer; + + Status = VariableServiceGetNextVariableInternal ( + VariableName, + VendorGuid, + VariableStoreHeader, + &VariablePtr, + mVariableAuthFormat + ); + if (!EFI_ERROR (Status)) { + VarNameSize = NameSizeOfVariable (VariablePtr, mVariableAuthFormat); + ASSERT (VarNameSize != 0); + if (VarNameSize <= *VariableNameSize) { + CopyMem (VariableName, GetVariableNamePtr (VariablePtr, mVariableAuthFormat), VarNameSize); + CopyMem (VendorGuid, GetVendorGuidPtr (VariablePtr, mVariableAuthFormat), sizeof (EFI_GUID)); + Status = EFI_SUCCESS; + } else { + Status = EFI_BUFFER_TOO_SMALL; + } + + *VariableNameSize = VarNameSize; + } + } + mVariableRuntimeCacheReadLock = FALSE; + + return Status; +} + +/** + Finds the next available variable in a SMM variable store. + + @param[in, out] VariableNameSize Size of the variable name. + @param[in, out] VariableName Pointer to variable name. + @param[in, out] VendorGuid Variable Vendor Guid. + + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_SUCCESS Find the specified variable. + @retval EFI_NOT_FOUND Not found. + @retval EFI_BUFFER_TO_SMALL DataSize is too small for the result. + +**/ +EFI_STATUS +GetNextVariableNameInSmm ( IN OUT UINTN *VariableNameSize, IN OUT CHAR16 *VariableName, IN OUT EFI_GUID *VendorGuid @@ -849,10 +922,6 @@ RuntimeServiceGetNextVariableName ( UINTN OutVariableNameSize; UINTN InVariableNameSize; - if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) { - return EFI_INVALID_PARAMETER; - } - OutVariableNameSize = *VariableNameSize; InVariableNameSize = StrSize (VariableName); SmmGetNextVariableName = NULL; @@ -864,8 +933,6 @@ RuntimeServiceGetNextVariableName ( return EFI_INVALID_PARAMETER; } - AcquireLockOnlyAtBootTime(&mVariableServicesLock); - // // Init the communicate buffer. The buffer data size is: // SMM_COMMUNICATE_HEADER_SIZE + SMM_VARIABLE_COMMUNICATE_HEADER_SIZE + PayloadSize. @@ -924,7 +991,59 @@ RuntimeServiceGetNextVariableName ( CopyMem (VariableName, SmmGetNextVariableName->Name, SmmGetNextVariableName->NameSize); Done: + return Status; +} + +/** + This code Finds the Next available variable. + + @param[in, out] VariableNameSize Size of the variable name. + @param[in, out] VariableName Pointer to variable name. + @param[in, out] VendorGuid Variable Vendor Guid. + + @retval EFI_INVALID_PARAMETER Invalid parameter. + @retval EFI_SUCCESS Find the specified variable. + @retval EFI_NOT_FOUND Not found. + @retval EFI_BUFFER_TO_SMALL DataSize is too small for the result. + +**/ +EFI_STATUS +EFIAPI +RuntimeServiceGetNextVariableName ( + IN OUT UINTN *VariableNameSize, + IN OUT CHAR16 *VariableName, + IN OUT EFI_GUID *VendorGuid + ) +{ + EFI_STATUS Status; + UINTN MaxLen; + + Status = EFI_NOT_FOUND; + + if (VariableNameSize == NULL || VariableName == NULL || VendorGuid == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Calculate the possible maximum length of name string, including the Null terminator. + // + MaxLen = *VariableNameSize / sizeof (CHAR16); + if ((MaxLen == 0) || (StrnLenS (VariableName, MaxLen) == MaxLen)) { + // + // Null-terminator is not found in the first VariableNameSize bytes of the input VariableName buffer, + // follow spec to return EFI_INVALID_PARAMETER. + // + return EFI_INVALID_PARAMETER; + } + + AcquireLockOnlyAtBootTime (&mVariableServicesLock); + if (FeaturePcdGet (PcdEnableVariableRuntimeCache)) { + Status = GetNextVariableNameInRuntimeCache (VariableNameSize, VariableName, VendorGuid); + } else { + Status = GetNextVariableNameInSmm (VariableNameSize, VariableName, VendorGuid); + } ReleaseLockOnlyAtBootTime (&mVariableServicesLock); + return Status; } From d511d6e0e7a9ffa960afb275c28093bfe41e42ad Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 14 Oct 2019 10:14:24 -0700 Subject: [PATCH 047/384] OvmfPkg: Disable variable runtime cache Sets gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache to FALSE in OvmfPkgIa32.dsc, OvmfPkgIa32X64.dsc, and OvmfPkgX64.dsc so that when SMM_REQUIRE is TRUE, the SMM variable driver will not use the runtime variable cache. This is done for OvmfPkg because it currently depends upon a SMM variable GetVariable ()implementation as a simple method to exercise the SMM driver stack. This allows the following commands to be used for variables such as Boot####, BootOrder, and BootNext to test SMM timing and stability differences on the BSP (e.g. CPU#0) vs an AP (e.g. CPU#1). # taskset -c 0 efibootmgr # taskset -c 1 efibootmgr Cc: Ard Biesheuvel Cc: Laszlo Ersek Cc: Liming Gao Cc: Jordan Justen Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Laszlo Ersek --- OvmfPkg/OvmfPkgIa32.dsc | 1 + OvmfPkg/OvmfPkgIa32X64.dsc | 1 + OvmfPkg/OvmfPkgX64.dsc | 1 + 3 files changed, 3 insertions(+) diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 05bb6ae136b..d350b756304 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -431,6 +431,7 @@ !if $(SMM_REQUIRE) == TRUE gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif [PcdsFixedAtBuild] diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 4a75a0332e0..1ef82cafe4a 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -436,6 +436,7 @@ !if $(SMM_REQUIRE) == TRUE gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif [PcdsFixedAtBuild] diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index ed54181180f..232815c08e1 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -436,6 +436,7 @@ !if $(SMM_REQUIRE) == TRUE gUefiOvmfPkgTokenSpaceGuid.PcdSmmSmramRequire|TRUE gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmEnableBspElection|FALSE + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE !endif [PcdsFixedAtBuild] From e07b7d024ac943ba0516e55819161b513439bf2b Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 14 Oct 2019 16:15:08 -0700 Subject: [PATCH 048/384] MdeModulePkg: Enable variable runtime cache by default This change enables the variable runtime cache by default by setting gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache in MdeModulePkg.dec to TRUE. Cc: Dandan Bi Cc: Ard Biesheuvel Cc: Eric Dong Cc: Laszlo Ersek Cc: Liming Gao Cc: Michael D Kinney Cc: Ray Ni Cc: Jian J Wang Cc: Hao A Wu Cc: Jiewen Yao Signed-off-by: Michael Kubacki Reviewed-by: Laszlo Ersek Reviewed-by: Jian J Wang Reviewed-by: Hao A Wu --- MdeModulePkg/MdeModulePkg.dec | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 3ef8fe7644d..1e964f59032 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -651,7 +651,7 @@ # TRUE - The UEFI variable runtime cache is enabled.
# FALSE - The UEFI variable runtime cache is disabled.
# @Prompt Enable the UEFI variable runtime cache. - gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|FALSE|BOOLEAN|0x00010039 + gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache|TRUE|BOOLEAN|0x00010039 ## Indicates if the statistics about variable usage will be collected. This information is # stored as a vendor configuration table into the EFI system table. From 78413dd4bc9718b6a5dde74d903e71764d48b8a7 Mon Sep 17 00:00:00 2001 From: "Rabeda, Maciej" Date: Wed, 6 Nov 2019 01:07:12 +0800 Subject: [PATCH 049/384] Maintainers.txt: Adding new NetworkPkg reviewer. Add Maciej Rabeda as reviewer of NetworkPkg. Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Maciej Rabeda Reviewed-by: Jiaxin Wu --- Maintainers.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/Maintainers.txt b/Maintainers.txt index 71a34a28456..922cc664ddc 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -356,6 +356,7 @@ F: NetworkPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg M: Jiaxin Wu R: Siyuan Fu +R: Maciej Rabeda OvmfPkg F: OvmfPkg/ From 1a04951309f807958cf54d38c29796737718e65f Mon Sep 17 00:00:00 2001 From: "Chu, Maggie" Date: Mon, 4 Nov 2019 12:04:28 +0800 Subject: [PATCH 050/384] SecurityPkg/OpalPassword: Remove dependency on EFI_BLOCK_IO_PROTOCOL https://bugzilla.tianocore.org/show_bug.cgi?id=2327 RAID drivers abstract their physical drives that make up the array into a single unit, and do not supply individual EFI_BLOCK_IO_PROTOCOL instances for each physical drive in the array. This breaks support for the Security Storage Command Protocol, which currently requires an EFI_BLOCK_IO_PROTOCOL to be associated with the same device the protocol is installed on and provide all the same parameters. This patch remove dependency on EFI_BLOCK_IO_PROTOCOL and allows access to Opal drive members of a RAID array. Signed-off-by: Maggie Chu Reviewed-by: Eric Dong Cc: Chao Zhang Cc: Jiewen Yao --- .../Tcg/Opal/OpalPassword/OpalDriver.c | 70 +++++++------------ 1 file changed, 27 insertions(+), 43 deletions(-) diff --git a/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c b/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c index 77905d2bf9e..6bec54b9321 100644 --- a/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c +++ b/SecurityPkg/Tcg/Opal/OpalPassword/OpalDriver.c @@ -2667,7 +2667,6 @@ OpalEfiDriverBindingSupported( { EFI_STATUS Status; EFI_STORAGE_SECURITY_COMMAND_PROTOCOL* SecurityCommand; - EFI_BLOCK_IO_PROTOCOL* BlkIo; if (mOpalEndOfDxe) { return EFI_UNSUPPORTED; @@ -2703,33 +2702,6 @@ OpalEfiDriverBindingSupported( Controller ); - // - // Test EFI_BLOCK_IO_PROTOCOL on controller Handle, required by EFI_STORAGE_SECURITY_COMMAND_PROTOCOL - // function APIs - // - Status = gBS->OpenProtocol( - Controller, - &gEfiBlockIoProtocolGuid, - (VOID **)&BlkIo, - This->DriverBindingHandle, - Controller, - EFI_OPEN_PROTOCOL_BY_DRIVER - ); - - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_INFO, "No EFI_BLOCK_IO_PROTOCOL on controller\n")); - return Status; - } - - // - // Close protocol and reopen in Start call - // - gBS->CloseProtocol( - Controller, - &gEfiBlockIoProtocolGuid, - This->DriverBindingHandle, - Controller - ); return EFI_SUCCESS; } @@ -2827,30 +2799,42 @@ OpalEfiDriverBindingStart( ); if (EFI_ERROR(Status)) { // - // Close storage security that was opened + // Block_IO not supported on handle // - gBS->CloseProtocol( - Controller, - &gEfiStorageSecurityCommandProtocolGuid, - This->DriverBindingHandle, - Controller - ); + if(Status == EFI_UNSUPPORTED) { + BlkIo = NULL; + } else { + // + // Close storage security that was opened + // + gBS->CloseProtocol( + Controller, + &gEfiStorageSecurityCommandProtocolGuid, + This->DriverBindingHandle, + Controller + ); - FreePool(Dev); - return Status; + FreePool(Dev); + return Status; + } } // // Save mediaId // - Dev->MediaId = BlkIo->Media->MediaId; + if(BlkIo == NULL) { + // If no Block IO present, use defined MediaId value. + Dev->MediaId = 0x0; + } else { + Dev->MediaId = BlkIo->Media->MediaId; - gBS->CloseProtocol( - Controller, - &gEfiBlockIoProtocolGuid, - This->DriverBindingHandle, - Controller + gBS->CloseProtocol( + Controller, + &gEfiBlockIoProtocolGuid, + This->DriverBindingHandle, + Controller ); + } // // Acquire Ascii printable name of child, if not found, then ignore device From 3a63c17ebc853cbb27d190729d01e27f68e65b94 Mon Sep 17 00:00:00 2001 From: Derek Lin Date: Wed, 6 Nov 2019 09:00:47 +0000 Subject: [PATCH 051/384] SecurityPkg: Fix TPM2 ACPI measurement. We have discussed in this thread. https://edk2.groups.io/g/devel/topic/32205028 Before the change, TPM FW upgrade will impact TPM2 ACPI PCR value because TPM2 ACPI HID include FW version. This change make the measurement before TPM2 HID fixup. So, after TPM FW upgrade, the ACPI PCR record remains the same. Signed-off-by: Derek Lin Reviewed by: Jiewen Yao Reviewed-by: Jian J Wang --- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 30 ++++++++++++++++-------------- 1 file changed, 16 insertions(+), 14 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c index bd786bf4791..54966c83ce8 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -664,7 +664,22 @@ PublishAcpiTable ( )); // - // Update TPM2 HID before measuring it to PCR + // Measure to PCR[0] with event EV_POST_CODE ACPI DATA. + // The measurement has to be done before UpdateHID since TPM2 ACPI HID + // imply TPM Firmware Version. Otherwise, the PCR record would be + // different after TPM FW update. + // + TpmMeasureAndLogData( + 0, + EV_POST_CODE, + EV_POSTCODE_INFO_ACPI_DATA, + ACPI_DATA_LEN, + Table, + TableSize + ); + + // + // Update TPM2 HID after measuring it to PCR // Status = UpdateHID(Table); if (EFI_ERROR(Status)) { @@ -694,19 +709,6 @@ PublishAcpiTable ( } } - // - // Measure to PCR[0] with event EV_POST_CODE ACPI DATA - // - TpmMeasureAndLogData( - 0, - EV_POST_CODE, - EV_POSTCODE_INFO_ACPI_DATA, - ACPI_DATA_LEN, - Table, - TableSize - ); - - ASSERT (Table->OemTableId == SIGNATURE_64 ('T', 'p', 'm', '2', 'T', 'a', 'b', 'l')); CopyMem (Table->OemId, PcdGetPtr (PcdAcpiDefaultOemId), sizeof (Table->OemId) ); mTcgNvs = AssignOpRegion (Table, SIGNATURE_32 ('T', 'N', 'V', 'S'), (UINT16) sizeof (TCG_NVS)); From 601a18bf08ca815544b2223208b437a83fba6858 Mon Sep 17 00:00:00 2001 From: Ashish Singhal Date: Mon, 4 Nov 2019 10:49:31 -0700 Subject: [PATCH 052/384] EmbeddedPkg/DtPlatformDxe: Add DT/ACPI Default Flexibility Add a PCD to govern whether to use DT or ACPI in case the variable governing this is not found or is not valid. Signed-off-by: Ashish Singhal Reviewed-by: Ard Biesheuvel --- EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c | 15 +++++++++------ .../Drivers/DtPlatformDxe/DtPlatformDxe.inf | 3 +++ EmbeddedPkg/EmbeddedPkg.dec | 5 +++++ 3 files changed, 17 insertions(+), 6 deletions(-) diff --git a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c index 907d46a495e..a6ac30c32a6 100644 --- a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c +++ b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.c @@ -124,18 +124,21 @@ DtPlatformDxeEntryPoint ( Status = gRT->GetVariable(DT_ACPI_VARIABLE_NAME, &gDtPlatformFormSetGuid, NULL, &BufferSize, &DtAcpiPref); if (EFI_ERROR (Status)) { - DEBUG ((DEBUG_WARN, "%a: no DT/ACPI preference found, defaulting to DT\n", - __FUNCTION__)); - DtAcpiPref.Pref = DT_ACPI_SELECT_DT; + DEBUG ((DEBUG_WARN, "%a: no DT/ACPI preference found, defaulting to %a\n", + __FUNCTION__, PcdGetBool (PcdDefaultDtPref) ? "DT" : "ACPI")); + DtAcpiPref.Pref = PcdGetBool (PcdDefaultDtPref) ? DT_ACPI_SELECT_DT + : DT_ACPI_SELECT_ACPI; } } if (!EFI_ERROR (Status) && DtAcpiPref.Pref != DT_ACPI_SELECT_ACPI && DtAcpiPref.Pref != DT_ACPI_SELECT_DT) { - DEBUG ((DEBUG_WARN, "%a: invalid value for %s, defaulting to DT\n", - __FUNCTION__, DT_ACPI_VARIABLE_NAME)); - DtAcpiPref.Pref = DT_ACPI_SELECT_DT; + DEBUG ((DEBUG_WARN, "%a: invalid value for %s, defaulting to %a\n", + __FUNCTION__, DT_ACPI_VARIABLE_NAME, + PcdGetBool (PcdDefaultDtPref) ? "DT" : "ACPI")); + DtAcpiPref.Pref = PcdGetBool (PcdDefaultDtPref) ? DT_ACPI_SELECT_DT + : DT_ACPI_SELECT_ACPI; Status = EFI_INVALID_PARAMETER; // trigger setvar below } diff --git a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf index b68f154182a..450ea29b4a2 100644 --- a/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf +++ b/EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf @@ -46,6 +46,9 @@ gEdkiiPlatformHasAcpiGuid gFdtTableGuid +[Pcd] + gEmbeddedTokenSpaceGuid.PcdDefaultDtPref + [Depex] gEfiVariableArchProtocolGuid AND gEfiVariableWriteArchProtocolGuid diff --git a/EmbeddedPkg/EmbeddedPkg.dec b/EmbeddedPkg/EmbeddedPkg.dec index bbaadc5a17a..8812a6db7c3 100644 --- a/EmbeddedPkg/EmbeddedPkg.dec +++ b/EmbeddedPkg/EmbeddedPkg.dec @@ -185,3 +185,8 @@ # truncation on overflow to specify negative offsets. # gEmbeddedTokenSpaceGuid.PcdDmaDeviceOffset|0x0|UINT64|0x0000058 + + # + # Selection between DT and ACPI as a default + # + gEmbeddedTokenSpaceGuid.PcdDefaultDtPref|TRUE|BOOLEAN|0x0000059 From 5cef92771fb966b6ebe5eccbd97c2127c091b4e9 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Tue, 29 Oct 2019 13:07:44 +0800 Subject: [PATCH 053/384] BaseTools: Add map file parsing support for CLANG9 Cc: Bob Feng Cc: Liming Gao Reviewed-by: Liming Gao Signed-off-by: Zhiguang Liu --- BaseTools/Source/Python/Common/Misc.py | 9 ++++++--- .../Source/Python/GenPatchPcdTable/GenPatchPcdTable.py | 9 ++++++--- 2 files changed, 12 insertions(+), 6 deletions(-) diff --git a/BaseTools/Source/Python/Common/Misc.py b/BaseTools/Source/Python/Common/Misc.py index a488536cb45..da5fb380f03 100755 --- a/BaseTools/Source/Python/Common/Misc.py +++ b/BaseTools/Source/Python/Common/Misc.py @@ -81,19 +81,22 @@ def GetVariableOffset(mapfilepath, efifilepath, varnames): if len(lines) == 0: return None firstline = lines[0].strip() + if re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', firstline): + return _parseForXcodeAndClang9(lines, efifilepath, varnames) if (firstline.startswith("Archive member included ") and firstline.endswith(" file (symbol)")): return _parseForGCC(lines, efifilepath, varnames) if firstline.startswith("# Path:"): - return _parseForXcode(lines, efifilepath, varnames) + return _parseForXcodeAndClang9(lines, efifilepath, varnames) return _parseGeneral(lines, efifilepath, varnames) -def _parseForXcode(lines, efifilepath, varnames): +def _parseForXcodeAndClang9(lines, efifilepath, varnames): status = 0 ret = [] for line in lines: line = line.strip() - if status == 0 and line == "# Symbols:": + if status == 0 and (re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', line) \ + or line == "# Symbols:"): status = 1 continue if status == 1 and len(line) != 0: diff --git a/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py b/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py index 7d5e4fc34a3..d962ab0adda 100644 --- a/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py +++ b/BaseTools/Source/Python/GenPatchPcdTable/GenPatchPcdTable.py @@ -49,20 +49,23 @@ def parsePcdInfoFromMapFile(mapfilepath, efifilepath): if len(lines) == 0: return None firstline = lines[0].strip() + if re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', firstline): + return _parseForXcodeAndClang9(lines, efifilepath) if (firstline.startswith("Archive member included ") and firstline.endswith(" file (symbol)")): return _parseForGCC(lines, efifilepath) if firstline.startswith("# Path:"): - return _parseForXcode(lines, efifilepath) + return _parseForXcodeAndClang9(lines, efifilepath) return _parseGeneral(lines, efifilepath) -def _parseForXcode(lines, efifilepath): +def _parseForXcodeAndClang9(lines, efifilepath): valuePattern = re.compile('^([\da-fA-FxX]+)([\s\S]*)([_]*_gPcd_BinaryPatch_([\w]+))') status = 0 pcds = [] for line in lines: line = line.strip() - if status == 0 and line == "# Symbols:": + if status == 0 and (re.match('^\s*Address\s*Size\s*Align\s*Out\s*In\s*Symbol\s*$', line) \ + or line == "# Symbols:"): status = 1 continue if status == 1 and len(line) != 0: From 0cecb1f99e6c4ba7408272074541bab98c98a116 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Fri, 1 Nov 2019 10:35:59 +0800 Subject: [PATCH 054/384] BaseTools: Add support for parseing map files generated by CLANG9 in GenFv REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2320 Add support for parseing map files generated by CLANG9 in GenFv Cc: Bob Feng Cc: Liming Gao Reviewed-by: Liming Gao Signed-off-by: Zhiguang Liu --- BaseTools/Source/C/GenFv/GenFvInternalLib.c | 28 +++++++++++++++++---- 1 file changed, 23 insertions(+), 5 deletions(-) diff --git a/BaseTools/Source/C/GenFv/GenFvInternalLib.c b/BaseTools/Source/C/GenFv/GenFvInternalLib.c index 908740de505..daebfe894c7 100644 --- a/BaseTools/Source/C/GenFv/GenFvInternalLib.c +++ b/BaseTools/Source/C/GenFv/GenFvInternalLib.c @@ -791,6 +791,7 @@ Routine Description: FILE *PeMapFile; CHAR8 Line [MAX_LINE_LEN]; CHAR8 KeyWord [MAX_LINE_LEN]; + CHAR8 KeyWord2 [MAX_LINE_LEN]; CHAR8 FunctionName [MAX_LINE_LEN]; EFI_PHYSICAL_ADDRESS FunctionAddress; UINT32 FunctionType; @@ -805,6 +806,7 @@ Routine Description: UINT32 TextVirtualAddress; UINT32 DataVirtualAddress; EFI_PHYSICAL_ADDRESS LinkTimeBaseAddress; + BOOLEAN IsUseClang; // // Init local variable @@ -932,6 +934,7 @@ Routine Description: // Output Functions information into Fv Map file // LinkTimeBaseAddress = 0; + IsUseClang = FALSE; while (fgets (Line, MAX_LINE_LEN, PeMapFile) != NULL) { // // Skip blank line @@ -946,6 +949,12 @@ Routine Description: if (FunctionType == 0) { sscanf (Line, "%s", KeyWord); if (stricmp (KeyWord, "Address") == 0) { + sscanf (Line, "%s %s", KeyWord, KeyWord2); + if (stricmp (KeyWord2, "Size") == 0) { + IsUseClang = TRUE; + FunctionType = 1; + continue; + } // // function list // @@ -967,11 +976,20 @@ Routine Description: // Printf Function Information // if (FunctionType == 1) { - sscanf (Line, "%s %s %llx %s", KeyWord, FunctionName, &TempLongAddress, FunctionTypeName); - FunctionAddress = (UINT64) TempLongAddress; - if (FunctionTypeName [1] == '\0' && (FunctionTypeName [0] == 'f' || FunctionTypeName [0] == 'F')) { - fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress)); - fprintf (FvMapFile, "%s\n", FunctionName); + if (IsUseClang) { + sscanf (Line, "%llx %s %s %s", &TempLongAddress, KeyWord, KeyWord2, FunctionTypeName); + FunctionAddress = (UINT64) TempLongAddress; + if (FunctionTypeName [0] == '_' ) { + fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress)); + fprintf (FvMapFile, "%s\n", FunctionTypeName); + } + } else { + sscanf (Line, "%s %s %llx %s", KeyWord, FunctionName, &TempLongAddress, FunctionTypeName); + FunctionAddress = (UINT64) TempLongAddress; + if (FunctionTypeName [1] == '\0' && (FunctionTypeName [0] == 'f' || FunctionTypeName [0] == 'F')) { + fprintf (FvMapFile, " 0x%010llx ", (unsigned long long) (ImageBaseAddress + FunctionAddress - LinkTimeBaseAddress)); + fprintf (FvMapFile, "%s\n", FunctionName); + } } } else if (FunctionType == 2) { sscanf (Line, "%s %s %llx %s", KeyWord, FunctionName, &TempLongAddress, FunctionTypeName); From 9e9f0be353d4e28ccbca8f84fc8b2ab1bbe31d5c Mon Sep 17 00:00:00 2001 From: Marvin H?user Date: Tue, 5 Nov 2019 21:50:44 +0800 Subject: [PATCH 055/384] ShellPkg/CommandLib: Use first found UC for unsupported PlatformLang REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2300 On some firmwares PlatformLang is set to the local language (e.g. ru-RU), however there is no Unicode Collation protocol instance that supports it. As for missing PlatformLang, fall back to the first found instance. Cc: Ray Ni Cc: Zhichao Gao Reviewed-by: Zhichao Gao Signed-off-by: Marvin Haeuser --- ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c index 4c48b65fbc1..345808a1eac 100644 --- a/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c +++ b/ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.c @@ -107,9 +107,13 @@ CommandInit( // // Without clue provided use the first Unicode Collation2 protocol. + // This may happen when PlatformLang is NULL or when no installed Unicode + // Collation2 protocol instance supports PlatformLang. // - if (PlatformLang == NULL) { + if (gUnicodeCollation == NULL) { gUnicodeCollation = Uc; + } + if (PlatformLang == NULL) { break; } From f55c76b301f15d287b58cd86dd59be978dc753a3 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 8 Nov 2019 08:58:15 +0100 Subject: [PATCH 056/384] BaseTools/GenFw AARCH64: disregard ADRP instructions that are patched already In order to permit the use of compilers that only implement the small code model [which involves the use of ADRP instructions that require 4 KB segment alignment] for generating PE/COFF binaries with a small footprint, we patch ADRP instructions into ADR instructions while doing the ELF to PE/COFF conversion. As it turns out, the linker may be doing the same, but for different reasons: there is a silicon erratum #843419 for ARM Cortex-A53 which affects ADRP instructions appearing at a certain offset in memory, and one of the mitigations for this erratum is to patch them into ADR instructions at link time if the symbol reference is within -/+ 1 MB. However, the LD linker fails to update the static relocation tables, and so we end up with an ADR instruction in the fully linked binary, but with a relocation entry in the RELA section identifying it as an ADRP instruction. Since the linker has already updated the symbol reference, there is no handling needed in GenFw for such instructions, and we can simply treat it as an ordinary ADR. However, since it is guaranteed to be accompanied by an add or load instruction with a LO12 relocation referencing the same symbol, the section offset check we apply to ADR instructions is going to take place anyway, so we can just disregard the ADR instruction entirely. Reported-by: Eugene Cohen Suggested-by: Eugene Cohen Tested-by: Eugene Cohen Reviewed-by: Leif Lindholm Acked-by: Liming Gao Signed-off-by: Ard Biesheuvel --- BaseTools/Source/C/GenFw/Elf64Convert.c | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/BaseTools/Source/C/GenFw/Elf64Convert.c b/BaseTools/Source/C/GenFw/Elf64Convert.c index d574300ac4f..d623dce1f9d 100644 --- a/BaseTools/Source/C/GenFw/Elf64Convert.c +++ b/BaseTools/Source/C/GenFw/Elf64Convert.c @@ -1044,6 +1044,19 @@ WriteSections64 ( /* fall through */ case R_AARCH64_ADR_PREL_PG_HI21: + // + // In order to handle Cortex-A53 erratum #843419, the LD linker may + // convert ADRP instructions into ADR instructions, but without + // updating the static relocation type, and so we may end up here + // while the instruction in question is actually ADR. So let's + // just disregard it: the section offset check we apply below to + // ADR instructions will trigger for its R_AARCH64_xxx_ABS_LO12_NC + // companion instruction as well, so it is safe to omit it here. + // + if ((*(UINT32 *)Targ & BIT31) == 0) { + break; + } + // // AArch64 PG_H21 relocations are typically paired with ABS_LO12 // relocations, where a PC-relative reference with +/- 4 GB range is From f9d0e5daa058f0cf4caa8edad0dfa2a3a390f1b0 Mon Sep 17 00:00:00 2001 From: Jian J Wang Date: Wed, 6 Nov 2019 21:13:32 +0000 Subject: [PATCH 057/384] MdeModulePkg/DxeIplPeim: reserve page 0 for NULL pointer detection When a boot loader examines the memory map, it can see that location 0 is available memory. If it chooses to use that memory, and PcdNullPointerDetectionPropertyMask is enabled, use of memory in page 0 will cause an exception. This does occur when running the memtest86 program. Leaving page 0 available is for legacy support purpose. Since we have deprecated the support of legacy, the solution is just reserving it so that it cannot be allocated for other uses. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=1885 Cc: Dandan Bi Cc: Liming Gao Cc: Ray Ni Cc: Hao A Wu Cc: Sean Brogan Signed-off-by: Jian J Wang Reviewed-by: Ray Ni --- MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c | 4 ++++ MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c | 4 ++++ 2 files changed, 8 insertions(+) diff --git a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c index 172d7cd1c60..6e8ca824d46 100644 --- a/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c @@ -246,8 +246,12 @@ HandOffToDxeCore ( EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; BOOLEAN BuildPageTablesIa32Pae; + // + // Clear page 0 and mark it as allocated if NULL pointer detection is enabled. + // if (IsNullDetectionEnabled ()) { ClearFirst4KPage (HobList.Raw); + BuildMemoryAllocationHob (0, EFI_PAGES_TO_SIZE (1), EfiBootServicesData); } Status = PeiServicesAllocatePages (EfiBootServicesData, EFI_SIZE_TO_PAGES (STACK_SIZE), &BaseOfStack); diff --git a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c index 2867610bff4..f465eb1d8ac 100644 --- a/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c +++ b/MdeModulePkg/Core/DxeIplPeim/X64/DxeLoadFunc.c @@ -36,8 +36,12 @@ HandOffToDxeCore ( EFI_VECTOR_HANDOFF_INFO *VectorInfo; EFI_PEI_VECTOR_HANDOFF_INFO_PPI *VectorHandoffInfoPpi; + // + // Clear page 0 and mark it as allocated if NULL pointer detection is enabled. + // if (IsNullDetectionEnabled ()) { ClearFirst4KPage (HobList.Raw); + BuildMemoryAllocationHob (0, EFI_PAGES_TO_SIZE (1), EfiBootServicesData); } // From fb92fe9e1817a53ca0fc985447f3c534201a62fa Mon Sep 17 00:00:00 2001 From: Jian J Wang Date: Wed, 6 Nov 2019 21:13:33 +0000 Subject: [PATCH 058/384] MdeModulePkg/Core/Dxe: free page 0 after disabling NULL pointer detection To solve access issue reported by BZ1885, page 0 will be allocated to avoid misuses if NULL pointer detection is enabled. It should be better to be freed after EndOfDxe if BIT7 of PcdNullPointerDetectionPropertyMask is set, because NULL pointer detection is no longer available after EndOfDxe and there will be no access conflict. Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=1885 Cc: Dandan Bi Cc: Liming Gao Cc: Ray Ni Cc: Hao A Wu Cc: Sean Brogan Signed-off-by: Jian J Wang Reviewed-by: Ray Ni --- MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c index 7a24bd07815..47edf86dfbf 100644 --- a/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c +++ b/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c @@ -1094,6 +1094,11 @@ DisableNullDetectionAtTheEndOfDxe ( ); ASSERT_EFI_ERROR (Status); + // + // Page 0 might have be allocated to avoid misuses. Free it here anyway. + // + CoreFreePages (0, 1); + CoreCloseEvent (Event); DEBUG ((DEBUG_INFO, "DisableNullDetectionAtTheEndOfDxe(): end\r\n")); From 05ca7ec3cfe83ca503f305f2b4ea1b9ce292129a Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Sun, 29 Sep 2019 16:22:38 +0800 Subject: [PATCH 059/384] MdePkg/Include: Add DMTF SPDM definition. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2303 Cc: Michael D Kinney Cc: Liming Gao Cc: Yun Lou Signed-off-by: Jiewen Yao Reviewed by: Liming Gao Reviewed by: Ray Ni --- MdePkg/Include/IndustryStandard/Spdm.h | 320 +++++++++++++++++++++++++ 1 file changed, 320 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/Spdm.h diff --git a/MdePkg/Include/IndustryStandard/Spdm.h b/MdePkg/Include/IndustryStandard/Spdm.h new file mode 100644 index 00000000000..c05395fea76 --- /dev/null +++ b/MdePkg/Include/IndustryStandard/Spdm.h @@ -0,0 +1,320 @@ +/** @file + Definitions of Security Protocol & Data Model Specification (SPDM) + version 0.99a in Distributed Management Task Force (DMTF). + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + +#ifndef __SPDM_H__ +#define __SPDM_H__ + +#pragma pack(1) + +/// +/// SPDM response code +/// +#define SPDM_DIGESTS 0x01 +#define SPDM_CERTIFICATE 0x02 +#define SPDM_CHALLENGE_AUTH 0x03 +#define SPDM_VERSION 0x04 +#define SPDM_MEASUREMENTS 0x60 +#define SPDM_CAPABILITIES 0x61 +#define SPDM_SET_CERT_RESPONSE 0x62 +#define SPDM_ALGORITHMS 0x63 +#define SPDM_ERROR 0x7F +/// +/// SPDM request code +/// +#define SPDM_GET_DIGESTS 0x81 +#define SPDM_GET_CERTIFICATE 0x82 +#define SPDM_CHALLENGE 0x83 +#define SPDM_GET_VERSION 0x84 +#define SPDM_GET_MEASUREMENTS 0xE0 +#define SPDM_GET_CAPABILITIES 0xE1 +#define SPDM_NEGOTIATE_ALGORITHMS 0xE3 +#define SPDM_RESPOND_IF_READY 0xFF + +/// +/// SPDM message header +/// +typedef struct { + UINT8 SPDMVersion; + UINT8 RequestResponseCode; + UINT8 Param1; + UINT8 Param2; +} SPDM_MESSAGE_HEADER; + +#define SPDM_MESSAGE_VERSION 0x10 + +/// +/// SPDM GET_VERSION request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; +} SPDM_GET_VERSION_REQUEST; + +/// +/// SPDM GET_VERSION response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT8 Reserved; + UINT8 VersionNumberEntryCount; +//SPDM_VERSION_NUMBER VersionNumberEntry[VersionNumberEntryCount]; +} SPDM_VERSION_RESPONSE; + +/// +/// SPDM VERSION structure +/// +typedef struct { + UINT16 Alpha:4; + UINT16 UpdateVersionNumber:4; + UINT16 MinorVersion:4; + UINT16 MajorVersion:4; +} SPDM_VERSION_NUMBER; + +/// +/// SPDM GET_CAPABILITIES request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; +} SPDM_GET_CAPABILITIES_REQUEST; + +/// +/// SPDM GET_CAPABILITIES response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT8 Reserved; + UINT8 CTExponent; + UINT16 Reserved2; + UINT32 Flags; +} SPDM_CAPABILITIES_RESPONSE; + +/// +/// SPDM GET_CAPABILITIES response Flags +/// +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_CACHE_CAP BIT0 +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_CERT_CAP BIT1 +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_CHAL_CAP BIT2 +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_MEAS_CAP (BIT3 | BIT4) +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_MEAS_CAP_NO_SIG BIT3 +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_MEAS_CAP_SIG BIT4 +#define SPDM_GET_CAPABILITIES_RESPONSE_FLAGS_MEAS_FRESH_CAP BIT5 + +/// +/// SPDM NEGOTIATE_ALGORITHMS request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT16 Length; + UINT8 MeasurementSpecification; + UINT8 Reserved; + UINT32 BaseAsymAlgo; + UINT32 BaseHashAlgo; + UINT8 Reserved2[12]; + UINT8 ExtAsymCount; + UINT8 ExtHashCount; + UINT16 Reserved3; +//UINT32 ExtAsym[ExtAsymCount]; +//UINT32 ExtHash[ExtHashCount]; +} SPDM_NEGOTIATE_ALGORITHMS_REQUEST; + +/// +/// SPDM NEGOTIATE_ALGORITHMS request BaseAsymAlgo +/// +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSASSA_2048 BIT0 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSAPSS_2048 BIT1 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSASSA_3072 BIT2 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSAPSS_3072 BIT3 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_ECDSA_ECC_NIST_P256 BIT4 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSASSA_4096 BIT5 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_RSAPSS_4096 BIT6 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_ECDSA_ECC_NIST_P384 BIT7 +#define SPDM_ALGORITHMS_BASE_ASYM_ALGO_TPM_ALG_ECDSA_ECC_NIST_P521 BIT8 + +/// +/// SPDM NEGOTIATE_ALGORITHMS request BaseHashAlgo +/// +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA_256 BIT0 +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA_384 BIT1 +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA_512 BIT2 +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA3_256 BIT3 +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA3_384 BIT4 +#define SPDM_ALGORITHMS_BASE_HASH_ALGO_TPM_ALG_SHA3_512 BIT5 + +/// +/// SPDM NEGOTIATE_ALGORITHMS response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT16 Length; + UINT8 MeasurementSpecificationSel; + UINT8 Reserved; + UINT32 MeasurementHashAlgo; + UINT32 BaseAsymSel; + UINT32 BaseHashSel; + UINT8 Reserved2[12]; + UINT8 ExtAsymSelCount; + UINT8 ExtHashSelCount; + UINT16 Reserved3; +//UINT32 ExtAsymSel[ExtAsymSelCount]; +//UINT32 ExtHashSel[ExtHashSelCount]; +} SPDM_ALGORITHMS_RESPONSE; + +/// +/// SPDM NEGOTIATE_ALGORITHMS response MeasurementHashAlgo +/// +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_RAW_BIT_STREAM_ONLY BIT0 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA_256 BIT1 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA_384 BIT2 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA_512 BIT3 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA3_256 BIT4 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA3_384 BIT5 +#define SPDM_ALGORITHMS_MEASUREMENT_HASH_ALGO_TPM_ALG_SHA3_512 BIT6 + +/// +/// SPDM GET_DIGESTS request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; +} SPDM_GET_DIGESTS_REQUEST; + +/// +/// SPDM GET_DIGESTS response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; +//UINT8 Digest[DigestSize]; +} SPDM_DIGESTS_RESPONSE; + +/// +/// SPDM GET_DIGESTS request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT16 Offset; + UINT16 Length; +} SPDM_GET_CERTIFICATE_REQUEST; + +/// +/// SPDM GET_DIGESTS response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT16 PortionLength; + UINT16 RemainderLength; +//UINT8 CertChain[CertChainSize]; +} SPDM_CERTIFICATE_RESPONSE; + +/// +/// SPDM CHALLENGE request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT32 Nonce; +} SPDM_CHALLENGE_REQUEST; + +/// +/// SPDM CHALLENGE response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; +//UINT8 CertChainHash[DigestSize]; +//UINT32 Nonce; +//UINT8 MeasurementSummaryHash[DigestSize]; +//UINT16 OpaqueLength; +//UINT8 OpaqueData[OpaqueLength]; +//UINT8 Signature[KeySize]; +} SPDM_CHALLENGE_AUTH_RESPONSE; + +/// +/// SPDM GET_MEASUREMENTS request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT32 Nonce; +} SPDM_GET_MEASUREMENTS_REQUEST; + +/// +/// SPDM MEASUREMENTS block common header +/// +typedef struct { + UINT8 Index; + UINT8 MeasurementSpecification; + UINT16 MeasurementSize; +//UINT8 Measurement[MeasurementSize]; +} SPDM_MEASUREMENT_BLOCK_COMMON_HEADER; + +#define SPDM_MEASUREMENT_BLOCK_HEADER_SPECIFICATION_DMTF BIT0 + +/// +/// SPDM MEASUREMENTS block DMTF header +/// +typedef struct { + UINT8 DMTFSpecMeasurementValueType; + UINT16 DMTFSpecMeasurementValueSize; +//UINT8 DMTFSpecMeasurementValue[DMTFSpecMeasurementValueSize]; +} SPDM_MEASUREMENT_BLOCK_DMTF_HEADER; + +/// +/// SPDM MEASUREMENTS block MeasurementValueType +/// +#define SPDM_MEASUREMENT_BLOCK_MEASUREMENT_TYPE_IMMUTABLE_ROM 0 +#define SPDM_MEASUREMENT_BLOCK_MEASUREMENT_TYPE_MUTABLE_FIRMWARE 1 +#define SPDM_MEASUREMENT_BLOCK_MEASUREMENT_TYPE_HARDWARE_CONFIGURATION 2 +#define SPDM_MEASUREMENT_BLOCK_MEASUREMENT_TYPE_FIRMWARE_CONFIGURATION 3 +#define SPDM_MEASUREMENT_BLOCK_MEASUREMENT_TYPE_RAW_BIT_STREAM BIT7 + +/// +/// SPDM GET_MEASUREMENTS response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + UINT8 NumberOfBlocks; + UINT8 MeasurementRecordLength[3]; +//UINT8 MeasurementRecord[MeasurementRecordLength]; +//UINT32 Nonce; +//UINT16 OpaqueLength; +//UINT8 OpaqueData[OpaqueLength]; +//UINT8 Signature[KeySize]; +} SPDM_MEASUREMENTS_RESPONSE; + +/// +/// SPDM ERROR response +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + // Param1 == Error Code + // Param2 == Error Data +//UINT8 ExtendedErrorData[]; +} SPDM_ERROR_RESPONSE; + +/// +/// SPDM error code +/// +#define SPDM_ERROR_CODE_INVALID_REQUEST 0x01 +#define SPDM_ERROR_CODE_BUSY 0x03 +#define SPDM_ERROR_CODE_UNEXPECTED_REQUEST 0x04 +#define SPDM_ERROR_CODE_UNSPECIFIED 0x05 +#define SPDM_ERROR_CODE_UNSUPPORTED_REQUEST 0x07 +#define SPDM_ERROR_CODE_MAJOR_VERSION_MISMATCH 0x41 +#define SPDM_ERROR_CODE_RESPONSE_NOT_READY 0x42 +#define SPDM_ERROR_CODE_REQUEST_RESYNCH 0x43 + +/// +/// SPDM RESPONSE_IF_READY request +/// +typedef struct { + SPDM_MESSAGE_HEADER Header; + // Param1 == RequestCode + // Param2 == Token +} SPDM_RESPONSE_IF_READY_REQUEST; + +#pragma pack() + +#endif + From aa4db5b15ef95061c18cbad58ae04479d030967b Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Sun, 20 Oct 2019 17:06:51 +0800 Subject: [PATCH 060/384] MdeModulePkg/Include: Add DeviceSecurity.h REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2303 EDKII_DEVICE_SECURITY_PROTOCOL is used for device measurement and/or authentication. It is similar to EFI_SECURITY_ARCH_PROTOCOL. Cc: Jian J Wang Cc: Hao A Wu Cc: Yun Lou Signed-off-by: Jiewen Yao Reviewed by: Ray Ni --- .../Include/Protocol/DeviceSecurity.h | 162 ++++++++++++++++++ 1 file changed, 162 insertions(+) create mode 100644 MdeModulePkg/Include/Protocol/DeviceSecurity.h diff --git a/MdeModulePkg/Include/Protocol/DeviceSecurity.h b/MdeModulePkg/Include/Protocol/DeviceSecurity.h new file mode 100644 index 00000000000..c3bf624cac3 --- /dev/null +++ b/MdeModulePkg/Include/Protocol/DeviceSecurity.h @@ -0,0 +1,162 @@ +/** @file + Device Security Protocol definition. + + It is used to authenticate a device based upon the platform policy. + It is similar to the EFI_SECURITY_ARCH_PROTOCOL, which is used to verify a image. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + +#ifndef __DEVICE_SECURITY_H__ +#define __DEVICE_SECURITY_H__ + +// +// Device Security Protocol GUID value +// +#define EDKII_DEVICE_SECURITY_PROTOCOL_GUID \ + { \ + 0x5d6b38c8, 0x5510, 0x4458, { 0xb4, 0x8d, 0x95, 0x81, 0xcf, 0xa7, 0xb0, 0xd } \ + } + +// +// Forward reference for pure ANSI compatability +// +typedef struct _EDKII_DEVICE_SECURITY_PROTOCOL EDKII_DEVICE_SECURITY_PROTOCOL; + +// +// Revision The revision to which the DEVICE_SECURITY interface adheres. +// All future revisions must be backwards compatible. +// If a future version is not back wards compatible it is not the same GUID. +// +#define EDKII_DEVICE_SECURITY_PROTOCOL_REVISION 0x00010000 + +// +// The device identifier. +// +typedef struct { + /// + /// Version of this data structure. + /// + UINT32 Version; + /// + /// Type of the device. + /// This field is also served as a device Access protocol GUID. + /// The device access protocol is installed on the DeviceHandle. + /// The device access protocol is device specific. + /// EDKII_DEVICE_IDENTIFIER_TYPE_PCI_GUID means the device access protocol is PciIo. + /// EDKII_DEVICE_IDENTIFIER_TYPE_USB_GUID means the device access protocol is UsbIo. + /// + EFI_GUID DeviceType; + /// + /// The handle created for this device. + /// NOTE: This might be a temporary handle. + /// If the device is not authenticated, this handle shall be uninstalled. + /// + /// As minimal requirement, there should be 2 protocols installed on the device handle. + /// 1) An EFI_DEVICE_PATH_PROTOCOL with EFI_DEVICE_PATH_PROTOCOL_GUID. + /// 2) A device access protocol with EDKII_DEVICE_IDENTIFIER_TYPE_xxx_GUID. + /// If the device is PCI device, the EFI_PCI_IO_PROTOCOL is installed with + /// EDKII_DEVICE_IDENTIFIER_TYPE_PCI_GUID. + /// If the device is USB device, the EFI_USB_IO_PROTOCOL is installed with + /// EDKII_DEVICE_IDENTIFIER_TYPE_USB_GUID. + /// + /// The device access protocol is required, because the verifier need have a way + /// to communciate with the device hardware to get the measurement or do the + /// challenge/response for the device authentication. + /// + /// NOTE: We don't use EFI_PCI_IO_PROTOCOL_GUID or EFI_USB_IO_PROTOCOL_GUID here, + /// because we don't want to expose a real protocol. A platform may have driver + /// register a protocol notify function. Installing a real protocol may cause + /// the callback function being executed before the device is authenticated. + /// + EFI_HANDLE DeviceHandle; +} EDKII_DEVICE_IDENTIFIER; + +// +// Revision The revision to which the DEVICE_IDENTIFIER interface adheres. +// All future revisions must be backwards compatible. +// +#define EDKII_DEVICE_IDENTIFIER_REVISION 0x00010000 + +// +// Device Identifier GUID value +// +#define EDKII_DEVICE_IDENTIFIER_TYPE_PCI_GUID \ + { \ + 0x2509b2f1, 0xa022, 0x4cca, { 0xaf, 0x70, 0xf9, 0xd3, 0x21, 0xfb, 0x66, 0x49 } \ + } + +#define EDKII_DEVICE_IDENTIFIER_TYPE_USB_GUID \ + { \ + 0x7394f350, 0x394d, 0x488c, { 0xbb, 0x75, 0xc, 0xab, 0x7b, 0x12, 0xa, 0xc5 } \ + } + +/** + The device driver uses this service to measure and/or verify a device. + + The flow in device driver is: + 1) Device driver discovers a new device. + 2) Device driver creates an EFI_DEVICE_PATH_PROTOCOL. + 3) Device driver creates a device access protocol. e.g. + EFI_PCI_IO_PROTOCOL for PCI device. + EFI_USB_IO_PROTOCOL for USB device. + EFI_EXT_SCSI_PASS_THRU_PROTOCOL for SCSI device. + EFI_ATA_PASS_THRU_PROTOCOL for ATA device. + EFI_NVM_EXPRESS_PASS_THRU_PROTOCOL for NVMe device. + EFI_SD_MMC_PASS_THRU_PROTOCOL for SD/MMC device. + 4) Device driver installs the EFI_DEVICE_PATH_PROTOCOL with EFI_DEVICE_PATH_PROTOCOL_GUID, + and the device access protocol with EDKII_DEVICE_IDENTIFIER_TYPE_xxx_GUID. + Once it is done, a DeviceHandle is returned. + 5) Device driver creates EDKII_DEVICE_IDENTIFIER with EDKII_DEVICE_IDENTIFIER_TYPE_xxx_GUID + and the DeviceHandle. + 6) Device driver calls DeviceAuthenticate(). + 7) If DeviceAuthenticate() returns EFI_SECURITY_VIOLATION, the device driver uninstalls + all protocols on this handle. + 8) If DeviceAuthenticate() returns EFI_SUCCESS, the device driver installs the device access + protocol with a real protocol GUID. e.g. + EFI_PCI_IO_PROTOCOL with EFI_PCI_IO_PROTOCOL_GUID. + EFI_USB_IO_PROTOCOL with EFI_USB_IO_PROTOCOL_GUID. + + @param[in] This The protocol instance pointer. + @param[in] DeviceId The Identifier for the device. + + @retval EFI_SUCCESS The device specified by the DeviceId passed the measurement + and/or authentication based upon the platform policy. + If TCG measurement is required, the measurement is extended to TPM PCR. + @retval EFI_SECURITY_VIOLATION The device fails to return the measurement data. + @retval EFI_SECURITY_VIOLATION The device fails to response the authentication request. + @retval EFI_SECURITY_VIOLATION The system fails to verify the device based upon the authentication response. + @retval EFI_SECURITY_VIOLATION The system fails to extend the measurement to TPM PCR. +**/ +typedef +EFI_STATUS +(EFIAPI *EDKII_DEVICE_AUTHENTICATE)( + IN EDKII_DEVICE_SECURITY_PROTOCOL *This, + IN EDKII_DEVICE_IDENTIFIER *DeviceId + ); + +/// +/// Device Security Protocol structure. +/// It is similar to the EFI_SECURITY_ARCH_PROTOCOL, which is used to verify a image. +/// This protocol is used to authenticate a device based upon the platform policy. +/// +struct _EDKII_DEVICE_SECURITY_PROTOCOL { + UINT64 Revision; + EDKII_DEVICE_AUTHENTICATE DeviceAuthenticate; +}; + +/// +/// Device Security Protocol GUID variable. +/// +extern EFI_GUID gEdkiiDeviceSecurityProtocolGuid; + +/// +/// Device Identifier tpye GUID variable. +/// +extern EFI_GUID gEdkiiDeviceIdentifierTypePciGuid; +extern EFI_GUID gEdkiiDeviceIdentifierTypeUsbGuid; + +#endif From 985e0a6de7482868c18d298f08db54d4339f2ea7 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Sun, 20 Oct 2019 17:07:06 +0800 Subject: [PATCH 061/384] MdeModulePkg/dec: Add EdkiiDeviceSecurityProtocolGuid. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2303 Cc: Jian J Wang Cc: Hao A Wu Cc: Yun Lou Signed-off-by: Jiewen Yao Reviewed by: Ray Ni --- MdeModulePkg/MdeModulePkg.dec | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 1e964f59032..41b9e70a1ac 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -584,6 +584,11 @@ ## Include/Protocol/IoMmu.h gEdkiiIoMmuProtocolGuid = { 0x4e939de9, 0xd948, 0x4b0f, { 0x88, 0xed, 0xe6, 0xe1, 0xce, 0x51, 0x7c, 0x1e } } + ## Include/Protocol/DeviceSecurity.h + gEdkiiDeviceSecurityProtocolGuid = { 0x5d6b38c8, 0x5510, 0x4458, { 0xb4, 0x8d, 0x95, 0x81, 0xcf, 0xa7, 0xb0, 0xd } } + gEdkiiDeviceIdentifierTypePciGuid = { 0x2509b2f1, 0xa022, 0x4cca, { 0xaf, 0x70, 0xf9, 0xd3, 0x21, 0xfb, 0x66, 0x49 } } + gEdkiiDeviceIdentifierTypeUsbGuid = { 0x7394f350, 0x394d, 0x488c, { 0xbb, 0x75, 0xc, 0xab, 0x7b, 0x12, 0xa, 0xc5 } } + ## Include/Protocol/SmmMemoryAttribute.h gEdkiiSmmMemoryAttributeProtocolGuid = { 0x69b792ea, 0x39ce, 0x402d, { 0xa2, 0xa6, 0xf7, 0x21, 0xde, 0x35, 0x1d, 0xfe } } From 995d8b8568fe67afffdaac3012d7b990e7314d0b Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Sun, 29 Sep 2019 16:37:14 +0800 Subject: [PATCH 062/384] MdeModulePkg/Pci: Add DeviceSecurity support. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2303 Whenever a PCI device is discovered, PCI bus calls the EDKII_DEVICE_SECURITY_PROTOCOL to authenticate it. If the function returns success, the PCI bus allocates the resource and installs the PCI_IO for the device. If the function returns fail, the PCI bus skips the device. It is similar to EFI_SECURITY_ARCH_PROTOCOL, which is used to verify an EFI image. Cc: Jian J Wang Cc: Hao A Wu Cc: Ray Ni Cc: Yun Lou Signed-off-by: Jiewen Yao Reviewed-by: Ray Ni --- MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c | 12 ++- MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h | 1 + MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf | 4 +- .../Bus/Pci/PciBusDxe/PciEnumeratorSupport.c | 77 +++++++++++++++++++ MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c | 4 +- 5 files changed, 94 insertions(+), 4 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c index b020ce50ce3..64284ac8251 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.c @@ -8,7 +8,7 @@ PCI Root Bridges. So it means platform needs install PCI Root Bridge IO protocol for each PCI Root Bus and install PCI Host Bridge Resource Allocation Protocol. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -37,7 +37,7 @@ UINT64 gAllZero = 0; EFI_PCI_PLATFORM_PROTOCOL *gPciPlatformProtocol; EFI_PCI_OVERRIDE_PROTOCOL *gPciOverrideProtocol; EDKII_IOMMU_PROTOCOL *mIoMmuProtocol; - +EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; GLOBAL_REMOVE_IF_UNREFERENCED EFI_PCI_HOTPLUG_REQUEST_PROTOCOL mPciHotPlugRequest = { PciHotPlugRequestNotify @@ -293,6 +293,14 @@ PciBusDriverBindingStart ( ); } + if (mDeviceSecurityProtocol == NULL) { + gBS->LocateProtocol ( + &gEdkiiDeviceSecurityProtocolGuid, + NULL, + (VOID **) &mDeviceSecurityProtocol + ); + } + if (PcdGetBool (PcdPciDisableBusEnumeration)) { gFullEnumeration = FALSE; } else { diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h index 504a1b1c129..d4113993c8a 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBus.h @@ -27,6 +27,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf index 05c22025b86..9284998f361 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciBusDxe.inf @@ -2,7 +2,7 @@ # The PCI bus driver will probe all PCI devices and allocate MMIO and IO space for these devices. # Please use PCD feature flag PcdPciBusHotplugDeviceSupport to enable hot plug supporting. # -# Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -90,6 +90,8 @@ gEfiIncompatiblePciDeviceSupportProtocolGuid ## SOMETIMES_CONSUMES gEfiLoadFile2ProtocolGuid ## SOMETIMES_PRODUCES gEdkiiIoMmuProtocolGuid ## SOMETIMES_CONSUMES + gEdkiiDeviceSecurityProtocolGuid ## SOMETIMES_CONSUMES + gEdkiiDeviceIdentifierTypePciGuid ## SOMETIMES_CONSUMES gEfiLoadedImageDevicePathProtocolGuid ## CONSUMES [FeaturePcd] diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c index c7eafff5935..f8020f4e721 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciEnumeratorSupport.c @@ -10,6 +10,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include "PciBus.h" extern CHAR16 *mBarTypeStr[]; +extern EDKII_DEVICE_SECURITY_PROTOCOL *mDeviceSecurityProtocol; #define OLD_ALIGN 0xFFFFFFFFFFFFFFFFULL #define EVEN_ALIGN 0xFFFFFFFFFFFFFFFEULL @@ -2070,6 +2071,67 @@ InitializeP2C ( PciIo->Pci.Write (PciIo, EfiPciIoWidthUint8, 0x3C, 1, &gAllZero); } +/* + Authenticate the PCI device by using DeviceSecurityProtocol. + + @param PciIoDevice PCI device. + + @retval EFI_SUCCESS The device passes the authentication. + @return not EFI_SUCCESS The device failes the authentication or + unexpected error happen during authentication. +*/ +EFI_STATUS +AuthenticatePciDevice ( + IN PCI_IO_DEVICE *PciIoDevice + ) +{ + EDKII_DEVICE_IDENTIFIER DeviceIdentifier; + EFI_STATUS Status; + + if (mDeviceSecurityProtocol != NULL) { + // + // Prepare the parameter + // + DeviceIdentifier.Version = EDKII_DEVICE_IDENTIFIER_REVISION; + CopyGuid (&DeviceIdentifier.DeviceType, &gEdkiiDeviceIdentifierTypePciGuid); + DeviceIdentifier.DeviceHandle = NULL; + Status = gBS->InstallMultipleProtocolInterfaces ( + &DeviceIdentifier.DeviceHandle, + &gEfiDevicePathProtocolGuid, + PciIoDevice->DevicePath, + &gEdkiiDeviceIdentifierTypePciGuid, + &PciIoDevice->PciIo, + NULL + ); + if (EFI_ERROR(Status)) { + return Status; + } + + // + // Do DeviceAuthentication + // + Status = mDeviceSecurityProtocol->DeviceAuthenticate (mDeviceSecurityProtocol, &DeviceIdentifier); + // + // Always uninstall, because they are only for Authentication. + // No need to check return Status. + // + gBS->UninstallMultipleProtocolInterfaces ( + DeviceIdentifier.DeviceHandle, + &gEfiDevicePathProtocolGuid, + PciIoDevice->DevicePath, + &gEdkiiDeviceIdentifierTypePciGuid, + &PciIoDevice->PciIo, + NULL + ); + return Status; + } + + // + // Device Security Protocol is not found, just return success + // + return EFI_SUCCESS; +} + /** Create and initialize general PCI I/O device instance for PCI device/bridge device/hotplug bridge device. @@ -2156,6 +2218,21 @@ CreatePciIoDevice ( PciIoDevice->IsPciExp = TRUE; } + // + // Now we can do the authentication check for the device. + // + Status = AuthenticatePciDevice (PciIoDevice); + // + // If authentication fails, skip this device. + // + if (EFI_ERROR(Status)) { + if (PciIoDevice->DevicePath != NULL) { + FreePool (PciIoDevice->DevicePath); + } + FreePool (PciIoDevice); + return NULL; + } + if (PcdGetBool (PcdAriSupport)) { // // Check if the device is an ARI device. diff --git a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c index 5b55fb5d3be..72690ab6476 100644 --- a/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c +++ b/MdeModulePkg/Bus/Pci/PciBusDxe/PciLib.c @@ -1054,7 +1054,9 @@ PciScanBus ( &PciDevice ); - ASSERT (!EFI_ERROR (Status)); + if (EFI_ERROR (Status)) { + continue; + } PciAddress = EFI_PCI_ADDRESS (StartBusNumber, Device, Func, 0); From cc6854506c2b2ab17007c1efe8ec9d0b536a5798 Mon Sep 17 00:00:00 2001 From: Leif Lindholm Date: Tue, 29 Oct 2019 09:54:36 +0800 Subject: [PATCH 063/384] Readme.md: remove positional references from submodule description Remove references to the number of submodules in the tree, as well as reword the referring to specific submodules as "former" and "previous". This means we won't need to keep updating the surrounding text if we add/remove submodules. Cc: Andrew Fish Cc: Michael D Kinney Signed-off-by: Leif Lindholm Reviewed-by: Laszlo Ersek --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index 27e4ce07719..9bf60bede8e 100644 --- a/Readme.md +++ b/Readme.md @@ -144,12 +144,12 @@ Signed-off-by: Contributor Name # Submodules Submodule in EDK II is allowed but submodule chain should be avoided -as possible as we can. Currently EDK II contains two submodules +as possible as we can. Currently EDK II contains the following submodules - CryptoPkg/Library/OpensslLib/openssl - ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 -The latter one is actually required by previous one. It's inevitable +ArmSoftFloatLib is actually required by OpensslLib. It's inevitable in openssl-1.1.1 (since stable201905) for floating point parameter conversion, but should be dropped once there's no such need in future release of openssl. From 021eb1820e31874618cfda0785f7eae2f0ec7ba9 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 25 Oct 2019 11:44:54 -0700 Subject: [PATCH 064/384] Maintainers.txt: Add continuous integration(CI) directories https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add maintainers and reviewers for the directories associated with continuous integration steps. * .azurepipelines * .mergify * .pytool Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Michael D Kinney Reviewed-by: Leif Lindholm Reviewed-by: Laszlo Ersek --- Maintainers.txt | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/Maintainers.txt b/Maintainers.txt index 922cc664ddc..180ad35d097 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -98,6 +98,29 @@ F: */Arm/ M: Leif Lindholm M: Ard Biesheuvel +EDK II Continuous Integration: +------------------------------ +.azurepipelines/ +F: .azurepipelines/ +M: Sean Brogan +M: Bret Barkelew +R: Michael D Kinney +R: Liming Gao + +.mergify/ +F: .mergify/ +M: Michael D Kinney +M: Liming Gao +R: Sean Brogan +R: Bret Barkelew + +.pytool/ +F: .pytool/ +M: Sean Brogan +M: Bret Barkelew +R: Michael D Kinney +R: Liming Gao + EDK II Packages: ---------------- ArmPkg From 48760409ccc8a11976892da6c7bf930144f61fda Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 24 Sep 2019 22:34:18 -0700 Subject: [PATCH 065/384] .gitignore: Ignore python compiled files, extdeps, and vscode https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Update .gitignore to ignore .pyc files and __pycache__ directories. Python based plugins can be added to any package or platform, so these files and directories may be present outside of BaseTools. Ignore _extdep directories that are generated by the pytool external dependency feature. Ignore .vscode directories generated by the VS Code editor. Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Kinney Reviewed-by: Leif Lindholm Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Laszlo Ersek Reviewed-by: Liming Gao --- .gitignore | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index 97f22c348c1..1dd30c14106 100644 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,7 @@ Build/ -tags/ .DS_Store +*_extdep/ +*.pyc +__pycache__/ +tags/ +.vscode/ From ab5892f260b0a49f85038e9cab7da4576b8b1874 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 24 Sep 2019 21:34:26 -0700 Subject: [PATCH 066/384] pip-requirements.txt: Add python pip requirements file https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add pip requirements file that is used to install the python pip modules build from the edk2-pytool-library and edk2-pytool-extensions repositories. These python modules provide the extensions required to perform EDK II Continuous Integration(CI) builds. Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao Reviewed-by: Laszlo Ersek --- pip-requirements.txt | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 pip-requirements.txt diff --git a/pip-requirements.txt b/pip-requirements.txt new file mode 100644 index 00000000000..6a41a95ec59 --- /dev/null +++ b/pip-requirements.txt @@ -0,0 +1,16 @@ +## @file +# EDK II Python PIP requirements file +# +# This file provides the list of python components to install using PIP. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# https://pypi.org/project/pip/ +# https://pip.pypa.io/en/stable/user_guide/#requirements-files +# https://pip.pypa.io/en/stable/reference/pip_install/#requirements-file-format +# +## + +edk2-pytool-library==0.10.* +edk2-pytool-extensions==0.12.* From 7569e35bc9f965c4b385d7cc91118228c1d93716 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Mon, 7 Oct 2019 19:54:21 -0700 Subject: [PATCH 067/384] BaseTools: Add RC_PATH define for VS2017/2019 https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add use of RC_PATH define that provides the path to the resource compiler that is typically provided in a Windows SDK. The path changes with different Windows SDK releases. This define is set to the WINSDK_PATH_FOR_RC_EXE environment variable. This environment variable must be set to the path to the currently installed resource compiler (rc.exe). Update set_vsprefix_envs.bat to set WINSDK_PATH_FOR_RC_EXE if a Windows SDK is detected. Cc: Bob Feng Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- BaseTools/Conf/tools_def.template | 18 ++++++++++++++++-- BaseTools/set_vsprefix_envs.bat | 10 ++++++++++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index dce6c5875a2..afa13a7cae7 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -4,9 +4,18 @@ # Portions copyright (c) 2011 - 2014, ARM Ltd. All rights reserved.
# Copyright (c) 2015, Hewlett-Packard Development Company, L.P.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
+# Copyright (c) Microsoft Corporation # # SPDX-License-Identifier: BSD-2-Clause-Patent # +# +# Increase this version tag any time you want user to get warning about updating this +# file in the Conf dir. By default it does not do update existing conf dirs. +# +# 2.00 - Initial version with changes for CI +# - Change RC path to use plugin +# +#!VERSION=2.00 IDENTIFIER = Default TOOL_CHAIN_CONF @@ -71,6 +80,11 @@ DEFINE VS2019_BIN_X64 = DEF(VS2019_BIN)\HostDEF(VS_HOST)\x64 DEFINE VS2019_BIN_ARM = DEF(VS2019_BIN)\HostDEF(VS_HOST)\arm DEFINE VS2019_BIN_AARCH64 = DEF(VS2019_BIN)\HostDEF(VS_HOST)\arm64 +# +# Resource compiler +# +DEFINE RC_PATH = ENV(WINSDK_PATH_FOR_RC_EXE)\rc.exe + DEFINE WINSDK_BIN = ENV(WINSDK_PREFIX) DEFINE WINSDKx86_BIN = ENV(WINSDKx86_PREFIX) @@ -1566,7 +1580,7 @@ NOOPT_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2017_*_MAKE_PATH = DEF(VS2017_BIN_HOST)\nmake.exe *_VS2017_*_MAKE_FLAG = /nologo -*_VS2017_*_RC_PATH = DEF(WINSDK10_BIN)\rc.exe +*_VS2017_*_RC_PATH = DEF(RC_PATH) *_VS2017_*_MAKE_FLAGS = /nologo *_VS2017_*_SLINK_FLAGS = /NOLOGO /LTCG @@ -1729,7 +1743,7 @@ NOOPT_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2019_*_MAKE_PATH = DEF(VS2019_BIN_HOST)\nmake.exe *_VS2019_*_MAKE_FLAG = /nologo -*_VS2019_*_RC_PATH = DEF(WINSDK10_BIN)\rc.exe +*_VS2019_*_RC_PATH = DEF(RC_PATH) *_VS2019_*_MAKE_FLAGS = /nologo *_VS2019_*_SLINK_FLAGS = /NOLOGO /LTCG diff --git a/BaseTools/set_vsprefix_envs.bat b/BaseTools/set_vsprefix_envs.bat index 6dff25d9300..9966a5a4ed5 100644 --- a/BaseTools/set_vsprefix_envs.bat +++ b/BaseTools/set_vsprefix_envs.bat @@ -158,6 +158,11 @@ if defined VCToolsInstallDir ( ) ) ) +if not defined WINSDK_PATH_FOR_RC_EXE ( + if defined WINSDK10_PREFIX ( + set "WINSDK_PATH_FOR_RC_EXE=%WINSDK10_PREFIX%x86" + ) +) :SetVS2017 if not defined VS150COMNTOOLS ( @@ -209,6 +214,11 @@ if defined VCToolsInstallDir ( ) ) ) +if not defined WINSDK_PATH_FOR_RC_EXE ( + if defined WINSDK10_PREFIX ( + set "WINSDK_PATH_FOR_RC_EXE=%WINSDK10_PREFIX%x86" + ) +) :SetWinDDK if not defined WINDDK3790_PREFIX ( From f7978bb25869408ab24673beb9f83d9b81f8061c Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Mon, 7 Oct 2019 18:37:13 -0700 Subject: [PATCH 068/384] BaseTools: Add YAML files with path env and tool extdeps https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Cc: Bob Feng Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml | 21 +++ BaseTools/Bin/gcc_arm_linux_ext_dep.yaml | 21 +++ BaseTools/Bin/iasl_ext_dep.yaml | 21 +++ BaseTools/Bin/nasm_ext_dep.yaml | 18 ++ .../BinWrappers/PosixLike/posix_path_env.yaml | 10 ++ .../WindowsLike/win_build_tools_path_env.yaml | 10 ++ BaseTools/Edk2ToolsBuild.py | 163 ++++++++++++++++++ .../basetool_tiano_python_path_env.yaml | 11 ++ BaseTools/basetools_calling_path_env.yaml | 11 ++ BaseTools/basetools_path_env.yaml | 11 ++ 10 files changed, 297 insertions(+) create mode 100644 BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml create mode 100644 BaseTools/Bin/gcc_arm_linux_ext_dep.yaml create mode 100644 BaseTools/Bin/iasl_ext_dep.yaml create mode 100644 BaseTools/Bin/nasm_ext_dep.yaml create mode 100644 BaseTools/BinWrappers/PosixLike/posix_path_env.yaml create mode 100644 BaseTools/BinWrappers/WindowsLike/win_build_tools_path_env.yaml create mode 100644 BaseTools/Edk2ToolsBuild.py create mode 100644 BaseTools/Source/Python/basetool_tiano_python_path_env.yaml create mode 100644 BaseTools/basetools_calling_path_env.yaml create mode 100644 BaseTools/basetools_path_env.yaml diff --git a/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml b/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml new file mode 100644 index 00000000000..e81223fd9ad --- /dev/null +++ b/BaseTools/Bin/gcc_aarch64_linux_ext_dep.yaml @@ -0,0 +1,21 @@ +## @file +# Download GCC AARCH64 compiler from Linaro's release site +# Set shell variable GCC5_AARCH64_INSTALL to this folder +# +# This is only downloaded when a build activates scope gcc_aarch64_linux +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "gcc_aarch64_linux", + "type": "web", + "name": "gcc_aarch64_linux", + "source": "http://releases.linaro.org/components/toolchain/binaries/7.4-2019.02/aarch64-linux-gnu/gcc-linaro-7.4.1-2019.02-x86_64_aarch64-linux-gnu.tar.xz", + "version": "7.4.1", + "sha256": "27f1dc2c491ed61ae8f0d4b0c11de59cd2f7dd9c94761ee7153006fcac1bf9ab", + "compression_type": "tar", + "internal_path": "/gcc-linaro-7.4.1-2019.02-x86_64_aarch64-linux-gnu/", + "flags": ["set_shell_var", ], + "var_name": "GCC5_AARCH64_INSTALL" +} diff --git a/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml b/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml new file mode 100644 index 00000000000..09481ceae05 --- /dev/null +++ b/BaseTools/Bin/gcc_arm_linux_ext_dep.yaml @@ -0,0 +1,21 @@ +## @file +# Download GCC ARM compiler from Linaro's release site +# Set shell variable GCC5_ARM_INSTALL to this folder +# +# This is only downloaded when a build activates scope gcc_arm_linux +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "gcc_arm_linux", + "type": "web", + "name": "gcc_arm_linux", + "source": "https://releases.linaro.org/components/toolchain/binaries/7.4-2019.02/arm-linux-gnueabihf/gcc-linaro-7.4.1-2019.02-x86_64_arm-linux-gnueabihf.tar.xz", + "version": "7.4.1", + "sha256": "3C951CF1941D0FA06D64CC0D5E88612B209D8123B273FA26C16D70BD7BC6B163", + "compression_type": "tar", + "internal_path": "/gcc-linaro-7.4.1-2019.02-x86_64_arm-linux-gnueabihf/", + "flags": ["set_shell_var", ], + "var_name": "GCC5_ARM_INSTALL" +} diff --git a/BaseTools/Bin/iasl_ext_dep.yaml b/BaseTools/Bin/iasl_ext_dep.yaml new file mode 100644 index 00000000000..1d81e89cf3a --- /dev/null +++ b/BaseTools/Bin/iasl_ext_dep.yaml @@ -0,0 +1,21 @@ +## @file +# Download iasl executable tool from a nuget.org package +# - package contains different binaries based on host +# Add the folder with the tool to the path +# +# This is only downloaded for scope cibuild thus +# should have no impact on the asl compiler used by any +# given platform to build. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "id": "iasl-ci-1", + "scope": "cibuild", + "type": "nuget", + "name": "iasl", + "source": "https://api.nuget.org/v3/index.json", + "version": "20190215.0.0", + "flags": ["set_path", "host_specific"] +} diff --git a/BaseTools/Bin/nasm_ext_dep.yaml b/BaseTools/Bin/nasm_ext_dep.yaml new file mode 100644 index 00000000000..60b1f71b56a --- /dev/null +++ b/BaseTools/Bin/nasm_ext_dep.yaml @@ -0,0 +1,18 @@ +## @file +# Download nasm x86 assembler executable tool from a nuget.org package +# - package contains different binaries based on host +# Put on the tool on the path +# +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "id": "nasm-1", + "scope": "edk2-build", + "type": "nuget", + "name": "mu_nasm", + "source": "https://api.nuget.org/v3/index.json", + "version": "2.14.02", + "flags": ["set_path", "host_specific"] +} diff --git a/BaseTools/BinWrappers/PosixLike/posix_path_env.yaml b/BaseTools/BinWrappers/PosixLike/posix_path_env.yaml new file mode 100644 index 00000000000..8b32e010bb1 --- /dev/null +++ b/BaseTools/BinWrappers/PosixLike/posix_path_env.yaml @@ -0,0 +1,10 @@ +## @file +# Set this folder on the path for all linux builds +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-nix", + "flags": ["set_path"] +} diff --git a/BaseTools/BinWrappers/WindowsLike/win_build_tools_path_env.yaml b/BaseTools/BinWrappers/WindowsLike/win_build_tools_path_env.yaml new file mode 100644 index 00000000000..83f5856e75c --- /dev/null +++ b/BaseTools/BinWrappers/WindowsLike/win_build_tools_path_env.yaml @@ -0,0 +1,10 @@ +## @file +# Add this folder to the path on Windows +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-win", + "flags": ["set_path"] +} diff --git a/BaseTools/Edk2ToolsBuild.py b/BaseTools/Edk2ToolsBuild.py new file mode 100644 index 00000000000..057d2e9e063 --- /dev/null +++ b/BaseTools/Edk2ToolsBuild.py @@ -0,0 +1,163 @@ +# @file Edk2ToolsBuild.py +# Invocable class that builds the basetool c files. +# +# Supports VS2017, VS2019, and GCC5 +## +# Copyright (c) Microsoft Corporation +# +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import sys +import logging +import argparse +from edk2toolext import edk2_logging +from edk2toolext.environment import self_describing_environment +from edk2toolext.base_abstract_invocable import BaseAbstractInvocable +from edk2toollib.utility_functions import RunCmd +from edk2toollib.windows.locate_tools import QueryVcVariables + + +class Edk2ToolsBuild(BaseAbstractInvocable): + + def ParseCommandLineOptions(self): + ''' parse arguments ''' + ParserObj = argparse.ArgumentParser() + ParserObj.add_argument("-t", "--tool_chain_tag", dest="tct", default="VS2017", + help="Set the toolchain used to compile the build tools") + args = ParserObj.parse_args() + self.tool_chain_tag = args.tct + + def GetWorkspaceRoot(self): + ''' Return the workspace root for initializing the SDE ''' + + # this is the bastools dir...not the traditional EDK2 workspace root + return os.path.dirname(os.path.abspath(__file__)) + + def GetActiveScopes(self): + ''' return tuple containing scopes that should be active for this process ''' + + # for now don't use scopes + return ('global',) + + def GetLoggingLevel(self, loggerType): + ''' Get the logging level for a given type (return Logging.Level) + base == lowest logging level supported + con == Screen logging + txt == plain text file logging + md == markdown file logging + ''' + if(loggerType == "con"): + return logging.ERROR + else: + return logging.DEBUG + + def GetLoggingFolderRelativeToRoot(self): + ''' Return a path to folder for log files ''' + return "BaseToolsBuild" + + def GetVerifyCheckRequired(self): + ''' Will call self_describing_environment.VerifyEnvironment if this returns True ''' + return True + + def GetLoggingFileName(self, loggerType): + ''' Get the logging file name for the type. + Return None if the logger shouldn't be created + + base == lowest logging level supported + con == Screen logging + txt == plain text file logging + md == markdown file logging + ''' + return "BASETOOLS_BUILD" + + def WritePathEnvFile(self, OutputDir): + ''' Write a PyTool path env file for future PyTool based edk2 builds''' + content = '''## +# Set shell variable EDK_TOOLS_BIN to this folder +# +# Autogenerated by Edk2ToolsBuild.py +# +# Copyright (c), Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "id": "You-Built-BaseTools", + "scope": "edk2-build", + "flags": ["set_shell_var", "set_path"], + "var_name": "EDK_TOOLS_BIN" +} +''' + with open(os.path.join(OutputDir, "basetoolsbin_path_env.yaml"), "w") as f: + f.write(content) + + def Go(self): + logging.info("Running Python version: " + str(sys.version_info)) + + (build_env, shell_env) = self_describing_environment.BootstrapEnvironment( + self.GetWorkspaceRoot(), self.GetActiveScopes()) + + # # Bind our current execution environment into the shell vars. + ph = os.path.dirname(sys.executable) + if " " in ph: + ph = '"' + ph + '"' + shell_env.set_shell_var("PYTHON_HOME", ph) + # PYTHON_COMMAND is required to be set for using edk2 python builds. + pc = sys.executable + if " " in pc: + pc = '"' + pc + '"' + shell_env.set_shell_var("PYTHON_COMMAND", pc) + + if self.tool_chain_tag.lower().startswith("vs"): + + # # Update environment with required VC vars. + interesting_keys = ["ExtensionSdkDir", "INCLUDE", "LIB"] + interesting_keys.extend( + ["LIBPATH", "Path", "UniversalCRTSdkDir", "UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath"]) + interesting_keys.extend( + ["WindowsSdkDir", "WindowsSdkVerBinPath", "WindowsSDKVersion", "VCToolsInstallDir"]) + vc_vars = QueryVcVariables( + interesting_keys, 'x86', vs_version=self.tool_chain_tag.lower()) + for key in vc_vars.keys(): + logging.debug(f"Var - {key} = {vc_vars[key]}") + if key.lower() == 'path': + shell_env.insert_path(vc_vars[key]) + else: + shell_env.set_shell_var(key, vc_vars[key]) + + self.OutputDir = os.path.join( + shell_env.get_shell_var("EDK_TOOLS_PATH"), "Bin", "Win32") + + # compiled tools need to be added to path because antlr is referenced + shell_env.insert_path(self.OutputDir) + + # Actually build the tools. + ret = RunCmd('nmake.exe', None, + workingdir=shell_env.get_shell_var("EDK_TOOLS_PATH")) + if ret != 0: + raise Exception("Failed to build.") + + self.WritePathEnvFile(self.OutputDir) + return ret + + elif self.tool_chain_tag.lower().startswith("gcc"): + ret = RunCmd("make", "-C .", workingdir=shell_env.get_shell_var("EDK_TOOLS_PATH")) + if ret != 0: + raise Exception("Failed to build.") + + self.OutputDir = os.path.join( + shell_env.get_shell_var("EDK_TOOLS_PATH"), "Source", "C", "bin") + + self.WritePathEnvFile(self.OutputDir) + return ret + + logging.critical("Tool Chain not supported") + return -1 + + +def main(): + Edk2ToolsBuild().Invoke() + + +if __name__ == "__main__": + main() diff --git a/BaseTools/Source/Python/basetool_tiano_python_path_env.yaml b/BaseTools/Source/Python/basetool_tiano_python_path_env.yaml new file mode 100644 index 00000000000..59369ccc657 --- /dev/null +++ b/BaseTools/Source/Python/basetool_tiano_python_path_env.yaml @@ -0,0 +1,11 @@ +## @file +# Add this folder to the pypath so modules can be easily +# loaded +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "flags": ["set_pypath"] +} diff --git a/BaseTools/basetools_calling_path_env.yaml b/BaseTools/basetools_calling_path_env.yaml new file mode 100644 index 00000000000..f33f6ea38b4 --- /dev/null +++ b/BaseTools/basetools_calling_path_env.yaml @@ -0,0 +1,11 @@ +## @file +# Set shell variable BASE_TOOL_PATH to this folder +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "flags": ["set_shell_var"], + "var_name": "BASE_TOOLS_PATH" +} diff --git a/BaseTools/basetools_path_env.yaml b/BaseTools/basetools_path_env.yaml new file mode 100644 index 00000000000..6bdddcd0960 --- /dev/null +++ b/BaseTools/basetools_path_env.yaml @@ -0,0 +1,11 @@ +## @file +# Set shell variable EDK_TOOL_PATH to this folder +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "flags": ["set_shell_var", "set_build_var"], + "var_name": "EDK_TOOLS_PATH" +} From de4ce46d6e5979f734b8f1063b9d3bdc0431bf21 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Mon, 7 Oct 2019 19:57:30 -0700 Subject: [PATCH 069/384] BaseTools: Add BaseTools plugins to support CI https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add the following plugins that are required to support EDK II Continuous Integration (CI) builds. These plugins are added to BaseTools because that support EDK II BaseTools features. * BuildToolsReportGenerator * LinuxGcc5ToolChain * WindowsResourceCompiler * WindowsVsToolChain Cc: Bob Feng Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .../BuildToolsReportGenerator.py | 69 ++++++++++ .../BuildToolsReportGenerator_plug_in.yaml | 12 ++ .../BuildToolsReport_Template.html | 126 ++++++++++++++++++ .../LinuxGcc5ToolChain/LinuxGcc5ToolChain.py | 85 ++++++++++++ .../LinuxGcc5ToolChain_plug_in.yaml | 12 ++ .../WindowsResourceCompiler/WinRcPath.py | 29 ++++ .../WinRcPath_plug_in.yaml | 13 ++ .../WindowsVsToolChain/WindowsVsToolChain.py | 126 ++++++++++++++++++ .../WindowsVsToolChain_plug_in.yaml | 11 ++ 9 files changed, 483 insertions(+) create mode 100644 BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator.py create mode 100644 BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator_plug_in.yaml create mode 100644 BaseTools/Plugin/BuildToolsReport/BuildToolsReport_Template.html create mode 100644 BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py create mode 100644 BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml create mode 100644 BaseTools/Plugin/WindowsResourceCompiler/WinRcPath.py create mode 100644 BaseTools/Plugin/WindowsResourceCompiler/WinRcPath_plug_in.yaml create mode 100644 BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py create mode 100644 BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain_plug_in.yaml diff --git a/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator.py b/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator.py new file mode 100644 index 00000000000..9f86b1c3588 --- /dev/null +++ b/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator.py @@ -0,0 +1,69 @@ +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import logging +import json + +try: + from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin + + class BuildToolsReportGenerator(IUefiBuildPlugin): + def do_report(self, thebuilder): + try: + from edk2toolext.environment import version_aggregator + except ImportError: + logging.critical("Loading BuildToolsReportGenerator failed, please update your Edk2-PyTool-Extensions") + return 0 + + OutputReport = os.path.join(thebuilder.env.GetValue("BUILD_OUTPUT_BASE"), "BUILD_TOOLS_REPORT") + OutputReport = os.path.normpath(OutputReport) + if not os.path.isdir(os.path.dirname(OutputReport)): + os.makedirs(os.path.dirname(OutputReport)) + + Report = BuildToolsReport() + Report.MakeReport(version_aggregator.GetVersionAggregator().GetAggregatedVersionInformation(), OutputReport=OutputReport) + + def do_pre_build(self, thebuilder): + self.do_report(thebuilder) + return 0 + + def do_post_build(self, thebuilder): + self.do_report(thebuilder) + return 0 + +except ImportError: + pass + + +class BuildToolsReport(object): + MY_FOLDER = os.path.dirname(os.path.realpath(__file__)) + VERSION = "1.00" + + def __init__(self): + pass + + def MakeReport(self, BuildTools, OutputReport="BuildToolsReport"): + logging.info("Writing BuildToolsReports to {0}".format(OutputReport)) + versions_list = [] + for key, value in BuildTools.items(): + versions_list.append(value) + versions_list = sorted(versions_list, key=lambda k: k['type']) + json_dict = {"modules": versions_list, + "PluginVersion": BuildToolsReport.VERSION} + + htmlfile = open(OutputReport + ".html", "w") + jsonfile = open(OutputReport + ".json", "w") + template = open(os.path.join(BuildToolsReport.MY_FOLDER, "BuildToolsReport_Template.html"), "r") + + for line in template.readlines(): + if "%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%" in line: + line = line.replace("%TO_BE_FILLED_IN_BY_PYTHON_SCRIPT%", json.dumps(json_dict)) + htmlfile.write(line) + + jsonfile.write(json.dumps(versions_list, indent=4)) + + jsonfile.close() + template.close() + htmlfile.close() diff --git a/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator_plug_in.yaml b/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator_plug_in.yaml new file mode 100644 index 00000000000..89335357297 --- /dev/null +++ b/BaseTools/Plugin/BuildToolsReport/BuildToolsReportGenerator_plug_in.yaml @@ -0,0 +1,12 @@ +## @file +# Build Plugin used to output html report of all versions collected +# during the build +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global", + "name": "Build Tools Report Generator", + "module": "BuildToolsReportGenerator" +} diff --git a/BaseTools/Plugin/BuildToolsReport/BuildToolsReport_Template.html b/BaseTools/Plugin/BuildToolsReport/BuildToolsReport_Template.html new file mode 100644 index 00000000000..8273fdee499 --- /dev/null +++ b/BaseTools/Plugin/BuildToolsReport/BuildToolsReport_Template.html @@ -0,0 +1,126 @@ + + + + + + Build Tools Report + + + + + + +
+

Build Tools Report

+ +
+
+ + + + + + + + + +
KeyValueType
+
+
+
+
+

+

+ Build Tools Report Template Version: 1.00
+ Build Tools Report Plugin Version:
+

+

License

+
+
+

+ Copyright (c) Microsoft Corporation.
+ + SPDX-License-Identifier: BSD-2-Clause-Patent + +

+
+
+
+

External Licenses

+
+
+
+
+
+ + + + + + + + + + + + diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py new file mode 100644 index 00000000000..c31641e9314 --- /dev/null +++ b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain.py @@ -0,0 +1,85 @@ +# @file LinuxGcc5ToolChain.py +# Plugin to configures paths for GCC5 ARM/AARCH64 Toolchain +## +# This plugin works in conjuncture with the tools_def +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import logging +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +from edk2toolext.environment import shell_environment + + +class LinuxGcc5ToolChain(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + return 0 + + def do_pre_build(self, thebuilder): + self.Logger = logging.getLogger("LinuxGcc5ToolChain") + + # + # GCC5 - The ARM and AARCH64 compilers need their paths set if available + if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "GCC5": + + # Start with AARACH64 compiler + ret = self._check_aarch64() + if ret != 0: + self.Logger.critical("Failed in check aarch64") + return ret + + # Check arm compiler + ret = self._check_arm() + if ret != 0: + self.Logger.critical("Failed in check arm") + return ret + + return 0 + + def _check_arm(self): + # check to see if full path already configured + if shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_PREFIX") is not None: + self.Logger.info("GCC5_ARM_PREFIX is already set.") + + else: + # now check for install dir. If set then set the Prefix + install_path = shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_INSTALL") + if install_path is None: + return 0 + + # make GCC5_ARM_PREFIX to align with tools_def.txt + prefix = os.path.join(install_path, "bin", "arm-linux-gnueabihf-") + shell_environment.GetEnvironment().set_shell_var("GCC5_ARM_PREFIX", prefix) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_ARM_PREFIX") + "gcc"): + self.Logger.error("Path for GCC5_ARM_PREFIX toolchain is invalid") + return -2 + + return 0 + + def _check_aarch64(self): + # check to see if full path already configured + if shell_environment.GetEnvironment().get_shell_var("GCC5_AARCH64_PREFIX") is not None: + self.Logger.info("GCC5_AARCH64_PREFIX is already set.") + + else: + # now check for install dir. If set then set the Prefix + install_path = shell_environment.GetEnvironment( + ).get_shell_var("GCC5_AARCH64_INSTALL") + if install_path is None: + return 0 + + # make GCC5_AARCH64_PREFIX to align with tools_def.txt + prefix = os.path.join(install_path, "bin", "aarch64-linux-gnu-") + shell_environment.GetEnvironment().set_shell_var("GCC5_AARCH64_PREFIX", prefix) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("GCC5_AARCH64_PREFIX") + "gcc"): + self.Logger.error( + "Path for GCC5_AARCH64_PREFIX toolchain is invalid") + return -2 + + return 0 diff --git a/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml new file mode 100644 index 00000000000..39c378a926a --- /dev/null +++ b/BaseTools/Plugin/LinuxGcc5ToolChain/LinuxGcc5ToolChain_plug_in.yaml @@ -0,0 +1,12 @@ +## @file +# Build Plugin used to set the path +# for the GCC5 ARM/AARCH64 downloaded compilers +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-nix", + "name": "Linux GCC5 Tool Chain Support", + "module": "LinuxGcc5ToolChain" +} diff --git a/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath.py b/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath.py new file mode 100644 index 00000000000..ec2f2d1298f --- /dev/null +++ b/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath.py @@ -0,0 +1,29 @@ +## @file WinRcPath.py +# Plugin to find Windows SDK Resource Compiler rc.exe +## +# This plugin works in conjuncture with the tools_def to support rc.exe +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +import edk2toollib.windows.locate_tools as locate_tools +from edk2toolext.environment import shell_environment +from edk2toolext.environment import version_aggregator + +class WinRcPath(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + return 0 + + def do_pre_build(self, thebuilder): + #get the locate tools module + path = locate_tools.FindToolInWinSdk("rc.exe") + if path is None: + thebuilder.logging.warning("Failed to find rc.exe") + else: + p = os.path.abspath(os.path.dirname(path)) + shell_environment.GetEnvironment().set_shell_var("WINSDK_PATH_FOR_RC_EXE", p) + version_aggregator.GetVersionAggregator().ReportVersion("WINSDK_PATH_FOR_RC_EXE", p, version_aggregator.VersionTypes.INFO) + return 0 diff --git a/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath_plug_in.yaml b/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath_plug_in.yaml new file mode 100644 index 00000000000..3aec35d863a --- /dev/null +++ b/BaseTools/Plugin/WindowsResourceCompiler/WinRcPath_plug_in.yaml @@ -0,0 +1,13 @@ +## @file +# Build Plugin used to set the path to rc.exe on windows. +# The plugin is able to use python to locate the tool as to avoid +# hard-coding the path +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-win", + "name": "Windows RC Path Support", + "module": "WinRcPath" +} diff --git a/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py new file mode 100644 index 00000000000..a8202e5992a --- /dev/null +++ b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain.py @@ -0,0 +1,126 @@ +## @file WindowsVsToolChain.py +# Plugin to configures paths for the VS2017 and VS2019 tool chain +## +# This plugin works in conjuncture with the tools_def +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import logging +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +import edk2toollib.windows.locate_tools as locate_tools +from edk2toollib.windows.locate_tools import FindWithVsWhere +from edk2toolext.environment import shell_environment +from edk2toolext.environment import version_aggregator + +class WindowsVsToolChain(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + return 0 + + def do_pre_build(self, thebuilder): + self.Logger = logging.getLogger("WindowsVsToolChain") + +# + # VS2017 - Follow VS2017 where there is potential for many versions of the tools. + # If a specific version is required then the user must set both env variables: + ## VS150INSTALLPATH: base install path on system to VC install dir. Here you will find the VC folder, etc + ## VS150TOOLVER: version number for the VC compiler tools + ## VS2017_PREFIX: path to MSVC compiler folder with trailing slash (can be used instead of two vars above) + if thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2017": + + # check to see if full path already configured + if shell_environment.GetEnvironment().get_shell_var("VS2017_PREFIX") != None: + self.Logger.info("VS2017_PREFIX is already set.") + + else: + install_path = self._get_vs_install_path("VS2017".lower(), "VS150INSTALLPATH") + vc_ver = self._get_vc_version(install_path, "VS150TOOLVER") + + if install_path is None or vc_ver is None: + self.Logger.error("Failed to configure environment for VS2017") + return -1 + + version_aggregator.GetVersionAggregator().ReportVersion( + "Visual Studio Install Path", install_path, version_aggregator.VersionTypes.INFO) + version_aggregator.GetVersionAggregator().ReportVersion( + "VC Version", vc_ver, version_aggregator.VersionTypes.TOOL) + + #make VS2017_PREFIX to align with tools_def.txt + prefix = os.path.join(install_path, "VC", "Tools", "MSVC", vc_ver) + prefix = prefix + os.path.sep + shell_environment.GetEnvironment().set_shell_var("VS2017_PREFIX", prefix) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("VS2017_PREFIX")): + self.Logger.error("Path for VS2017 toolchain is invalid") + return -2 + + # + # VS2019 - Follow VS2019 where there is potential for many versions of the tools. + # If a specific version is required then the user must set both env variables: + ## VS160INSTALLPATH: base install path on system to VC install dir. Here you will find the VC folder, etc + ## VS160TOOLVER: version number for the VC compiler tools + ## VS2019_PREFIX: path to MSVC compiler folder with trailing slash (can be used instead of two vars above) + elif thebuilder.env.GetValue("TOOL_CHAIN_TAG") == "VS2019": + + # check to see if full path already configured + if shell_environment.GetEnvironment().get_shell_var("VS2019_PREFIX") != None: + self.Logger.info("VS2019_PREFIX is already set.") + + else: + install_path = self._get_vs_install_path("VS2019".lower(), "VS160INSTALLPATH") + vc_ver = self._get_vc_version(install_path, "VS160TOOLVER") + + if install_path is None or vc_ver is None: + self.Logger.error("Failed to configure environment for VS2019") + return -1 + + version_aggregator.GetVersionAggregator().ReportVersion( + "Visual Studio Install Path", install_path, version_aggregator.VersionTypes.INFO) + version_aggregator.GetVersionAggregator().ReportVersion( + "VC Version", vc_ver, version_aggregator.VersionTypes.TOOL) + + #make VS2019_PREFIX to align with tools_def.txt + prefix = os.path.join(install_path, "VC", "Tools", "MSVC", vc_ver) + prefix = prefix + os.path.sep + shell_environment.GetEnvironment().set_shell_var("VS2019_PREFIX", prefix) + + # now confirm it exists + if not os.path.exists(shell_environment.GetEnvironment().get_shell_var("VS2019_PREFIX")): + self.Logger.error("Path for VS2019 toolchain is invalid") + return -2 + + return 0 + + def _get_vs_install_path(self, vs_version, varname): + # check if already specified + path = shell_environment.GetEnvironment().get_shell_var(varname) + if(path is None): + # Not specified...find latest + (rc, path) = FindWithVsWhere(vs_version=vs_version) + if rc == 0 and path is not None and os.path.exists(path): + self.Logger.debug("Found VS instance for %s", vs_version) + else: + self.Logger.error("Failed to find VS instance with VsWhere (%d)" % rc) + return path + + def _get_vc_version(self, path, varname): + # check if already specified + vc_ver = shell_environment.GetEnvironment().get_shell_var(varname) + if (path is None): + self.Logger.critical("Failed to find Visual Studio tools. Might need to check for VS install") + return vc_ver + if(vc_ver is None): + # Not specified...find latest + p2 = os.path.join(path, "VC", "Tools", "MSVC") + if not os.path.isdir(p2): + self.Logger.critical( + "Failed to find VC tools. Might need to check for VS install") + return vc_ver + vc_ver = os.listdir(p2)[-1].strip() # get last in list + self.Logger.debug("Found VC Tool version is %s" % vc_ver) + return vc_ver + + diff --git a/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain_plug_in.yaml b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain_plug_in.yaml new file mode 100644 index 00000000000..72b5c4a0926 --- /dev/null +++ b/BaseTools/Plugin/WindowsVsToolChain/WindowsVsToolChain_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# Build Plugin used to set the path to the visual studio tools chain +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "global-win", + "name": "Windows Visual Studio Tool Chain Support", + "module": "WindowsVsToolChain" +} From 9da7846c880ead64239f68157849e41a521a31fa Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Thu, 17 Oct 2019 21:40:58 -0700 Subject: [PATCH 070/384] .pytool/Plugin: Add CI plugins https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add .pytool directory to the edk2 repository with the following plugins. These plugins are in a top level directory because that can be used with all packages and platforms. * CharEncodingCheck * CompilerPlugin * DependencyCheck * DscCompleteCheck * GuidCheck * LibraryClassCheck * SpellCheck Cc: Sean Brogan Cc: Bret Barkelew Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .../CharEncodingCheck/CharEncodingCheck.py | 118 ++++++++ .../CharEncodingCheck_plug_in.yaml | 11 + .pytool/Plugin/CharEncodingCheck/Readme.md | 18 ++ .../Plugin/CompilerPlugin/CompilerPlugin.py | 102 +++++++ .../CompilerPlugin/Compiler_plug_in.yaml | 11 + .pytool/Plugin/CompilerPlugin/Readme.md | 17 ++ .../Plugin/DependencyCheck/DependencyCheck.py | 120 +++++++++ .../DependencyCheck_plug_in.yaml | 13 + .pytool/Plugin/DependencyCheck/Readme.md | 31 +++ .../DscCompleteCheck/DscCompleteCheck.py | 118 ++++++++ .../DscCompleteCheck_plug_in.yaml | 12 + .pytool/Plugin/DscCompleteCheck/Readme.md | 27 ++ .pytool/Plugin/GuidCheck/GuidCheck.py | 251 ++++++++++++++++++ .../Plugin/GuidCheck/GuidCheck_plug_in.yaml | 11 + .pytool/Plugin/GuidCheck/Readme.md | 80 ++++++ .../LibraryClassCheck/LibraryClassCheck.py | 153 +++++++++++ .../LibraryClassCheck_plug_in.yaml | 11 + .pytool/Plugin/LibraryClassCheck/Readme.md | 25 ++ .pytool/Plugin/SpellCheck/Readme.md | 127 +++++++++ .pytool/Plugin/SpellCheck/SpellCheck.py | 216 +++++++++++++++ .../Plugin/SpellCheck/SpellCheck_plug_in.yaml | 11 + .pytool/Plugin/SpellCheck/cspell.base.yaml | 165 ++++++++++++ 22 files changed, 1648 insertions(+) create mode 100644 .pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py create mode 100644 .pytool/Plugin/CharEncodingCheck/CharEncodingCheck_plug_in.yaml create mode 100644 .pytool/Plugin/CharEncodingCheck/Readme.md create mode 100644 .pytool/Plugin/CompilerPlugin/CompilerPlugin.py create mode 100644 .pytool/Plugin/CompilerPlugin/Compiler_plug_in.yaml create mode 100644 .pytool/Plugin/CompilerPlugin/Readme.md create mode 100644 .pytool/Plugin/DependencyCheck/DependencyCheck.py create mode 100644 .pytool/Plugin/DependencyCheck/DependencyCheck_plug_in.yaml create mode 100644 .pytool/Plugin/DependencyCheck/Readme.md create mode 100644 .pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py create mode 100644 .pytool/Plugin/DscCompleteCheck/DscCompleteCheck_plug_in.yaml create mode 100644 .pytool/Plugin/DscCompleteCheck/Readme.md create mode 100644 .pytool/Plugin/GuidCheck/GuidCheck.py create mode 100644 .pytool/Plugin/GuidCheck/GuidCheck_plug_in.yaml create mode 100644 .pytool/Plugin/GuidCheck/Readme.md create mode 100644 .pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py create mode 100644 .pytool/Plugin/LibraryClassCheck/LibraryClassCheck_plug_in.yaml create mode 100644 .pytool/Plugin/LibraryClassCheck/Readme.md create mode 100644 .pytool/Plugin/SpellCheck/Readme.md create mode 100644 .pytool/Plugin/SpellCheck/SpellCheck.py create mode 100644 .pytool/Plugin/SpellCheck/SpellCheck_plug_in.yaml create mode 100644 .pytool/Plugin/SpellCheck/cspell.base.yaml diff --git a/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py new file mode 100644 index 00000000000..02f25ab19fd --- /dev/null +++ b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py @@ -0,0 +1,118 @@ +# @file CharEncodingCheck.py +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +import os +import logging +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toolext.environment.var_dict import VarDict + +## +# map +## +EcodingMap = { + ".md": 'utf-8', + ".dsc": 'utf-8', + ".dec": 'utf-8', + ".c": 'utf-8', + ".h": 'utf-8', + ".asm": 'utf-8', + ".masm": 'utf-8', + ".nasm": 'utf-8', + ".s": 'utf-8', + ".inf": 'utf-8', + ".asl": 'utf-8', + ".uni": 'utf-8', + ".py": 'utf-8' +} + + +class CharEncodingCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that scans each file in the code tree and confirms the encoding is correct. + + Configuration options: + "CharEncodingCheck": { + "IgnoreFiles": [] + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + """ + return ("Check for valid file encoding for " + packagename, packagename + ".CharEncodingCheck") + + ## + # External function of plugin. This function is used to perform the task of the ci_build_plugin Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + overall_status = 0 + files_tested = 0 + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + + if abs_pkg_path is None: + tc.SetSkipped() + tc.LogStdError("No Package folder {0}".format(abs_pkg_path)) + return 0 + + for (ext, enc) in EcodingMap.items(): + files = self.WalkDirectoryForExtension([ext], abs_pkg_path) + files = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in files] # make edk2relative path so can process ignores + + if "IgnoreFiles" in pkgconfig: + for a in pkgconfig["IgnoreFiles"]: + a = a.replace(os.sep, "/") + try: + tc.LogStdOut("Ignoring File {0}".format(a)) + files.remove(a) + except: + tc.LogStdError("CharEncodingCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + logging.info("CharEncodingCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + + files = [Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(x) for x in files] + for a in files: + files_tested += 1 + if(self.TestEncodingOk(a, enc)): + logging.debug("File {0} Passed Encoding Check {1}".format(a, enc)) + else: + tc.LogStdError("Encoding Failure in {0}. Not {1}".format(a, enc)) + overall_status += 1 + + tc.LogStdOut("Tested Encoding on {0} files".format(files_tested)) + if overall_status is not 0: + tc.SetFailed("CharEncoding {0} Failed. Errors {1}".format(packagename, overall_status), "CHAR_ENCODING_CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status + + def TestEncodingOk(self, apath, encodingValue): + try: + with open(apath, "rb") as fobj: + fobj.read().decode(encodingValue) + except Exception as exp: + logging.error("Encoding failure: file: {0} type: {1}".format(apath, encodingValue)) + logging.debug("EXCEPTION: while processing {1} - {0}".format(exp, apath)) + return False + + return True diff --git a/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck_plug_in.yaml b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck_plug_in.yaml new file mode 100644 index 00000000000..f3ce0b3b3de --- /dev/null +++ b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# CiBuildPlugin used to check char encoding +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Char Encoding Check Test", + "module": "CharEncodingCheck" +} diff --git a/.pytool/Plugin/CharEncodingCheck/Readme.md b/.pytool/Plugin/CharEncodingCheck/Readme.md new file mode 100644 index 00000000000..47486e5c3cb --- /dev/null +++ b/.pytool/Plugin/CharEncodingCheck/Readme.md @@ -0,0 +1,18 @@ +# Character Encoding Check Plugin + +This CiBuildPlugin scans all the files in a package to make sure each file is +correctly encoded and all characters can be read. Improper encoding causes +tools to fail in some situations especially in different locals. + +## Configuration + +The plugin can be configured to ignore certain files. + +``` yaml +"CharEncodingCheck": { + "IgnoreFiles": [] +} +``` +### IgnoreFiles + +OPTIONAL List of file to ignore. diff --git a/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py new file mode 100644 index 00000000000..3b6f7c76988 --- /dev/null +++ b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py @@ -0,0 +1,102 @@ +# @file HostUnitTestCompiler_plugin.py +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import logging +import os +import re +from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toolext.environment.uefi_build import UefiBuilder +from edk2toolext import edk2_logging +from edk2toolext.environment.var_dict import VarDict + + +class CompilerPlugin(ICiBuildPlugin): + """ + A CiBuildPlugin that compiles the package dsc + from the package being tested. + + Configuration options: + "CompilerPlugin": { + "DscPath": "" + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + """ + target = environment.GetValue("TARGET") + return ("Compile " + packagename + " " + target, packagename + ".Compiler." + target) + + def RunsOnTargetList(self): + return ["DEBUG", "RELEASE"] + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + self._env = environment + + # Parse the config for required DscPath element + if "DscPath" not in pkgconfig: + tc.SetSkipped() + tc.LogStdError("DscPath not found in config file. Nothing to compile.") + return -1 + + AP = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + + APDSC = os.path.join(AP, pkgconfig["DscPath"].strip()) + AP_Path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(APDSC) + if AP is None or AP_Path is None or not os.path.isfile(APDSC): + tc.SetSkipped() + tc.LogStdError("Package Dsc not found.") + return -1 + + logging.info("Building {0}".format(AP_Path)) + self._env.SetValue("ACTIVE_PLATFORM", AP_Path, "Set in Compiler Plugin") + + # Parse DSC to check for SUPPORTED_ARCHITECTURES + dp = DscParser() + dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) + dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp.ParseFile(AP_Path) + if "SUPPORTED_ARCHITECTURES" in dp.LocalVars: + SUPPORTED_ARCHITECTURES = dp.LocalVars["SUPPORTED_ARCHITECTURES"].split('|') + TARGET_ARCHITECTURES = environment.GetValue("TARGET_ARCH").split(' ') + + # Skip if there is no intersection between SUPPORTED_ARCHITECTURES and TARGET_ARCHITECTURES + if len(set(SUPPORTED_ARCHITECTURES) & set(TARGET_ARCHITECTURES)) == 0: + tc.SetSkipped() + tc.LogStdError("No supported architecutres to build") + return -1 + + uefiBuilder = UefiBuilder() + # do all the steps + # WorkSpace, PackagesPath, PInHelper, PInManager + ret = uefiBuilder.Go(Edk2pathObj.WorkspacePath, os.pathsep.join(Edk2pathObj.PackagePathList), PLMHelper, PLM) + if ret != 0: # failure: + tc.SetFailed("Compile failed for {0}".format(packagename), "Compile_FAILED") + tc.LogStdError("{0} Compile failed with error code {1} ".format(AP_Path, ret)) + return 1 + + else: + tc.SetSuccess() + return 0 diff --git a/.pytool/Plugin/CompilerPlugin/Compiler_plug_in.yaml b/.pytool/Plugin/CompilerPlugin/Compiler_plug_in.yaml new file mode 100644 index 00000000000..4d7ca326c79 --- /dev/null +++ b/.pytool/Plugin/CompilerPlugin/Compiler_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# CiBuildPlugin used to compile each package +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Compiler Plugin", + "module": "CompilerPlugin" +} diff --git a/.pytool/Plugin/CompilerPlugin/Readme.md b/.pytool/Plugin/CompilerPlugin/Readme.md new file mode 100644 index 00000000000..44e6a2c8d97 --- /dev/null +++ b/.pytool/Plugin/CompilerPlugin/Readme.md @@ -0,0 +1,17 @@ +# Compiler Plugin + +This CiBuildPlugin compiles the package DSC from the package being tested. + +## Configuration + +The package relative path of the DSC file to build. + +``` yaml +"CompilerPlugin": { + "DscPath": "" +} +``` + +### DscPath + +Package relative path to the DSC file to build. diff --git a/.pytool/Plugin/DependencyCheck/DependencyCheck.py b/.pytool/Plugin/DependencyCheck/DependencyCheck.py new file mode 100644 index 00000000000..2c3d8baf698 --- /dev/null +++ b/.pytool/Plugin/DependencyCheck/DependencyCheck.py @@ -0,0 +1,120 @@ +# @file dependency_check.py +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import logging +import os +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser +from edk2toolext.environment.var_dict import VarDict + + +class DependencyCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that finds all modules (inf files) in a package and reviews the packages used + to confirm they are acceptable. This is to help enforce layering and identify improper + dependencies between packages. + + Configuration options: + "DependencyCheck": { + "AcceptableDependencies": [], # Package dec files that are allowed in all INFs. Example: MdePkg/MdePkg.dec + "AcceptableDependencies-": [], # OPTIONAL Package dependencies for INFs that are HOST_APPLICATION + "AcceptableDependencies-HOST_APPLICATION": [], # EXAMPLE Package dependencies for INFs that are HOST_APPLICATION + "IgnoreInf": [] # Ignore INF if found in filesystem + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + """ + return ("Test Package Dependencies for modules in " + packagename, packagename + ".DependencyCheck") + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + overall_status = 0 + + # Get current platform + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + + # Get INF Files + INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] # make edk2relative path so can compare with Ignore List + + # Remove ignored INFs + if "IgnoreInf" in pkgconfig: + for a in pkgconfig["IgnoreInf"]: + a = a.replace(os.sep, "/") ## convert path sep in case ignore list is bad. Can't change case + try: + INFFiles.remove(a) + tc.LogStdOut("IgnoreInf {0}".format(a)) + except: + logging.info("DependencyConfig.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + tc.LogStdError("DependencyConfig.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + + + # Get the AccpetableDependencies list + if "AcceptableDependencies" not in pkgconfig: + logging.info("DependencyCheck Skipped. No Acceptable Dependencies defined.") + tc.LogStdOut("DependencyCheck Skipped. No Acceptable Dependencies defined.") + tc.SetSkipped() + return -1 + + # Log dependencies + for k in pkgconfig.keys(): + if k.startswith("AcceptableDependencies"): + pkgstring = "\n".join(pkgconfig[k]) + if ("-" in k): + _, _, mod_type = k.partition("-") + tc.LogStdOut(f"Additional dependencies for MODULE_TYPE {mod_type}:\n {pkgstring}") + else: + tc.LogStdOut(f"Acceptable Dependencies:\n {pkgstring}") + + # For each INF file + for file in INFFiles: + ip = InfParser() + logging.debug("Parsing " + file) + ip.SetBaseAbsPath(Edk2pathObj.WorkspacePath).SetPackagePaths(Edk2pathObj.PackagePathList).ParseFile(file) + + if("MODULE_TYPE" not in ip.Dict): + tc.LogStdOut("Ignoring INF. Missing key for MODULE_TYPE {0}".format(file)) + continue + + mod_type = ip.Dict["MODULE_TYPE"].upper() + for p in ip.PackagesUsed: + if p not in pkgconfig["AcceptableDependencies"]: + # If not in the main acceptable dependencies list then check module specific + mod_specific_key = "AcceptableDependencies-" + mod_type + if mod_specific_key in pkgconfig and p in pkgconfig[mod_specific_key]: + continue + + logging.error("Dependency Check: Invalid Dependency INF: {0} depends on pkg {1}".format(file, p)) + tc.LogStdError("Dependency Check: Invalid Dependency INF: {0} depends on pkg {1}".format(file, p)) + overall_status += 1 + + # If XML object exists, add results + if overall_status is not 0: + tc.SetFailed("Failed with {0} errors".format(overall_status), "DEPENDENCYCHECK_FAILED") + else: + tc.SetSuccess() + return overall_status diff --git a/.pytool/Plugin/DependencyCheck/DependencyCheck_plug_in.yaml b/.pytool/Plugin/DependencyCheck/DependencyCheck_plug_in.yaml new file mode 100644 index 00000000000..c9834697162 --- /dev/null +++ b/.pytool/Plugin/DependencyCheck/DependencyCheck_plug_in.yaml @@ -0,0 +1,13 @@ +## @file +# CiBuildPlugin used to check all infs within a package +# to confirm the packagesdependency are on the configured list of acceptable +# dependencies. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Dependency Check Test", + "module": "DependencyCheck" +} diff --git a/.pytool/Plugin/DependencyCheck/Readme.md b/.pytool/Plugin/DependencyCheck/Readme.md new file mode 100644 index 00000000000..62612f69652 --- /dev/null +++ b/.pytool/Plugin/DependencyCheck/Readme.md @@ -0,0 +1,31 @@ +# Depdendency Check Plugin + +A CiBuildPlugin that finds all modules (inf files) in a package and reviews the +packages used to confirm they are acceptable. This is to help enforce layering +and identify improper dependencies between packages. + +## Configuration + +The plugin must be configured with the acceptabe package dependencies for the +package. + +``` yaml +"DependencyCheck": { + "AcceptableDependencies": [], + "AcceptableDependencies-": [], + "IgnoreInf": [] +} +``` + +### AcceptableDependencies + +Package dec files that are allowed in all INFs. Example: MdePkg/MdePkg.dec + +### AcceptableDependencies- + +OPTIONAL Package dependencies for INFs that have module type . +Example: AcceptableDependencies-HOST_APPLICATION. + +### IgnoreInf + +OPTIONAL list of INFs to ignore for this dependency check. diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py new file mode 100644 index 00000000000..e2485f57084 --- /dev/null +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py @@ -0,0 +1,118 @@ +# @file DscCompleteCheck.py +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import logging +import os +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser +from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser +from edk2toolext.environment.var_dict import VarDict + + +class DscCompleteCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that scans the package dsc file and confirms all modules (inf files) are + listed in the components sections. + + Configuration options: + "DscCompleteCheck": { + "DscPath": "" + "IgnoreInf": [] # Ignore INF if found in filesystem by not dsc + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + """ + return ("Check the " + packagename + " DSC for a being complete", packagename + ".DscCompleteCheck") + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - VarDict containing the shell environment Build Vars + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + overall_status = 0 + + # Parse the config for required DscPath element + if "DscPath" not in pkgconfig: + tc.SetSkipped() + tc.LogStdError("DscPath not found in config file. Nothing to check.") + return -1 + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) + wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) + + if abs_dsc_path is None or wsr_dsc_path is "" or not os.path.isfile(abs_dsc_path): + tc.SetSkipped() + tc.LogStdError("Package Dsc not found") + return 0 + + # Get INF Files + INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] # make edk2relative path so can compare with DSC + + # remove ignores + + if "IgnoreInf" in pkgconfig: + for a in pkgconfig["IgnoreInf"]: + a = a.replace(os.sep, "/") + try: + tc.LogStdOut("Ignoring INF {0}".format(a)) + INFFiles.remove(a) + except: + tc.LogStdError("DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + logging.info("DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + + # DSC Parser + dp = DscParser() + dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) + dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp.SetInputVars(environment.GetAllBuildKeyValues()) + dp.ParseFile(wsr_dsc_path) + + # Check if INF in component section + for INF in INFFiles: + if not any(INF.strip() in x for x in dp.ThreeMods) and \ + not any(INF.strip() in x for x in dp.SixMods) and \ + not any(INF.strip() in x for x in dp.OtherMods): + + infp = InfParser().SetBaseAbsPath(Edk2pathObj.WorkspacePath) + infp.SetPackagePaths(Edk2pathObj.PackagePathList) + infp.ParseFile(INF) + if("MODULE_TYPE" not in infp.Dict): + tc.LogStdOut("Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) + continue + + if(infp.Dict["MODULE_TYPE"] == "HOST_APPLICATION"): + tc.LogStdOut("Ignoring INF. Module type is HOST_APPLICATION {0}".format(INF)) + continue + + logging.critical(INF + " not in " + wsr_dsc_path) + tc.LogStdError("{0} not in {1}".format(INF, wsr_dsc_path)) + overall_status = overall_status + 1 + + # If XML object exists, add result + if overall_status is not 0: + tc.SetFailed("DscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck_plug_in.yaml b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck_plug_in.yaml new file mode 100644 index 00000000000..215b8b76a95 --- /dev/null +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck_plug_in.yaml @@ -0,0 +1,12 @@ +## @file +# CiBuildPlugin used to confirm all INFs are listed in +# the components section of package dsc +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Dsc Complete Check Test", + "module": "DscCompleteCheck" +} diff --git a/.pytool/Plugin/DscCompleteCheck/Readme.md b/.pytool/Plugin/DscCompleteCheck/Readme.md new file mode 100644 index 00000000000..eefbb9894d5 --- /dev/null +++ b/.pytool/Plugin/DscCompleteCheck/Readme.md @@ -0,0 +1,27 @@ +# Dsc Complete Check Plugin + +This CiBuildPlugin scans all INF files from a package and confirms they are +listed in the package level DSC file. The test considers it an error if any INF +does not appear in the `Components` section of the package-level DSC (indicating +that it would not be built if the package were built). This is critical because +much of the CI infrastructure assumes that all modules will be listed in the DSC +and compiled. + +## Configuration + +The plugin has a few configuration options to support the UEFI codebase. + +``` yaml +"DscCompleteCheck": { + "DscPath": "", # Path to dsc from root of package + "IgnoreInf": [] # Ignore INF if found in filesystem by not dsc + } +``` + +### DscPath + +Path to DSC to consider platform dsc + +### IgnoreInf + +Ignore error if Inf file is not listed in DSC file diff --git a/.pytool/Plugin/GuidCheck/GuidCheck.py b/.pytool/Plugin/GuidCheck/GuidCheck.py new file mode 100644 index 00000000000..f0b10beb1e8 --- /dev/null +++ b/.pytool/Plugin/GuidCheck/GuidCheck.py @@ -0,0 +1,251 @@ +# @file GuidCheck.py +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import logging +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.guid_list import GuidList +from edk2toolext.environment.var_dict import VarDict + + +class GuidCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that scans the code tree and looks for duplicate guids + from the package being tested. + + Configuration options: + "GuidCheck": { + "IgnoreGuidName": [], # provide in format guidname=guidvalue or just guidname + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] # Provide in format guidname=guidname=guidname... + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + """ + return ("Confirm GUIDs are unique in " + packagename, packagename + ".GuidCheck") + + def _FindConflictingGuidValues(self, guidlist: list) -> list: + """ Find all duplicate guids by guid value and report them as errors + """ + # Sort the list by guid + guidsorted = sorted( + guidlist, key=lambda x: x.guid.upper(), reverse=True) + + previous = None # Store previous entry for comparison + error = None + errors = [] + for index in range(len(guidsorted)): + i = guidsorted[index] + if(previous is not None): + if i.guid == previous.guid: # Error + if(error is None): + # Catch errors with more than 1 conflict + error = ErrorEntry("guid") + error.entries.append(previous) + errors.append(error) + error.entries.append(i) + else: + # no match. clear error + error = None + previous = i + return errors + + def _FindConflictingGuidNames(self, guidlist: list) -> list: + """ Find all duplicate guids by name and if they are not all + from inf files report them as errors. It is ok to have + BASE_NAME duplication. + + Is this useful? It would catch two same named guids in dec file + that resolve to different values. + """ + # Sort the list by guid + namesorted = sorted(guidlist, key=lambda x: x.name.upper()) + + previous = None # Store previous entry for comparison + error = None + errors = [] + for index in range(len(namesorted)): + i = namesorted[index] + if(previous is not None): + # If name matches + if i.name == previous.name: + if(error is None): + # Catch errors with more than 1 conflict + error = ErrorEntry("name") + error.entries.append(previous) + errors.append(error) + error.entries.append(i) + else: + # no match. clear error + error = None + previous = i + + # Loop thru and remove any errors where all files are infs as it is ok if + # they have the same inf base name. + for e in errors[:]: + if len( [en for en in e.entries if not en.absfilepath.lower().endswith(".inf")]) == 0: + errors.remove(e) + + return errors + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + Errors = [] + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath( + packagename) + + if abs_pkg_path is None: + tc.SetSkipped() + tc.LogStdError("No package {0}".format(packagename)) + return -1 + + All_Ignores = ["/Build", "/Conf"] + # Parse the config for other ignores + if "IgnoreFoldersAndFiles" in pkgconfig: + All_Ignores.extend(pkgconfig["IgnoreFoldersAndFiles"]) + + # Parse the workspace for all GUIDs + gs = GuidList.guidlist_from_filesystem( + Edk2pathObj.WorkspacePath, ignore_lines=All_Ignores) + + # Remove ignored guidvalue + if "IgnoreGuidValue" in pkgconfig: + for a in pkgconfig["IgnoreGuidValue"]: + try: + tc.LogStdOut("Ignoring Guid {0}".format(a.upper())) + for b in gs[:]: + if b.guid == a.upper(): + gs.remove(b) + except: + tc.LogStdError("GuidCheck.IgnoreGuid -> {0} not found. Invalid ignore guid".format(a.upper())) + logging.info("GuidCheck.IgnoreGuid -> {0} not found. Invalid ignore guid".format(a.upper())) + + # Remove ignored guidname + if "IgnoreGuidName" in pkgconfig: + for a in pkgconfig["IgnoreGuidName"]: + entry = a.split("=") + if(len(entry) > 2): + tc.LogStdError("GuidCheck.IgnoreGuidName -> {0} Invalid Format.".format(a)) + logging.info("GuidCheck.IgnoreGuidName -> {0} Invalid Format.".format(a)) + continue + try: + tc.LogStdOut("Ignoring Guid {0}".format(a)) + for b in gs[:]: + if b.name == entry[0]: + if(len(entry) == 1): + gs.remove(b) + elif(len(entry) == 2 and b.guid.upper() == entry[1].upper()): + gs.remove(b) + else: + c.LogStdError("GuidCheck.IgnoreGuidName -> {0} incomplete match. Invalid ignore guid".format(a)) + + except: + tc.LogStdError("GuidCheck.IgnoreGuidName -> {0} not found. Invalid ignore name".format(a)) + logging.info("GuidCheck.IgnoreGuidName -> {0} not found. Invalid ignore name".format(a)) + + # Find conflicting Guid Values + Errors.extend(self._FindConflictingGuidValues(gs)) + + # Check if there are expected duplicates and remove it from the error list + if "IgnoreDuplicates" in pkgconfig: + for a in pkgconfig["IgnoreDuplicates"]: + names = a.split("=") + if len(names) < 2: + tc.LogStdError("GuidCheck.IgnoreDuplicates -> {0} invalid format".format(a)) + logging.info("GuidCheck.IgnoreDuplicates -> {0} invalid format".format(a)) + continue + + for b in Errors[:]: + if b.type != "guid": + continue + ## Make a list of the names that are not in the names list. If there + ## are any in the list then this error should not be ignored. + t = [x for x in b.entries if x.name not in names] + if(len(t) == len(b.entries)): + ## did not apply to any entry + continue + elif(len(t) == 0): + ## full match - ignore duplicate + tc.LogStdOut("GuidCheck.IgnoreDuplicates -> {0}".format(a)) + Errors.remove(b) + elif(len(t) < len(b.entries)): + ## partial match + tc.LogStdOut("GuidCheck.IgnoreDuplicates -> {0} incomplete match".format(a)) + logging.info("GuidCheck.IgnoreDuplicates -> {0} incomplete match".format(a)) + else: + tc.LogStdOut("GuidCheck.IgnoreDuplicates -> {0} unknown error.".format(a)) + logging.info("GuidCheck.IgnoreDuplicates -> {0} unknown error".format(a)) + + + + # Find conflicting Guid Names + Errors.extend(self._FindConflictingGuidNames(gs)) + + # Log errors for anything within the package under test + for er in Errors[:]: + InMyPackage = False + for a in er.entries: + if abs_pkg_path in a.absfilepath: + InMyPackage = True + break + if(not InMyPackage): + Errors.remove(er) + else: + logging.error(str(er)) + tc.LogStdError(str(er)) + + # add result to test case + overall_status = len(Errors) + if overall_status is not 0: + tc.SetFailed("GuidCheck {0} Failed. Errors {1}".format( + packagename, overall_status), "CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status + + +class ErrorEntry(): + """ Custom/private class for reporting errors in the GuidList + """ + + def __init__(self, errortype): + self.type = errortype # 'guid' or 'name' depending on error type + self.entries = [] # GuidListEntry that are in error condition + + def __str__(self): + a = f"Error Duplicate {self.type}: " + if(self.type == "guid"): + a += f" {self.entries[0].guid}" + elif(self.type == "name"): + a += f" {self.entries[0].name}" + + a += f" ({len(self.entries)})\n" + + for e in self.entries: + a += "\t" + str(e) + "\n" + return a diff --git a/.pytool/Plugin/GuidCheck/GuidCheck_plug_in.yaml b/.pytool/Plugin/GuidCheck/GuidCheck_plug_in.yaml new file mode 100644 index 00000000000..b16f6c16b67 --- /dev/null +++ b/.pytool/Plugin/GuidCheck/GuidCheck_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# CiBuildPlugin used to check guid uniqueness +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Guid Check Test", + "module": "GuidCheck" +} diff --git a/.pytool/Plugin/GuidCheck/Readme.md b/.pytool/Plugin/GuidCheck/Readme.md new file mode 100644 index 00000000000..4e2c353cc44 --- /dev/null +++ b/.pytool/Plugin/GuidCheck/Readme.md @@ -0,0 +1,80 @@ +# Guid Check Plugin + +This CiBuildPlugin scans all the files in a code tree to find all the GUID +definitions. After collection it will then look for duplication in the package +under test. Uniqueness of all GUIDs are critical within the UEFI environment. +Duplication can cause numerous issues including locating the wrong data +structure, calling the wrong function, or decoding the wrong data members. + +Currently Scanned: + +* INF files are scanned for there Module guid +* DEC files are scanned for all of their Protocols, PPIs, and Guids as well as + the one package GUID. + +Any GUID value being equal to two names or even just defined in two files is +considered an error unless in the ignore list. + +Any GUID name that is found more than once is an error unless all occurrences +are Module GUIDs. Since the Module GUID is assigned to the Module name it is +common to have numerous versions of the same module named the same. + +## Configuration + +The plugin has numerous configuration options to support the UEFI codebase. + +``` yaml +"GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] + } +``` + +### IgnoreGuidName + +This list allows strings in two formats. + +* _GuidName_ + * This will remove any entry with this GuidName from the list of GUIDs + therefore ignoring any error associated with this name. +* _GuidName=GuidValue_ + * This will also ignore the GUID by name but only if the value equals the + GuidValue. + * GuidValue should be in registry format. + * This is the suggested format to use as it will limit the ignore to only the + defined case. + +### IgnoreGuidValue + +This list allows strings in guid registry format _GuidValue_. + +* This will remove any entry with this GuidValue from the list of GUIDs + therefore ignoring any error associated with this value. +* GuidValue must be in registry format xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx + +### IgnoreFoldersAndFiles + +This supports .gitignore file and folder matching strings including wildcards + +* Any folder or file ignored will not be parsed and therefore any GUID defined + will be ignored. +* The plugin will always ignores the following ["/Build", "/Conf"] + +### IgnoreDuplicates + +This supports strings in the format of _GuidName_=_GuidName_=_GuidName_ + +* For the error with the GuidNames to be ignored the list must match completely + with what is found during the code scan. + * For example if there are two GUIDs that are by design equal within the code + tree then it should be _GuidName_=_GuidName_ + * If instead there are three GUIDs then it must be + _GuidName_=_GuidName_=_GuidName_ +* This is the best ignore list to use because it is the most strict and will + catch new problems when new conflicts are introduced. +* There are numerous places in the UEFI specification in which two GUID names + are assigned the same value. These names should be set in this ignore list so + that they don't cause an error but any additional duplication would still be + caught. diff --git a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py new file mode 100644 index 00000000000..5dafcbc13f8 --- /dev/null +++ b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py @@ -0,0 +1,153 @@ +# @file LibraryClassCheck.py +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import logging +import os +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.parsers.dec_parser import DecParser +from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser +from edk2toolext.environment.var_dict import VarDict + + +class LibraryClassCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that scans the code tree and library classes for undeclared + files + + Configuration options: + "LibraryClassCheck": { + IgnoreHeaderFile: [], # Ignore a file found on disk + IgnoreLibraryClass: [] # Ignore a declaration found in dec file + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + """ + return ("Check library class declarations in " + packagename, packagename + ".LibraryClassCheck") + + def __GetPkgDec(self, rootpath): + try: + allEntries = os.listdir(rootpath) + for entry in allEntries: + if entry.lower().endswith(".dec"): + return(os.path.join(rootpath, entry)) + except Exception: + logging.error("Unable to find DEC for package:{0}".format(rootpath)) + + return None + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + overall_status = 0 + LibraryClassIgnore = [] + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + abs_dec_path = self.__GetPkgDec(abs_pkg_path) + wsr_dec_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dec_path) + + if abs_dec_path is None or wsr_dec_path is "" or not os.path.isfile(abs_dec_path): + tc.SetSkipped() + tc.LogStdError("No DEC file {0} in package {1}".format(abs_dec_path, abs_pkg_path)) + return -1 + + # Get all include folders + dec = DecParser() + dec.SetBaseAbsPath(Edk2pathObj.WorkspacePath).SetPackagePaths(Edk2pathObj.PackagePathList) + dec.ParseFile(wsr_dec_path) + + AllHeaderFiles = [] + + for includepath in dec.IncludePaths: + ## Get all header files in the library folder + AbsLibraryIncludePath = os.path.join(abs_pkg_path, includepath, "Library") + if(not os.path.isdir(AbsLibraryIncludePath)): + continue + + hfiles = self.WalkDirectoryForExtension([".h"], AbsLibraryIncludePath) + hfiles = [os.path.relpath(x,abs_pkg_path) for x in hfiles] # make package root relative path + hfiles = [x.replace("\\", "/") for x in hfiles] # make package relative path + + AllHeaderFiles.extend(hfiles) + + if len(AllHeaderFiles) == 0: + tc.SetSkipped() + tc.LogStdError(f"No Library include folder in any Include path") + return -1 + + # Remove ignored paths + if "IgnoreHeaderFile" in pkgconfig: + for a in pkgconfig["IgnoreHeaderFile"]: + try: + tc.LogStdOut("Ignoring Library Header File {0}".format(a)) + AllHeaderFiles.remove(a) + except: + tc.LogStdError("LibraryClassCheck.IgnoreHeaderFile -> {0} not found. Invalid Header File".format(a)) + logging.info("LibraryClassCheck.IgnoreHeaderFile -> {0} not found. Invalid Header File".format(a)) + + if "IgnoreLibraryClass" in pkgconfig: + LibraryClassIgnore = pkgconfig["IgnoreLibraryClass"] + + + ## Attempt to find library classes + for lcd in dec.LibraryClasses: + ## Check for correct file path separator + if "\\" in lcd.path: + tc.LogStdError("LibraryClassCheck.DecFilePathSeparator -> {0} invalid.".format(lcd.path)) + logging.error("LibraryClassCheck.DecFilePathSeparator -> {0} invalid.".format(lcd.path)) + overall_status += 1 + continue + + if lcd.name in LibraryClassIgnore: + tc.LogStdOut("Ignoring Library Class Name {0}".format(lcd.name)) + LibraryClassIgnore.remove(lcd.name) + continue + + logging.debug(f"Looking for Library Class {lcd.path}") + try: + AllHeaderFiles.remove(lcd.path) + + except ValueError: + tc.LogStdError(f"Library {lcd.name} with path {lcd.path} not found in package filesystem") + logging.error(f"Library {lcd.name} with path {lcd.path} not found in package filesystem") + overall_status += 1 + + ## any remaining AllHeaderFiles are not described in DEC + for h in AllHeaderFiles: + tc.LogStdError(f"Library Header File {h} not declared in package DEC {wsr_dec_path}") + logging.error(f"Library Header File {h} not declared in package DEC {wsr_dec_path}") + overall_status += 1 + + ## Warn about any invalid library class names in the ignore list + for r in LibraryClassIgnore: + tc.LogStdError("LibraryClassCheck.IgnoreLibraryClass -> {0} not found. Library Class not found".format(r)) + logging.info("LibraryClassCheck.IgnoreLibraryClass -> {0} not found. Library Class not found".format(r)) + + + # If XML object exists, add result + if overall_status is not 0: + tc.SetFailed("LibraryClassCheck {0} Failed. Errors {1}".format(wsr_dec_path, overall_status), "CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status diff --git a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck_plug_in.yaml b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck_plug_in.yaml new file mode 100644 index 00000000000..f90eec32ff6 --- /dev/null +++ b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# CiBuildPlugin used to check that all library classes are declared correctly in dec file +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Library Class Check Test", + "module": "LibraryClassCheck" +} diff --git a/.pytool/Plugin/LibraryClassCheck/Readme.md b/.pytool/Plugin/LibraryClassCheck/Readme.md new file mode 100644 index 00000000000..7fa2b202f24 --- /dev/null +++ b/.pytool/Plugin/LibraryClassCheck/Readme.md @@ -0,0 +1,25 @@ +# Library Class Check Plugin + +This CiBuildPlugin scans at all library header files found in the `Library` +folders in all of the package's declared include directories and ensures that +all files have a matching LibraryClass declaration in the DEC file for the +package. Any missing declarations will cause a failure. + +## Configuration + +The plugin has a few configuration options to support the UEFI codebase. + +``` yaml +"LibraryClassCheck": { + IgnoreHeaderFile: [], # Ignore a file found on disk + IgnoreLibraryClass: [] # Ignore a declaration found in dec file +} +``` + +### IgnoreHeaderFile + +Ignore a file found on disk + +### IgnoreLibraryClass + +Ignore a declaration found in dec file diff --git a/.pytool/Plugin/SpellCheck/Readme.md b/.pytool/Plugin/SpellCheck/Readme.md new file mode 100644 index 00000000000..394bb8effc8 --- /dev/null +++ b/.pytool/Plugin/SpellCheck/Readme.md @@ -0,0 +1,127 @@ +# Spell Check Plugin + +This CiBuildPlugin scans all the files in a given package and checks for +spelling errors. + +This plugin requires NodeJs and cspell. If the plugin doesn't find its required +tools then it will mark the test as skipped. + +* NodeJS: https://nodejs.org/en/ +* cspell: https://www.npmjs.com/package/cspell + * Src and doc available: https://github.com/streetsidesoftware/cspell + +## Configuration + +The plugin has a few configuration options to support the UEFI codebase. + +``` yaml + "SpellCheck": { + "AuditOnly": False, # If True, log all errors and then mark as skipped + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +``` + +### AuditOnly + +Boolean - Default is False. +If True run the test in an Audit only mode which will log all errors but instead +of failing the build it will set the test as skipped. This allows visibility +into the failures without breaking the build. + +### IgnoreFiles + +This supports .gitignore file and folder matching strings including wildcards + +* All files will be parsed regardless but then any spelling errors found within + ignored files will not be reported as an error. +* Errors in ignored files will still be output to the test results as + informational comments. + +### ExtendWords + +This list allows words to be added to the dictionary for the spell checker when +this package is tested. These follow the rules of the cspell config words field. + +### IgnoreStandardPaths + +This plugin by default will check the below standard paths. If the package +would like to ignore any of them list that here. + +```python +[ +# C source +"*.c", +"*.h", + +# Assembly files +"*.nasm", +"*.asm", +"*.masm", +"*.s", + +# ACPI source language +"*.asl", + +# Edk2 build files +"*.dsc", "*.dec", "*.fdf", "*.inf", + +# Documentation files +"*.md", "*.txt" +] +``` + +### AdditionalIncludePaths + +If the package would to add additional path patterns to be included in +spellchecking they can be defined here. + +## Other configuration + +In the cspell.base.json there are numerous other settings configured. There is +no support to override these on a per package basis but future features could +make this available. One interesting configuration option is `minWordLength`. +Currently it is set to _5_ which means all 2,3, and 4 letter words will be +ignored. This helps minimize the number of technical acronyms, register names, +and other UEFI specific values that must be ignored. + +## False positives + +The cspell dictionary is not perfect and there are cases where technical words +or acronyms are not found in the dictionary. There are three ways to resolve +false positives and the choice for which method should be based on how broadly +the word should be accepted. + +### CSpell Base Config file + +If the change should apply to all UEFI code and documentation then it should be +added to the base config file `words` section. The base config file is adjacent +to this file and titled `cspell.base.json`. This is a list of accepted words +for all spell checking operations on all packages. + +### Package Config + +In the package `*.ci.yaml` file there is a `SpellCheck` config section. This +section allows files to be ignored as well as words that should be considered +valid for all files within this package. Add the desired words to the +"ExtendedWords" member. + +### In-line File + +CSpell supports numerous methods to annotate your files to ignore words, +sections, etc. This can be found in CSpell documentation. Suggestion here is +to use a c-style comment at the top of the file to add words that should be +ignored just for this file. Obviously this has the highest maintenance cost so +it should only be used for file unique words. + +``` c +// spell-checker:ignore unenroll, word2, word3 +``` + +or + +```ini +# spell-checker:ignore unenroll, word2, word3 +``` diff --git a/.pytool/Plugin/SpellCheck/SpellCheck.py b/.pytool/Plugin/SpellCheck/SpellCheck.py new file mode 100644 index 00000000000..43365441b91 --- /dev/null +++ b/.pytool/Plugin/SpellCheck/SpellCheck.py @@ -0,0 +1,216 @@ +# @file SpellCheck.py +# +# An edk2-pytool based plugin wrapper for cspell +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import logging +import json +import yaml +from io import StringIO +import os +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.utility_functions import RunCmd +from edk2toolext.environment.var_dict import VarDict +from edk2toollib.gitignore_parser import parse_gitignore_lines +from edk2toolext.environment import version_aggregator + + +class SpellCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that uses the cspell node module to scan the files + from the package being tested for spelling errors. The plugin contains + the base cspell.json file then thru the configuration options other settings + can be changed or extended. + + Configuration options: + "SpellCheck": { + "AuditOnly": False, # Don't fail the build if there are errors. Just log them + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } + """ + + # + # A package can remove any of these using IgnoreStandardPaths + # + STANDARD_PLUGIN_DEFINED_PATHS = ["*.c", "*.h", + "*.nasm", "*.asm", "*.masm", "*.s", + "*.asl", + "*.dsc", "*.dec", "*.fdf", "*.inf", + "*.md", "*.txt" + ] + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + """ + return ("Spell check files in " + packagename, packagename + ".SpellCheck") + + ## + # External function of plugin. This function is used to perform the task of the CiBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + Errors = [] + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath( + packagename) + + if abs_pkg_path is None: + tc.SetSkipped() + tc.LogStdError("No package {0}".format(packagename)) + return -1 + + # check for node + return_buffer = StringIO() + ret = RunCmd("node", "--version", outstream=return_buffer) + if (ret != 0): + tc.SetSkipped() + tc.LogStdError("NodeJs not installed. Test can't run") + logging.warning("NodeJs not installed. Test can't run") + return -1 + node_version = return_buffer.getvalue().strip() # format vXX.XX.XX + tc.LogStdOut(f"Node version: {node_version}") + version_aggregator.GetVersionAggregator().ReportVersion( + "NodeJs", node_version, version_aggregator.VersionTypes.INFO) + + # Check for cspell + return_buffer = StringIO() + ret = RunCmd("cspell", "--version", outstream=return_buffer) + if (ret != 0): + tc.SetSkipped() + tc.LogStdError("cspell not installed. Test can't run") + logging.warning("cspell not installed. Test can't run") + return -1 + cspell_version = return_buffer.getvalue().strip() # format XX.XX.XX + tc.LogStdOut(f"CSpell version: {cspell_version}") + version_aggregator.GetVersionAggregator().ReportVersion( + "CSpell", cspell_version, version_aggregator.VersionTypes.INFO) + + package_relative_paths_to_spell_check = SpellCheck.STANDARD_PLUGIN_DEFINED_PATHS + + # + # Allow the ci.yaml to remove any of the above standard paths + # + if("IgnoreStandardPaths" in pkgconfig): + for a in pkgconfig["IgnoreStandardPaths"]: + if(a in package_relative_paths_to_spell_check): + tc.LogStdOut( + f"ignoring standard path due to ci.yaml ignore: {a}") + package_relative_paths_to_spell_check.remove(a) + else: + tc.LogStdOut(f"Invalid IgnoreStandardPaths value: {a}") + + # + # check for any additional include paths defined by package config + # + if("AdditionalIncludePaths" in pkgconfig): + package_relative_paths_to_spell_check.extend( + pkgconfig["AdditionalIncludePaths"]) + + # + # Make the path string for cspell to check + # + relpath = os.path.relpath(abs_pkg_path) + cpsell_paths = " ".join( + [f"{relpath}/**/{x}" for x in package_relative_paths_to_spell_check]) + + # Make the config file + config_file_path = os.path.join( + Edk2pathObj.WorkspacePath, "Build", packagename, "cspell_actual_config.json") + mydir = os.path.dirname(os.path.abspath(__file__)) + # load as yaml so it can have comments + base = os.path.join(mydir, "cspell.base.yaml") + with open(base, "r") as i: + config = yaml.safe_load(i) + + if("ExtendWords" in pkgconfig): + config["words"].extend(pkgconfig["ExtendWords"]) + with open(config_file_path, "w") as o: + json.dump(config, o) # output as json so compat with cspell + + All_Ignores = [] + # Parse the config for other ignores + if "IgnoreFiles" in pkgconfig: + All_Ignores.extend(pkgconfig["IgnoreFiles"]) + + # spell check all the files + ignore = parse_gitignore_lines(All_Ignores, os.path.join( + abs_pkg_path, "nofile.txt"), abs_pkg_path) + + # result is a list of strings like this + # C:\src\sp-edk2\edk2\FmpDevicePkg\FmpDevicePkg.dec:53:9 - Unknown word (Capule) + EasyFix = [] + results = self._check_spelling(cpsell_paths, config_file_path) + for r in results: + path, _, word = r.partition(" - Unknown word ") + if len(word) == 0: + # didn't find pattern + continue + + pathinfo = path.rsplit(":", 2) # remove the line no info + if(ignore(pathinfo[0])): # check against ignore list + tc.LogStdOut(f"ignoring error due to ci.yaml ignore: {r}") + continue + + # real error + EasyFix.append(word.strip().strip("()")) + Errors.append(r) + + # Log all errors tc StdError + for l in Errors: + tc.LogStdError(l.strip()) + + # Helper - Log the syntax needed to add these words to dictionary + if len(EasyFix) > 0: + EasyFix = sorted(set(a.lower() for a in EasyFix)) + tc.LogStdOut("\n Easy fix:") + OneString = "If these are not errors add this to your ci.yaml file.\n" + OneString += '"SpellCheck": {\n "ExtendWords": [' + for a in EasyFix: + tc.LogStdOut(f'\n"{a}",') + OneString += f'\n "{a}",' + logging.info(OneString.rstrip(",") + '\n ]\n}') + + # add result to test case + overall_status = len(Errors) + if overall_status != 0: + if "AuditOnly" in pkgconfig and pkgconfig["AuditOnly"]: + # set as skipped if AuditOnly + tc.SetSkipped() + return -1 + else: + tc.SetFailed("SpellCheck {0} Failed. Errors {1}".format( + packagename, overall_status), "CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status + + def _check_spelling(self, abs_file_to_check: str, abs_config_file_to_use: str) -> []: + output = StringIO() + ret = RunCmd( + "cspell", f"--config {abs_config_file_to_use} {abs_file_to_check}", outstream=output) + if ret == 0: + return [] + else: + return output.getvalue().strip().splitlines() diff --git a/.pytool/Plugin/SpellCheck/SpellCheck_plug_in.yaml b/.pytool/Plugin/SpellCheck/SpellCheck_plug_in.yaml new file mode 100644 index 00000000000..d438199f609 --- /dev/null +++ b/.pytool/Plugin/SpellCheck/SpellCheck_plug_in.yaml @@ -0,0 +1,11 @@ +## @file +# CiBuildPlugin used to check spelling +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "cibuild", + "name": "Spell Check Test", + "module": "SpellCheck" +} diff --git a/.pytool/Plugin/SpellCheck/cspell.base.yaml b/.pytool/Plugin/SpellCheck/cspell.base.yaml new file mode 100644 index 00000000000..53000fc3814 --- /dev/null +++ b/.pytool/Plugin/SpellCheck/cspell.base.yaml @@ -0,0 +1,165 @@ +## @file +# CSpell configuration +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "version": "0.1", + "language": "en", + "dictionaries": [ + "companies ", + "softwareTerms", + "python", + "cpp" + ], + "ignorePaths": [ + "*.pdb", + "**/*_extdep/**", + "*.pdf", + "*.exe", + "*.jpg" + ], + "minWordLength": 5, + "allowCompoundWords": false, + "ignoreWords": [ + "muchange" + ], + "words": [ + "MTRRs", + "Microarchitecture", + "Goldmont", + "cpuid", + "mwait", + "cstate", + "smram", + "scrtm", + "smbus", + "selftest", + "socket", + "MMRAM", + "qword", + "ENDBR", + "SMBASE", + "FXSAVE", + "FXRSTOR", + "RDRAND", + "IOAPIC", + "ATAPI", + "movsb", + "iretw", + "XENSTORE", + "cdrom", + "oprom", + "oproms", + "varstore", + "EKU", + "ascii", + "nmake", + "NVDIMM", + "nasmb", + "Mtftp", + "Hypercall", + "hypercalls", + "IOMMU", + "QEMU", + "qemus", + "OVMF", + "tiano", + "tianocore", + "edkii", + "coreboot", + "uefipayload", + "bootloader", + "bootloaders", + "mdepkg", + "skuid", + "dxefv", + "toolchain", + "libraryclass", + "preboot", + "pythonpath", + "cygpath", + "nuget", + "basetools", + "prepi", + "OPTEE", + "stringid", + "peims", + "memmap", + "guids", + "uuids", + "smbios", + "certdb", + "certdbv", + "EfiSigList", + "depex", + "IHANDLE", + "Virtio", + "Mbytes", + "Citrix", + "initrd", + "semihost", + "Semihosting", + "Trustzone", + "Fastboot", + "framebuffer", + "genfw", + "TTYTERM", + "miniport", + "LFENCE", + "PCANSI", + "submodule", + "submodules", + "brotli", + "PCCTS", + "softfloat", + "whitepaper", + "ACPICA", + "plugfest", + "bringup", + "formset", #VFR + "ideqvallist", + "numberof", + "oneof", + "endformset", + "endnumeric", + "endoneof", + "disableif", + "guidid", + "classguid", + "efivarstore", + "formsetguid", + "formid", + "suppressif", + "grayoutif", + "ideqval", + "endform", + "endcheckbox", + "questionid", + "questionref", + "enddate", + "endstring", + "guidop", + "endguidop", + "langdef", + "dynamicex", + "tokenspace", + "tokenguid", + "pcd's", #seems like cspell bug + "peim's", + "autogen", + "Disasm", + "Torito", + "SRIOV", + "MRIOV", + "UARTs", + "Consplitter", # common module in UEFI + "FIFOs", + "ACPINVS", + "Endof", # due to of not being uppercase + "bootability", + "Sdhci", + "inmodule", + ] +} From f98a44541fb8b220cc2511ca0772707084898eed Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:19:09 -0700 Subject: [PATCH 071/384] CryptoPkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Jian J Wang Cc: Xiaoyu Lu Signed-off-by: Kinney Reviewed-by: Jian J Wang Reviewed-by: Liming Gao --- CryptoPkg/CryptoPkg.ci.yaml | 47 +++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 CryptoPkg/CryptoPkg.ci.yaml diff --git a/CryptoPkg/CryptoPkg.ci.yaml b/CryptoPkg/CryptoPkg.ci.yaml new file mode 100644 index 00000000000..f54ebfb22e7 --- /dev/null +++ b/CryptoPkg/CryptoPkg.ci.yaml @@ -0,0 +1,47 @@ +## @file +# CI configuration for CryptoPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "CryptoPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "CryptoPkg/CryptoPkg.dec", + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "CryptoPkg.dsc", + "IgnoreInf": [] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "skip": True, + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 6d807aef57f7d41499175aa5bfbfc7c242983502 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:19:28 -0700 Subject: [PATCH 072/384] FatPkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Ray Ni Signed-off-by: Michael D Kinney Acked-by: Ray Ni Reviewed-by: Liming Gao --- FatPkg/FatPkg.ci.yaml | 50 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 FatPkg/FatPkg.ci.yaml diff --git a/FatPkg/FatPkg.ci.yaml b/FatPkg/FatPkg.ci.yaml new file mode 100644 index 00000000000..8b0fb1d4fcd --- /dev/null +++ b/FatPkg/FatPkg.ci.yaml @@ -0,0 +1,50 @@ +## @file +# CI configuration for FatPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "FatPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "IgnoreInf": [], + "DscPath": "FatPkg.dsc" + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + "SpellCheck": { + "ExtendWords": [ + "ELTORITO", + "FHAND", + "IFILE", + "OFILE", + "FDISKed", + "Lfnbuffer", + "FFFFFFFFL", + "CDVOL", + "DMDEPKG" + ] + } +} From 8bc648fe6c10c1f94a7ee73bd38b65a0122de12f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:19:46 -0700 Subject: [PATCH 073/384] FmpDevicePkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Use BaseCryptLibNull for package CI builds to reduce package build times. Enabled with CONTINUOUS_INTEGRATION in YAML files. By default CONTINUOUS_INTEGRATION is not defined, and the original lib mappings are preserved. Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- FmpDevicePkg/FmpDevicePkg.ci.yaml | 43 +++++++++++++++++++++++++++++++ FmpDevicePkg/FmpDevicePkg.dsc | 6 ++++- 2 files changed, 48 insertions(+), 1 deletion(-) create mode 100644 FmpDevicePkg/FmpDevicePkg.ci.yaml diff --git a/FmpDevicePkg/FmpDevicePkg.ci.yaml b/FmpDevicePkg/FmpDevicePkg.ci.yaml new file mode 100644 index 00000000000..c17b355d428 --- /dev/null +++ b/FmpDevicePkg/FmpDevicePkg.ci.yaml @@ -0,0 +1,43 @@ +## @file +# CI configuration for FmpDevicePkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "FmpDevicePkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "FmpDevicePkg/FmpDevicePkg.dec", + "CryptoPkg/CryptoPkg.dec" + ], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "FmpDevicePkg.dsc", + "IgnoreInf": [] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + "SpellCheck": { + "ExtendWords": [ + "FMPSTATE", + ] + }, + "Defines": { + "BLD_*_CONTINUOUS_INTEGRATION": "TRUE", + } +} diff --git a/FmpDevicePkg/FmpDevicePkg.dsc b/FmpDevicePkg/FmpDevicePkg.dsc index 67b5aa7a327..f4093d3837c 100644 --- a/FmpDevicePkg/FmpDevicePkg.dsc +++ b/FmpDevicePkg/FmpDevicePkg.dsc @@ -48,9 +48,13 @@ DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif FmpAuthenticationLib|SecurityPkg/Library/FmpAuthenticationLibPkcs7/FmpAuthenticationLibPkcs7.inf CapsuleUpdatePolicyLib|FmpDevicePkg/Library/CapsuleUpdatePolicyLibNull/CapsuleUpdatePolicyLibNull.inf FmpPayloadHeaderLib|FmpDevicePkg/Library/FmpPayloadHeaderLibV1/FmpPayloadHeaderLibV1.inf From e4612477b96b459f8d96b3e507a05c897c815fb0 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:20:04 -0700 Subject: [PATCH 074/384] MdeModulePkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael D Kinney Reviewed-by: Hao A Wu Reviewed-by: Liming Gao --- MdeModulePkg/MdeModulePkg.ci.yaml | 80 +++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 MdeModulePkg/MdeModulePkg.ci.yaml diff --git a/MdeModulePkg/MdeModulePkg.ci.yaml b/MdeModulePkg/MdeModulePkg.ci.yaml new file mode 100644 index 00000000000..0bf149f205e --- /dev/null +++ b/MdeModulePkg/MdeModulePkg.ci.yaml @@ -0,0 +1,80 @@ +## @file +# CI configuration for MdeModulePkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined ci/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "MdeModulePkg.dsc" + }, + + ## options defined ci/Plugin/CharEncodingCheck + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined ci/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "StandaloneMmPkg/StandaloneMmPkg.dec", + "ArmPkg/ArmPkg.dec" # this should be fixed by promoting an abstraction + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined ci/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [], + "DscPath": "MdeModulePkg.dsc" + }, + + ## options defined ci/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": ["00000000-0000-0000-0000-000000000000"], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [ + "gEdkiiFormBrowserExProtocolGuid=gEfiFormBrowserExProtocolGuid", + "gEfiPeiMmAccessPpiGuid=gPeiSmmAccessPpiGuid", + "gPeiSmmControlPpiGuid=gEfiPeiMmControlPpiGuid", + ] + }, + + ## options defined ci/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreStandardPaths": [ # Standard Plugin defined paths that should be ignore + "*.c", "*.asm", "*.h", "*.nasm", "*.s", "*.asl", "*.inf" + ], + "IgnoreFiles": [ # use gitignore syntax to ignore errors in matching files + "Library/LzmaCustomDecompressLib/Sdk/DOC/*" + ], + "ExtendWords": [ # words to extend to the dictionary for this package + "LIGHTGRAY", + "DARKGRAY", + "LIGHTBLUE", + "LIGHTGREEN", + "LIGHTCYAN", + "LIGHTRED", + "LIGHTMAGENTA", + "FVMAIN", + "VARCHECKPCD", + "Getxx", + "lzturbo" + ], + "AdditionalIncludePaths": [] # Additional paths to spell check relative to package root (wildcards supported) + } +} From 3059a38d5fc649f56a691cd11826a6957985fa4c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:20:17 -0700 Subject: [PATCH 075/384] MdePkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- MdePkg/MdePkg.ci.yaml | 90 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 90 insertions(+) create mode 100644 MdePkg/MdePkg.ci.yaml diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml new file mode 100644 index 00000000000..65c4ec3becc --- /dev/null +++ b/MdePkg/MdePkg.ci.yaml @@ -0,0 +1,90 @@ +## @file +# CI configuration for MdePkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + ## options defined ci/Plugin/CompilerPlugin + "CompilerPlugin": { + "DscPath": "MdePkg.dsc" + }, + + ## options defined ci/Plugin/CharEncodingCheck +"CharEncodingCheck": { + "IgnoreFiles": [] + }, + + ## options defined ci/Plugin/DependencyCheck + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + + ## options defined ci/Plugin/DscCompleteCheck + "DscCompleteCheck": { + "IgnoreInf": [], + "DscPath": "MdePkg.dsc" + }, + + ## options defined ci/Plugin/GuidCheck + "GuidCheck": { + "IgnoreGuidName": [ + "gEfiFirmwareVolumeTopFileGuid" # sec modules must be set to this guid + ], + "IgnoreGuidValue": ["00000000-0000-0000-0000-000000000000"], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [ + "gEfiFirmwareVolumeBlockProtocolGuid=gEfiFirmwareVolumeBlock2ProtocolGuid", + "gEfiMmAccessProtocolGuid=gEfiSmmAccess2ProtocolGuid", + "gEfiSmmCommunicationProtocolGuid=gEfiMmCommunicationProtocolGuid", + "gEfiMmPciRootBridgeIoProtocolGuid=gEfiSmmPciRootBridgeIoProtocolGuid", + "gEfiTrEEProtocolGuid=gEfiTcg2ProtocolGuid", + "gEfiSmmPowerButtonDispatch2ProtocolGuid=gEfiMmPowerButtonDispatchProtocolGuid", + "gEfiSmmBase2ProtocolGuid=gEfiMmBaseProtocolGuid", + "gEfiSmmUsbDispatch2ProtocolGuid=gEfiMmUsbDispatchProtocolGuid", + "gEfiSmmCpuProtocolGuid=gEfiMmCpuProtocolGuid", + "gEfiAcpiTableGuid=gEfiAcpi20TableGuid", + "gEfiSmmControl2ProtocolGuid=gEfiMmControlProtocolGuid", + "gEfiSmmStandbyButtonDispatch2ProtocolGuid=gEfiMmStandbyButtonDispatchProtocolGuid", + "gEfiSmmStatusCodeProtocolGuid=gEfiMmStatusCodeProtocolGuid", + "gEfiDxeSmmReadyToLockProtocolGuid=gEfiDxeMmReadyToLockProtocolGuid", + "gEfiSmmIoTrapDispatch2ProtocolGuid=gEfiMmIoTrapDispatchProtocolGuid", + "gEfiSmmReadyToLockProtocolGuid=gEfiMmReadyToLockProtocolGuid", + "gEfiSmmSxDispatch2ProtocolGuid=gEfiMmSxDispatchProtocolGuid", + "gEfiPeiCapsulePpiGuid=gPeiCapsulePpiGuid", + "gEfiSmmCpuIo2ProtocolGuid=gEfiMmCpuIoProtocolGuid", + "gEfiSmmRscHandlerProtocolGuid=gEfiMmRscHandlerProtocolGuid", + "gEfiSmmConfigurationProtocolGuid=gEfiMmConfigurationProtocolGuid", + "gEfiSmmGpiDispatch2ProtocolGuid=gEfiMmGpiDispatchProtocolGuid", + "gEfiSmmEndOfDxeProtocolGuid=gEfiMmEndOfDxeProtocolGuid", + "gEfiSmmSwDispatch2ProtocolGuid=gEfiMmSwDispatchProtocolGuid", + "gEfiDebugPortProtocolGuid=gEfiDebugPortVariableGuid=gEfiDebugPortDevicePathGuid", ## is this a bug + "gEfiProcessorSpecificErrorSectionGuid=gEfiIa32X64ProcessorErrorSectionGuid", ## is this a bug + "gEfiSmmPeriodicTimerDispatch2ProtocolGuid=gEfiMmPeriodicTimerDispatchProtocolGuid", + "gEdkiiFormBrowserExProtocolGuid=gEfiFormBrowserExProtocolGuid", + "gEfiPeiMmAccessPpiGuid=gPeiSmmAccessPpiGuid", + "gPeiSmmControlPpiGuid=gEfiPeiMmControlPpiGuid" + ] + }, + + ## options defined ci/Plugin/LibraryClassCheck + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 420c859831d621e556317cf100161766eb08fb86 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:20:40 -0700 Subject: [PATCH 076/384] NetworkPkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Use BaseCryptLibNull and TlsLibNull for package CI builds to reduce package build times. Enabled with CONTINUOUS_INTEGRATION in YAML files. By default CONTINUOUS_INTEGRATION is not defined, and the original lib mappings are preserved. Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- NetworkPkg/NetworkPkg.ci.yaml | 62 +++++++++++++++++++++++++++++++++++ NetworkPkg/NetworkPkg.dsc | 5 +++ 2 files changed, 67 insertions(+) create mode 100644 NetworkPkg/NetworkPkg.ci.yaml diff --git a/NetworkPkg/NetworkPkg.ci.yaml b/NetworkPkg/NetworkPkg.ci.yaml new file mode 100644 index 00000000000..70f2e101474 --- /dev/null +++ b/NetworkPkg/NetworkPkg.ci.yaml @@ -0,0 +1,62 @@ +## @file +# CI configuration for NetworkPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "NetworkPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "NetworkPkg/NetworkPkg.dec", + "CryptoPkg/CryptoPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[ + "ShellPkg/ShellPkg.dec" + ], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "NetworkPkg.dsc", + "IgnoreInf": [] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + }, + + "Defines": { + "BLD_*_CONTINUOUS_INTEGRATION": "TRUE", + "BLD_*_NETWORK_ENABLE": "TRUE", + "BLD_*_NETWORK_SNP_ENABLE": "TRUE", + "BLD_*_NETWORK_VLAN_ENABLE": "TRUE", + "BLD_*_NETWORK_IP4_ENABLE": "TRUE", + "BLD_*_NETWORK_IP6_ENABLE": "TRUE", + "BLD_*_NETWORK_TLS_ENABLE": "TRUE", + "BLD_*_NETWORK_HTTP_BOOT_ENABLE": "TRUE", + "BLD_*_NETWORK_ISCSI_ENABLE": "TRUE", + } +} diff --git a/NetworkPkg/NetworkPkg.dsc b/NetworkPkg/NetworkPkg.dsc index 11a29812614..b149453d26f 100644 --- a/NetworkPkg/NetworkPkg.dsc +++ b/NetworkPkg/NetworkPkg.dsc @@ -41,10 +41,15 @@ DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf + TlsLib|CryptoPkg/Library/TlsLibNull/TlsLibNull.inf +!else BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf TlsLib|CryptoPkg/Library/TlsLib/TlsLib.inf +!endif DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf From d495762a97f8fac5f74da77a08c7e1c411d1edc3 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:21:07 -0700 Subject: [PATCH 077/384] PcAtChipsetPkg: Add YAML files for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Ray Ni Signed-off-by: Michael D Kinney Acked-by: Ray Ni Reviewed-by: Liming Gao --- PcAtChipsetPkg/PcAtChipsetPkg.ci.yaml | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 PcAtChipsetPkg/PcAtChipsetPkg.ci.yaml diff --git a/PcAtChipsetPkg/PcAtChipsetPkg.ci.yaml b/PcAtChipsetPkg/PcAtChipsetPkg.ci.yaml new file mode 100644 index 00000000000..be470807bd9 --- /dev/null +++ b/PcAtChipsetPkg/PcAtChipsetPkg.ci.yaml @@ -0,0 +1,46 @@ +## @file +# CI configuration for PcAtChipsetPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "PcAtChipsetPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "PcAtChipsetPkg/PcAtChipsetPkg.dec", + "UefiCpuPkg/UefiCpuPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "PcAtChipsetPkg.dsc", + "IgnoreInf": [] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + "SpellCheck": { + "ExtendWords": [ + "ENUMER", # this is part of an IDE enum + "PCATCHIPSET", + "TXRDY" + ] + } +} From 566c45a533d2062a909f2706f908c0c258b4658a Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:21:26 -0700 Subject: [PATCH 078/384] SecurityPkg: Add YAML files for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Use BaseCryptLibNull for package CI builds to reduce package build times. Enabled with CONTINUOUS_INTEGRATION in YAML files. By default CONTINUOUS_INTEGRATION is not defined, and the original lib mappings are preserved. Cc: Jiewen Yao Cc: Jian J Wang Cc: Chao Zhang Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao Reviewed-by: Jian J Wang --- SecurityPkg/SecurityPkg.ci.yaml | 80 +++++++++++++++++++++++++++++++++ SecurityPkg/SecurityPkg.dsc | 32 ++++++++++++- 2 files changed, 110 insertions(+), 2 deletions(-) create mode 100644 SecurityPkg/SecurityPkg.ci.yaml diff --git a/SecurityPkg/SecurityPkg.ci.yaml b/SecurityPkg/SecurityPkg.ci.yaml new file mode 100644 index 00000000000..95321905331 --- /dev/null +++ b/SecurityPkg/SecurityPkg.ci.yaml @@ -0,0 +1,80 @@ +## @file +# CI configuration for SecurityPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "SecurityPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "SecurityPkg/SecurityPkg.dec", + "CryptoPkg/CryptoPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "SecurityPkg.dsc", + "IgnoreInf": [] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": ["00000000-0000-0000-0000-000000000000"], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [ + "Tpm2InstanceLibDTpm=gEfiTpmDeviceInstanceTpm20DtpmGuid", # by design + ] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "ExtendWords": [ # words to extend to the dictionary for this package + "shortformed", # tpm acpi + "autodetect", + "blocksid", + "comid", + "cpinsidpin", #OpalSScV2 + "ecdsa", # TPM + "ecschnorr", # TPM + "eisaid", # ACPI + "harddisk", + "hashall", + "hashto", + "kek's", + "lfanew", # PE/COFF + "pcrindex", + "pkglength", + "ppuser", + "preos", + "stclear", + "toctou", + "tpm's", + "tpmcmdbuflength", + "tpmcommlib", + "tpmnvvaluelength", + "wrlocked", + "xored" + ], + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + }, + + "Defines": { + "BLD_*_CONTINUOUS_INTEGRATION": "TRUE", + } +} diff --git a/SecurityPkg/SecurityPkg.dsc b/SecurityPkg/SecurityPkg.dsc index 9a254087a34..a2eeadda7a7 100644 --- a/SecurityPkg/SecurityPkg.dsc +++ b/SecurityPkg/SecurityPkg.dsc @@ -44,8 +44,6 @@ HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf TpmCommLib|SecurityPkg/Library/TpmCommLib/TpmCommLib.inf PlatformSecureLib|SecurityPkg/Library/PlatformSecureLibNull/PlatformSecureLibNull.inf @@ -84,7 +82,13 @@ PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +!endif HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterPei.inf ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibDTpm/Tpm12DeviceLibDTpm.inf @@ -95,7 +99,13 @@ [LibraryClasses.common.DXE_DRIVER] HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterDxe.inf Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibTcg/Tpm12DeviceLibTcg.inf Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf @@ -110,13 +120,25 @@ [LibraryClasses.common.DXE_RUNTIME_DRIVER] ReportStatusCodeLib|MdeModulePkg/Library/RuntimeDxeReportStatusCodeLib/RuntimeDxeReportStatusCodeLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +!endif HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterDxe.inf Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibTcg/Tpm12DeviceLibTcg.inf Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf [LibraryClasses.common.UEFI_DRIVER, LibraryClasses.common.UEFI_APPLICATION] +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif HashLib|SecurityPkg/Library/HashLibBaseCryptoRouter/HashLibBaseCryptoRouterDxe.inf Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibTcg/Tpm12DeviceLibTcg.inf Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf @@ -127,7 +149,13 @@ MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +!endif Tpm12DeviceLib|SecurityPkg/Library/Tpm12DeviceLibTcg/Tpm12DeviceLibTcg.inf Tpm2DeviceLib|SecurityPkg/Library/Tpm2DeviceLibTcg2/Tpm2DeviceLibTcg2.inf Tcg2PhysicalPresenceLib|SecurityPkg/Library/SmmTcg2PhysicalPresenceLib/SmmTcg2PhysicalPresenceLib.inf From e3b8a0081b3c2996e6c9a136285fd1e5e2866122 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:21:41 -0700 Subject: [PATCH 079/384] ShellPkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Michael D Kinney Acked-by: Zhichao Gao Acked-by: Ray Ni Reviewed-by: Liming Gao --- ShellPkg/ShellPkg.ci.yaml | 55 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 ShellPkg/ShellPkg.ci.yaml diff --git a/ShellPkg/ShellPkg.ci.yaml b/ShellPkg/ShellPkg.ci.yaml new file mode 100644 index 00000000000..67de34a2556 --- /dev/null +++ b/ShellPkg/ShellPkg.ci.yaml @@ -0,0 +1,55 @@ +## @file +# CI configuration for ShellPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "ShellPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "ShellPkg/ShellPkg.dec", + "NetworkPkg/NetworkPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "ShellPkg.dsc", + "IgnoreInf": [ + "ShellPkg/Application/ShellCTestApp/ShellCTestApp.inf", + "ShellPkg/Application/ShellExecTestApp/SA.inf", + "ShellPkg/Application/ShellSortTestApp/ShellSortTestApp.inf" + ] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [ + "Shell=gUefiShellFileGuid", # by design + ] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 30c00d7f191252466d4ed72bf584fe659f14be0a Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:21:54 -0700 Subject: [PATCH 080/384] UefiCpuPkg: Add YAML file for CI builds https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YAML file to the package directory with the configuration of the checks to perform during a CI build. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Signed-off-by: Michael D Kinney Acked-by: Laszlo Ersek Acked-by: Ray Ni Reviewed-by: Liming Gao --- UefiCpuPkg/UefiCpuPkg.ci.yaml | 51 +++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 UefiCpuPkg/UefiCpuPkg.ci.yaml diff --git a/UefiCpuPkg/UefiCpuPkg.ci.yaml b/UefiCpuPkg/UefiCpuPkg.ci.yaml new file mode 100644 index 00000000000..99e460a8b09 --- /dev/null +++ b/UefiCpuPkg/UefiCpuPkg.ci.yaml @@ -0,0 +1,51 @@ +## @file +# CI configuration for UefiCpuPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "UefiCpuPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "MdeModulePkg/MdeModulePkg.dec", + "UefiCpuPkg/UefiCpuPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "UefiCpuPkg.dsc", + "IgnoreInf": [ + "UefiCpuPkg/ResetVector/FixupVtf/Vtf.inf", + "UefiCpuPkg/ResetVector/Vtf0/Vtf0.inf" + ] + }, + "GuidCheck": { + "IgnoreGuidName": ["SecCore", "ResetVector"], # Expected duplication for gEfiFirmwareVolumeTopFileGuid + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} From 3137900fc95ef0537990035dc2a94fe7086d604e Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 25 Oct 2019 13:53:34 -0700 Subject: [PATCH 081/384] SignedCapsulePkg: Use BaseCryptLibNull to reduce package CI time https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Use BaseCryptLibNull for package CI builds to reduce package build times. Enabled with PYTOOL_CONTINUOUS_INTEGRATION in YAML files. By default PYTOOL_CONTINUOUS_INTEGRATION is not defined, and the original lib mappings are preserved. Cc: Jiewen Yao Cc: Chao Zhang Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- SignedCapsulePkg/SignedCapsulePkg.dsc | 38 +++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/SignedCapsulePkg/SignedCapsulePkg.dsc b/SignedCapsulePkg/SignedCapsulePkg.dsc index 03f714f9a79..c5080ec1dd4 100644 --- a/SignedCapsulePkg/SignedCapsulePkg.dsc +++ b/SignedCapsulePkg/SignedCapsulePkg.dsc @@ -87,8 +87,6 @@ AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf - IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf - OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf EdkiiSystemCapsuleLib|SignedCapsulePkg/Library/EdkiiSystemCapsuleLib/EdkiiSystemCapsuleLib.inf IniParsingLib|SignedCapsulePkg/Library/IniParsingLib/IniParsingLib.inf @@ -116,7 +114,13 @@ HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf LockBoxLib|MdeModulePkg/Library/SmmLockBoxLib/SmmLockBoxPeiLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +!endif [LibraryClasses.common.DXE_CORE] HobLib|MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf @@ -125,7 +129,13 @@ [LibraryClasses.common.DXE_DRIVER] HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.inf @@ -133,7 +143,13 @@ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +!endif CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibFmp/DxeRuntimeCapsuleLib.inf @@ -150,19 +166,37 @@ MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf SmmMemLib|MdePkg/Library/SmmMemLib/SmmMemLib.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +!endif [LibraryClasses.common.UEFI_DRIVER] HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf DebugLib|MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif [LibraryClasses.common.UEFI_APPLICATION] HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf DebugLib|MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf +!ifdef CONTINUOUS_INTEGRATION + BaseCryptLib|CryptoPkg/Library/BaseCryptLibNull/BaseCryptLibNull.inf +!else + IntrinsicLib|CryptoPkg/Library/IntrinsicLib/IntrinsicLib.inf + OpensslLib|CryptoPkg/Library/OpensslLib/OpensslLib.inf BaseCryptLib|CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +!endif [PcdsFixedAtBuild] gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x0f From 4eb2baba9343624e366032697049a713bdaef369 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Mon, 7 Oct 2019 20:25:30 -0700 Subject: [PATCH 082/384] .pytool: Add CISettings.py and Readme.md https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add main python script for EDK II Continuous Integration (CI) builds along with a Readme.md that provides a summary of the packages, platforms, and checks performs during a CI build. Cc: Sean Brogan Cc: Bret Barkelew Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .pytool/CISettings.py | 173 ++++++++++++++++++++++++++++++++ .pytool/Readme.md | 223 ++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 396 insertions(+) create mode 100644 .pytool/CISettings.py create mode 100644 .pytool/Readme.md diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py new file mode 100644 index 00000000000..ce177937e13 --- /dev/null +++ b/.pytool/CISettings.py @@ -0,0 +1,173 @@ +# @file +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import os +import logging +from edk2toolext.environment import shell_environment +from edk2toolext.invocables.edk2_ci_build import CiBuildSettingsManager +from edk2toolext.invocables.edk2_setup import SetupSettingsManager, RequiredSubmodule +from edk2toolext.invocables.edk2_update import UpdateSettingsManager +from edk2toolext.invocables.edk2_pr_eval import PrEvalSettingsManager +from edk2toollib.utility_functions import GetHostInfo + + +class Settings(CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): + + def __init__(self): + self.ActualPackages = [] + self.ActualTargets = [] + self.ActualArchitectures = [] + self.ActualToolChainTag = "" + + # ####################################################################################### # + # Extra CmdLine configuration # + # ####################################################################################### # + + def AddCommandLineOptions(self, parserObj): + pass + + def RetrieveCommandLineOptions(self, args): + pass + + # ####################################################################################### # + # Default Support for this Ci Build # + # ####################################################################################### # + + def GetPackagesSupported(self): + ''' return iterable of edk2 packages supported by this build. + These should be edk2 workspace relative paths ''' + + return ("MdePkg", + "MdeModulePkg", + "NetworkPkg", + "PcAtChipsetPkg", + "SecurityPkg", + "UefiCpuPkg", + "FmpDevicePkg", + "ShellPkg", + "FatPkg", + "CryptoPkg" + ) + + def GetArchitecturesSupported(self): + ''' return iterable of edk2 architectures supported by this build ''' + return ("IA32", + "X64", + "ARM", + "AARCH64") + + def GetTargetsSupported(self): + ''' return iterable of edk2 target tags supported by this build ''' + return ("DEBUG", "RELEASE", "NO-TARGET", "NOOPT") + + # ####################################################################################### # + # Verify and Save requested Ci Build Config # + # ####################################################################################### # + + def SetPackages(self, list_of_requested_packages): + ''' Confirm the requested package list is valid and configure SettingsManager + to build the requested packages. + + Raise UnsupportedException if a requested_package is not supported + ''' + unsupported = set(list_of_requested_packages) - \ + set(self.GetPackagesSupported()) + if(len(unsupported) > 0): + logging.critical( + "Unsupported Package Requested: " + " ".join(unsupported)) + raise Exception("Unsupported Package Requested: " + + " ".join(unsupported)) + self.ActualPackages = list_of_requested_packages + + def SetArchitectures(self, list_of_requested_architectures): + ''' Confirm the requests architecture list is valid and configure SettingsManager + to run only the requested architectures. + + Raise Exception if a list_of_requested_architectures is not supported + ''' + unsupported = set(list_of_requested_architectures) - \ + set(self.GetArchitecturesSupported()) + if(len(unsupported) > 0): + logging.critical( + "Unsupported Architecture Requested: " + " ".join(unsupported)) + raise Exception( + "Unsupported Architecture Requested: " + " ".join(unsupported)) + self.ActualArchitectures = list_of_requested_architectures + + def SetTargets(self, list_of_requested_target): + ''' Confirm the request target list is valid and configure SettingsManager + to run only the requested targets. + + Raise UnsupportedException if a requested_target is not supported + ''' + unsupported = set(list_of_requested_target) - \ + set(self.GetTargetsSupported()) + if(len(unsupported) > 0): + logging.critical( + "Unsupported Targets Requested: " + " ".join(unsupported)) + raise Exception("Unsupported Targets Requested: " + + " ".join(unsupported)) + self.ActualTargets = list_of_requested_target + + # ####################################################################################### # + # Actual Configuration for Ci Build # + # ####################################################################################### # + + def GetActiveScopes(self): + ''' return tuple containing scopes that should be active for this process ''' + scopes = ("cibuild","edk2-build") + + self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") + + if GetHostInfo().os.upper() == "LINUX" and self.ActualToolChainTag.upper().startswith("GCC"): + if "AARCH64" in self.ActualArchitectures: + scopes += ("gcc_aarch64_linux",) + if "ARM" in self.ActualArchitectures: + scopes += ("gcc_arm_linux",) + + return scopes + + def GetRequiredSubmodules(self): + ''' return iterable containing RequiredSubmodule objects. + If no RequiredSubmodules return an empty iterable + ''' + rs=[] + rs.append(RequiredSubmodule( + "ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3", False)) + rs.append(RequiredSubmodule( + "CryptoPkg/Library/OpensslLib/openssl", False)) + return rs + + def GetName(self): + return "Edk2" + + def GetDependencies(self): + return [] + + def GetPackagesPath(self): + return () + + def GetWorkspaceRoot(self): + ''' get WorkspacePath ''' + return os.path.dirname(os.path.dirname(os.path.abspath(__file__))) + + def FilterPackagesToTest(self, changedFilesList: list, potentialPackagesList: list) -> list: + ''' Filter potential packages to test based on changed files. ''' + build_these_packages=[] + possible_packages=potentialPackagesList.copy() + for f in changedFilesList: + nodes=f.split("/") # split each part of path for comparison later + + # python file change in .pytool folder causes building all + if f.endswith(".py") and ".pytool" in nodes: + build_these_packages = possible_packages + break + + # BaseTools files that might change the build + if "BaseTools" in nodes: + if os.path.splitext(f) not in [".txt", ".md"]: + build_these_packages = possible_packages + break + return build_these_packages diff --git a/.pytool/Readme.md b/.pytool/Readme.md new file mode 100644 index 00000000000..135d283fe22 --- /dev/null +++ b/.pytool/Readme.md @@ -0,0 +1,223 @@ +# Edk2 Continuous Integration + +## Basic Status + +| Package | Windows VS2019 (IA32/X64)| Ubuntu GCC (IA32/X64/ARM/AARCH64) | Known Issues | +| :---- | :----- | :---- | :--- | +| ArmPkg | +| ArmPlatformPkg | +| ArmVirtPkg | +| CryptoPkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode +| DynamicTablesPkg | +| EmbeddedPkg | +| EmulatorPkg | +| FatPkg | :heavy_check_mark: | :heavy_check_mark: | +| FmpDevicePkg | :heavy_check_mark: | :heavy_check_mark: | +| IntelFsp2Pkg | +| IntelFsp2WrapperPkg | +| MdeModulePkg | :heavy_check_mark: | :heavy_check_mark: | DxeIpl dependency on ArmPkg, Depends on StandaloneMmPkg, Spell checking in audit mode +| MdePkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode +| NetworkPkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode +| OvmfPkg | +| PcAtChipsetPkg | :heavy_check_mark: | :heavy_check_mark: | +| SecurityPkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode +| ShellPkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode, 3 modules are not being built by DSC +| SignedCapsulePkg | +| SourceLevelDebugPkg | +| StandaloneMmPkg | +| UefiCpuPkg | :heavy_check_mark: | :heavy_check_mark: | Spell checking in audit mode, 2 binary modules not being built by DSC +| UefiPayloadPkg | + +For more detailed status look at the test results of the latest CI run on the +repo readme. + +## Background + +This Continuous integration and testing infrastructure leverages the TianoCore EDKII Tools PIP modules: +[library](https://pypi.org/project/edk2-pytool-library/) and +[extensions](https://pypi.org/project/edk2-pytool-extensions/) (with repos +located [here](https://github.com/tianocore/edk2-pytool-library) and +[here](https://github.com/tianocore/edk2-pytool-extensions)). + +The primary execution flows can be found in the +`.azurepipelines/Windows-VS2019.yml` and `.azurepipelines/Ubuntu-GCC5.yml` +files. These YAML files are consumed by the Azure Dev Ops Build Pipeline and +dictate what server resources should be used, how they should be configured, and +what processes should be run on them. An overview of this schema can be found +[here](https://docs.microsoft.com/en-us/azure/devops/pipelines/yaml-schema?view=azure-devops&tabs=schema). + +Inspection of these files reveals the EDKII Tools commands that make up the +primary processes for the CI build: 'stuart_setup', 'stuart_update', and +'stuart_ci_build'. These commands come from the EDKII Tools PIP modules and are +configured as described below. More documentation on the tools can be +found [here](https://github.com/tianocore/edk2-pytool-extensions/blob/master/docs/using.md) +and [here](https://github.com/tianocore/edk2-pytool-extensions/blob/master/docs/features/feature_invocables.md). + +## Configuration + +Configuration of the CI process consists of (in order of precedence): + +* command-line arguments passed in via the Pipeline YAML +* a per-package configuration file (e.g. `.ci.yaml`) that is + detected by the CI system in EDKII Tools. +* a global configuration Python module (e.g. `CISetting.py`) passed in via the + command-line + +The global configuration file is described in +[this readme](https://github.com/tianocore/edk2-pytool-extensions/blob/master/docs/usability/using_settings_manager.md) +from the EDKII Tools documentation. This configuration is written as a Python +module so that decisions can be made dynamically based on command line +parameters and codebase state. + +The per-package configuration file can override most settings in the global +configuration file, but is not dynamic. This file can be used to skip or +customize tests that may be incompatible with a specific package. Each test generally requires +per package configuration which comes from this file. + +## Running CI locally + +The EDKII Tools environment (and by extension the ci) is designed to support +easily and consistantly running locally and in a cloud ci environment. To do +that a few steps should be followed. Details of EDKII Tools can be found in the +[docs folder here](https://github.com/tianocore/edk2-pytool-extensions/tree/master/docs) + +### Prerequisets + +1. A supported toolchain (others might work but this is what is tested and validated) + * Windows 10: + * VS 2017 or VS 2019 + * Windows SDK (for rc) + * Windows WDK (for capsules) + * Ubuntu 16.04 + * GCC5 + * Easy to add more but this is the current state +2. Python 3.7.x or newer on path +3. git on path +4. Recommended to setup and activate a python virtual environment +5. Install the requirements `pip install --upgrade pip-requirements.txt` + +### Running CI + +1. clone your edk2 repo +2. Activate your python virtual environment in cmd window +3. Get code dependencies (done only when submodules change) + * `stuart_setup -c .pytool/CISettings.py TOOL_CHAIN_TAG=` +4. Update other dependencies (done more often) + * `stuart_update -c .pytool/CISettings.py TOOL_CHAIN_TAG=` +5. Run CI build (--help will give you options) + * `stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=` + * -p : To build only certain packages use a CSV list + * -a : To run only certain architectures use a CSV list + * -t : To run only tests related to certain targets use a + CSV list + * By default all tests are opted in. Then given a package.ci.yaml file those + tests can be configured for a package. Finally setting the check to the + value `skip` will skip that plugin. Examples: + * `CompilerPlugin=skip` skip the build test + * `GuidCheck=skip` skip the Guid check + * `SpellCheck=skip` skip the spell checker + * etc +6. Detailed reports and logs per package are captured in the `Build` directory + +## Current PyTool Test Capabilities + +All CI tests are instances of EDKII Tools plugins. Documentation on the plugin +system can be found [here](https://github.com/tianocore/edk2-pytool-extensions/blob/master/docs/usability/using_plugin_manager.md) +and [here](https://github.com/tianocore/edk2-pytool-extensions/blob/master/docs/features/feature_plugin_manager.md). +Upon invocation, each plugin will be passed the path to the current package +under test and a dictionary containing its targeted configuration, as assembled +from the command line, per-package configuration, and global configuration. + +Note: CI plugins are considered unique from build plugins and helper plugins, +even though some CI plugins may execute steps of a build. + +In the example, these plugins live alongside the code under test (in the +`.pytool/Plugin` directory), but may be moved to the 'edk2-test' repo if that +location makes more sense for the community. + +### Module Inclusion Test - DscCompleteCheck + +This test scans all available modules (via INF files) and compares them to the +package-level DSC file for the package each module is contained within. The test +considers it an error if any module does not appear in the `Components` section +of at least one package-level DSC (indicating that it would not be built if the +package were built). + +### Code Compilation Test - CompilerPlugin + +Once the Module Inclusion Test has verified that all modules would be built if +all package-level DSCs were built, the Code Compilation Test simply runs through +and builds every package-level DSC on every toolchain and for every architecture +that is supported. Any module that fails to build is considered an error. + +### GUID Uniqueness Test - GuidCheck + +This test works on the collection of all packages rather than an individual +package. It looks at all FILE_GUIDs and GUIDs declared in DEC files and ensures +that they are unique for the codebase. This prevents, for example, accidental +duplication of GUIDs when using an existing INF as a template for a new module. + +### Cross-Package Dependency Test - DependencyCheck + +This test compares the list of all packages used in INFs files for a given +package against a list of "allowed dependencies" in plugin configuration for +that package. Any module that depends on a disallowed package will cause a test +failure. + +### Library Declaration Test - LibraryClassCheck + +This test scans at all library header files found in the `Library` folders in +all of the package's declared include directories and ensures that all files +have a matching LibraryClass declaration in the DEC file for the package. Any +missing declarations will cause a failure. + +### Invalid Character Test - CharEncodingCheck + +This test scans all files in a package to make sure that there are no invalid +Unicode characters that may cause build errors in some character +sets/localizations. + +### Spell Checking - cspell + +This test runs a spell checker on all files within the package. This is done +using the NodeJs cspell tool. For details check `.pytool/Plugin/SpellCheck`. +For this plugin to run during ci you must install nodejs and cspell and have +both available to the command line when running your CI. + +Install + +* Install nodejs from https://nodejs.org/en/ +* Install cspell + 1. Open cmd prompt with access to node and npm + 2. Run `npm install -g cspell` + + More cspell info: https://github.com/streetsidesoftware/cspell + +## PyTool Scopes + +Scopes are how the PyTool ext_dep, path_env, and plugins are activated. Meaning +that if an invocable process has a scope active then those ext_dep and path_env +will be active. To allow easy integration of PyTools capabilities there are a +few standard scopes. + +| Scope | Invocable | Description | +| :---- | :----- | :---- | +| global | edk2_invocable++ - should be base_abstract_invocable | Running an invocables | +| global-win | edk2_invocable++ | Running on Microsoft Windows | +| global-nix | edk2_invocable++ | Running on Linux based OS | +| edk2-build | | This indicates that an invocable is building EDK2 based UEFI code | +| cibuild | set in .pytool/CISettings.py | Suggested target for edk2 continuous integration builds. Tools used for CiBuilds can use this scope. Example: asl compiler | + +## Future investments + +* PatchCheck tests as plugins +* MacOS/xcode support +* Clang/LLVM support +* Visual Studio AARCH64 and ARM support +* BaseTools C tools CI/PR and binary release process +* BaseTools Python tools CI/PR process +* Host based unit testing +* Extensible private/closed source platform reporting +* Platform builds, validation +* UEFI SCTs +* Other automation From 106c7a991c1b15c8065af921d8e32462fdde64b7 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Mon, 7 Oct 2019 20:34:34 -0700 Subject: [PATCH 083/384] .azurepipelines: Add Azure Pipelines YML configuration files https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add YML configuration files used to run the EDK II Continuous Integration (CI) checks on Azure Pipelines agents. Cc: Sean Brogan Cc: Bret Barkelew Cc: Liming Gao Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .azurepipelines/Ubuntu-GCC5.yml | 18 +++ .azurepipelines/Ubuntu-PatchCheck.yml | 35 +++++ .azurepipelines/Windows-VS2019.yml | 18 +++ .../templates/basetools-build-steps.yml | 37 +++++ .../templates/pr-gate-build-job.yml | 80 +++++++++++ .azurepipelines/templates/pr-gate-steps.yml | 130 ++++++++++++++++++ .../templates/spell-check-prereq-steps.yml | 22 +++ 7 files changed, 340 insertions(+) create mode 100644 .azurepipelines/Ubuntu-GCC5.yml create mode 100644 .azurepipelines/Ubuntu-PatchCheck.yml create mode 100644 .azurepipelines/Windows-VS2019.yml create mode 100644 .azurepipelines/templates/basetools-build-steps.yml create mode 100644 .azurepipelines/templates/pr-gate-build-job.yml create mode 100644 .azurepipelines/templates/pr-gate-steps.yml create mode 100644 .azurepipelines/templates/spell-check-prereq-steps.yml diff --git a/.azurepipelines/Ubuntu-GCC5.yml b/.azurepipelines/Ubuntu-GCC5.yml new file mode 100644 index 00000000000..a26a3a2cb2e --- /dev/null +++ b/.azurepipelines/Ubuntu-GCC5.yml @@ -0,0 +1,18 @@ +## @file +# Azure Pipeline build file for a build using ubuntu and GCC5 +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +trigger: +- master +pr: +- master + +jobs: +- template: templates/pr-gate-build-job.yml + parameters: + tool_chain_tag: 'GCC5' + vm_image: 'ubuntu-latest' + arch_list: "IA32,X64,ARM,AARCH64" + diff --git a/.azurepipelines/Ubuntu-PatchCheck.yml b/.azurepipelines/Ubuntu-PatchCheck.yml new file mode 100644 index 00000000000..dff8f579b67 --- /dev/null +++ b/.azurepipelines/Ubuntu-PatchCheck.yml @@ -0,0 +1,35 @@ +## @file +# Azure Pipielines YML file that evalues the patch series in a PR using the +# python script BaseTools/Scripts/PatchCheck.py. +# +# NOTE: This example monitors pull requests against the edk2-ci branch. Most +# environments would replace 'edk2-ci' with 'master'. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# https://github.com/tianocore +# +## + +trigger: none + +pr: +- master + +pool: + vmImage: 'ubuntu-latest' + +steps: +- checkout: self + clean: true + +- task: UsePythonVersion@0 + inputs: + versionSpec: '3.7.x' + architecture: 'x64' + +- script: | + git fetch origin $(System.PullRequest.TargetBranch):$(System.PullRequest.TargetBranch) + python BaseTools/Scripts/PatchCheck.py $(System.PullRequest.TargetBranch)..$(System.PullRequest.SourceCommitId) + displayName: 'Use PatchCheck.py to verify patch series in pull request' diff --git a/.azurepipelines/Windows-VS2019.yml b/.azurepipelines/Windows-VS2019.yml new file mode 100644 index 00000000000..d6b879cd989 --- /dev/null +++ b/.azurepipelines/Windows-VS2019.yml @@ -0,0 +1,18 @@ +## @file +# Azure Pipeline build file for a build using Windows and VS2019 +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +trigger: +- master + +pr: +- master + +jobs: +- template: templates/pr-gate-build-job.yml + parameters: + tool_chain_tag: 'VS2019' + vm_image: 'windows-latest' + arch_list: "IA32,X64" diff --git a/.azurepipelines/templates/basetools-build-steps.yml b/.azurepipelines/templates/basetools-build-steps.yml new file mode 100644 index 00000000000..d8c108c6e21 --- /dev/null +++ b/.azurepipelines/templates/basetools-build-steps.yml @@ -0,0 +1,37 @@ +## @file +# File templates/basetools-build-job.yml +# +# template file to build basetools +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +parameters: + tool_chain_tag: '' + +steps: +- ${{ if contains(parameters.tool_chain_tag, 'GCC') }}: + - bash: sudo apt-get update + displayName: Update apt + condition: and(gt(variables.pkg_count, 0), succeeded()) + + - bash: sudo apt-get install gcc g++ make uuid-dev + displayName: Install required tools + condition: and(gt(variables.pkg_count, 0), succeeded()) + +- task: CmdLine@1 + displayName: Build Base Tools from source + inputs: + filename: python + arguments: BaseTools/Edk2ToolsBuild.py -t ${{ parameters.tool_chain_tag }} + condition: and(gt(variables.pkg_count, 0), succeeded()) + +- task: CopyFiles@2 + displayName: "Copy base tools build log" + inputs: + targetFolder: '$(Build.ArtifactStagingDirectory)' + SourceFolder: 'BaseTools/BaseToolsBuild' + contents: | + BASETOOLS_BUILD*.* + flattenFolders: true + condition: and(gt(variables.pkg_count, 0), succeededOrFailed()) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml new file mode 100644 index 00000000000..981acd68a19 --- /dev/null +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -0,0 +1,80 @@ +## @file +# File templates/pr-gate-build-job.yml +# +# template file used to build supported packages. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +parameters: + tool_chain_tag: '' + vm_image: '' + arch_list: '' + +# Build step +jobs: + +- job: Build_${{ parameters.tool_chain_tag }} + + #Use matrix to speed up the build process + strategy: + matrix: + TARGET_MDE_CPU: + Build.Pkgs: 'MdePkg,UefiCpuPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + TARGET_MDEMODULE_DEBUG: + Build.Pkgs: 'MdeModulePkg' + Build.Targets: 'DEBUG' + TARGET_MDEMODULE_RELEASE: + Build.Pkgs: 'MdeModulePkg' + Build.Targets: 'RELEASE,NO-TARGET' + TARGET_NETWORK: + Build.Pkgs: 'NetworkPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + TARGET_OTHER: + Build.Pkgs: 'PcAtChipsetPkg,ShellPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + TARGET_FMP: + Build.Pkgs: 'FmpDevicePkg,FatPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + TARGET_CRYPTO: + Build.Pkgs: 'CryptoPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + TARGET_SECURITY: + Build.Pkgs: 'SecurityPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + + workspace: + clean: all + + pool: + vmImage: ${{ parameters.vm_image }} + + steps: + - template: pr-gate-steps.yml + parameters: + tool_chain_tag: ${{ parameters.tool_chain_tag }} + build_pkgs: $(Build.Pkgs) + build_targets: $(Build.Targets) + build_archs: ${{ parameters.arch_list }} + +- job: FINISHED + dependsOn: Build_${{ parameters.tool_chain_tag }} + condition: succeeded() + steps: + - checkout: none + - script: | + echo FINISHED + sleep 10 + displayName: FINISHED + +- job: FAILED + dependsOn: Build_${{ parameters.tool_chain_tag }} + condition: failed() + steps: + - checkout: none + - script: | + echo FAILED + sleep 10 + displayName: FAILED diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml new file mode 100644 index 00000000000..a969661dea1 --- /dev/null +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -0,0 +1,130 @@ +## @file +# File templates/pr-gate-steps.yml +# +# template file containing the steps to build +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +parameters: + tool_chain_tag: '' + build_pkgs: '' + build_targets: '' + build_archs: '' + +steps: +- checkout: self + clean: true + fetchDepth: 1 + +- task: UsePythonVersion@0 + inputs: + versionSpec: '3.7.x' + architecture: 'x64' + +- script: pip install -r pip-requirements.txt --upgrade + displayName: 'Install/Upgrade pip modules' + +# Set default +- bash: | + echo "##vso[task.setvariable variable=pkgs_to_build]${{ parameters.build_pkgs }}" + echo "##vso[task.setvariable variable=pkg_count]${{ 1 }}" + +# trim the package list if this is a PR +- task: CmdLine@1 + displayName: Check if ${{ parameters.build_pkgs }} need testing + inputs: + filename: stuart_pr_eval + arguments: -c .pytool/CISettings.py -p ${{ parameters.build_pkgs }} --pr-target origin/$(System.PullRequest.targetBranch) --output-csv-format-string "##vso[task.setvariable variable=pkgs_to_build;isOutpout=true]{pkgcsv}" --output-count-format-string "##vso[task.setvariable variable=pkg_count;isOutpout=true]{pkgcount}" + condition: eq(variables['Build.Reason'], 'PullRequest') + +# build basetools +- template: basetools-build-steps.yml + parameters: + tool_chain_tag: ${{ parameters.tool_chain_tag }} + +# install spell check prereqs +- template: spell-check-prereq-steps.yml + +# Build repo +- task: CmdLine@1 + displayName: Setup ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} + inputs: + filename: stuart_setup + arguments: -c .pytool/CISettings.py -p $(pkgs_to_build) -t ${{ parameters.build_targets}} -a ${{ parameters.build_archs}} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} + condition: and(gt(variables.pkg_count, 0), succeeded()) + +- task: CmdLine@1 + displayName: Update ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} + inputs: + filename: stuart_update + arguments: -c .pytool/CISettings.py -p $(pkgs_to_build) -t ${{ parameters.build_targets}} -a ${{ parameters.build_archs}} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} + condition: and(gt(variables.pkg_count, 0), succeeded()) + +- task: CmdLine@1 + displayName: Build and Test ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} + inputs: + filename: stuart_ci_build + arguments: -c .pytool/CISettings.py -p $(pkgs_to_build) -t ${{ parameters.build_targets}} -a ${{ parameters.build_archs}} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} + condition: and(gt(variables.pkg_count, 0), succeeded()) + +# Publish Test Results to Azure Pipelines/TFS +- task: PublishTestResults@2 + displayName: 'Publish junit test results' + continueOnError: true + condition: and( succeededOrFailed(),gt(variables.pkg_count, 0)) + inputs: + testResultsFormat: 'JUnit' # Options: JUnit, NUnit, VSTest, xUnit + testResultsFiles: 'Build/TestSuites.xml' + #searchFolder: '$(System.DefaultWorkingDirectory)' # Optional + mergeTestResults: true # Optional + testRunTitle: $(System.JobName) # Optional + #buildPlatform: # Optional + #buildConfiguration: # Optional + publishRunAttachments: true # Optional + +# Publish Test Results to Azure Pipelines/TFS +- task: PublishTestResults@2 + displayName: 'Publish host based test results for $(System.JobName)' + continueOnError: true + condition: and( succeededOrFailed(), gt(variables.pkg_count, 0)) + inputs: + testResultsFormat: 'JUnit' # Options: JUnit, NUnit, VSTest, xUnit + testResultsFiles: 'Build/**/*.result.xml' + #searchFolder: '$(System.DefaultWorkingDirectory)' # Optional + mergeTestResults: false # Optional + testRunTitle: ${{ parameters.build_pkgs }} # Optional + #buildPlatform: # Optional + #buildConfiguration: # Optional + publishRunAttachments: true # Optional + +# Copy the build logs to the artifact staging directory +- task: CopyFiles@2 + displayName: "Copy build logs" + inputs: + targetFolder: '$(Build.ArtifactStagingDirectory)' + SourceFolder: 'Build' + contents: | + BUILDLOG_*.txt + BUILDLOG_*.md + CI_*.txt + CI_*.md + CISETUP.txt + SETUPLOG.txt + UPDATE_LOG.txt + PREVALLOG.txt + TestSuites.xml + **/BUILD_TOOLS_REPORT.html + **/OVERRIDELOG.TXT + flattenFolders: true + condition: succeededOrFailed() + +# Publish build artifacts to Azure Artifacts/TFS or a file share +- task: PublishBuildArtifacts@1 + continueOnError: true + displayName: "Publish build logs" + inputs: + pathtoPublish: '$(Build.ArtifactStagingDirectory)' + artifactName: 'Build Logs $(System.JobName)' + condition: succeededOrFailed() diff --git a/.azurepipelines/templates/spell-check-prereq-steps.yml b/.azurepipelines/templates/spell-check-prereq-steps.yml new file mode 100644 index 00000000000..e1570d4f2aa --- /dev/null +++ b/.azurepipelines/templates/spell-check-prereq-steps.yml @@ -0,0 +1,22 @@ +## @file +# File templates/spell-check-prereq-steps.yml +# +# template file used to install spell checking prerequisits +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +parameters: + none: '' + +steps: +- task: NodeTool@0 + inputs: + versionSpec: '10.x' + #checkLatest: false # Optional + condition: and(gt(variables.pkg_count, 0), succeeded()) + +- script: npm install -g cspell + displayName: 'Install cspell npm' + condition: and(gt(variables.pkg_count, 0), succeeded()) From 4baa783d5e372380c64d538a153bc97640e8257c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 18 Oct 2019 15:22:36 -0700 Subject: [PATCH 084/384] .mergify: Add Mergify YML pull request rules configuration file https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Add directory for the Mergify YML configuration files that provides rules and actions used to process a pull request. * Auto commit a PR from EDK II Maintainer with 'push' label set and all CI checks pass * Auto close a PR from any developers without 'push' label set and all CI checks pass. * Auto close a PR from a non EDK II Maintainer that has the 'push' label set. * Post a comment to a PR that has a merge conflict. Submitter can resolved conflicts and reopen the PR. * Post a comment to a PR that fails PatchCheck.py Submitter can resolve PatchCheck.py issues and reopen the PR. Cc: Liming Gao Cc: Sean Brogan Cc: Bret Barkelew Signed-off-by: Michael D Kinney Reviewed-by: Liming Gao --- .mergify/config.yml | 97 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 97 insertions(+) create mode 100644 .mergify/config.yml diff --git a/.mergify/config.yml b/.mergify/config.yml new file mode 100644 index 00000000000..26583de0f63 --- /dev/null +++ b/.mergify/config.yml @@ -0,0 +1,97 @@ +## @file +# Mergify YML file that automatically merges a GitHub pull request against +# edk2-ci if all of the GitHub branch protections have passed. It also +# contains rules to: +# * auto close branches that are not from an EDK II Maintainer +# * post a comment on pull requests that have merge conflicts. +# * post a comment on pull requests that have PatchCheck.py errors. +# +# Configuration Notes: +# * Update the 'base=edk2-ci' statements with the name of the branch to merge +# pull requests. +# +# * Update the 'status-failure' statement with the name of the name of the Azure +# Pipelines Build that performs the EDK II Maintainer check. +# +# * This file must be checked into the 'default' branch of a repo. Copies +# of this file on other branches of a repo are ignored by Mergify. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +# https://github.com/apps/mergify +# https://doc.mergify.io/ +# +## + +pull_request_rules: + + - name: Automatically merge a PR when all required checks pass and 'push' label is present + conditions: + - base=master + - label=push + - author=@tianocore/edk-ii-maintainers + - status-success=tianocore.PatchCheck + - status-success=Ubuntu GCC5 PR + - status-success=Windows VS2019 PR + actions: + merge: + strict: true + method: rebase + + - name: Automatically close a PR when all required checks pass and 'push' label is not present + conditions: + - base=master + - -label=push + - -closed + - status-success=tianocore.PatchCheck + - status-success=Ubuntu GCC5 PR + - status-success=Windows VS2019 PR + - status-success=Ubuntu GCC5 PR (FINISHED) + - status-success=Windows VS2019 PR (FINISHED) + actions: + close: + message: All checks passed. Auto close personal build. + + - name: Post a comment on a PR that can not be merged due to a merge conflict + conditions: + - base=master + - conflict + actions: + comment: + message: PR can not be merged due to conflict. Please rebase and resubmit + + - name: Automatically close a PR that fails the EDK II Maintainers membership check and 'push' label is present + conditions: + - base=master + - label=push + - -author=@tianocore/edk-ii-maintainers + actions: + close: + message: PR submitter is not a member of the Tianocore EDK II Maintainers team + + - name: Post a comment on a PR if PatchCheck fails + conditions: + - base=master + - status-failure=tianocore.PatchCheck + actions: + comment: + message: PR can not be merged due to a PatchCheck failure. Please resolve and resubmit + + - name: Post a comment on a PR if Ubuntu GCC5 fails + conditions: + - base=master + - status-failure=Ubuntu GCC5 PR + - status-success=Ubuntu GCC5 PR (FAILED) + actions: + comment: + message: PR can not be merged due to an Ubuntu GCC5 failure. Please resolve and resubmit + + - name: Post a comment on a PR if Windows VS2019 fails + conditions: + - base=master + - status-failure=Windows VS2019 PR + - status-success=Windows VS2019 PR (FAILED) + actions: + comment: + message: PR can not be merged due to a Windows VS2019 failure. Please resolve and resubmit From f8dd7c7018adf78992da572eeaf53c0ce31a411f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 28 Oct 2019 13:48:49 -0700 Subject: [PATCH 085/384] Readme.md: Add CI build status badges https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Update Readme.md with status badges from the most recent EDK II Continuous Integration(CI) build. Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Michael D Kinney Acked-by: Laszlo Ersek Reviewed-by: Liming Gao Reviewed-by: Leif Lindholm --- Readme.md | 51 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) diff --git a/Readme.md b/Readme.md index 9bf60bede8e..dcd86daef14 100644 --- a/Readme.md +++ b/Readme.md @@ -3,6 +3,57 @@ A modern, feature-rich, cross-platform firmware development environment for the UEFI and PI specifications from www.uefi.org. +# Build Status + + + + + + + + + + + + + + + + + + + + + + + + + + +
Host TypeToolchainBranchBuild StatusTest StatusCode Coverage
WindowsVS2019edk2-ci + + + + + + + + +
UbuntuGCCedk2-ci + + + + + + + + +
+ +[More CI Build information](.pytool/Readme.md) + +# License Details + The majority of the content in the EDK II open source project uses a [BSD-2-Clause Plus Patent License](License.txt). The EDK II open source project contains the following components that are covered by additional licenses: From 3b0631e57e4b859221e585a9601c5c12152caaeb Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 11 Nov 2019 15:13:10 -0800 Subject: [PATCH 086/384] Readme.md: Update EDK II CI build status badge and links https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Update Readme.md with the status badges from the Azure Pipelines, tianocore organization, edk2-ci project https://dev.azure.com/tianocore/edk2-ci/_build * Windows VS2019 CI pipeline badges and results * Ubuntu GCC5 CI pipeline badges and results Cc: Sean Brogan Cc: Bret Barkelew Cc: Liming Gao Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Michael D Kinney Reviewed-by: Sean Brogan --- Readme.md | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/Readme.md b/Readme.md index dcd86daef14..acbcca88d3c 100644 --- a/Readme.md +++ b/Readme.md @@ -19,15 +19,15 @@ for the UEFI and PI specifications from www.uefi.org. VS2019 edk2-ci - - + + - - + + - + @@ -36,15 +36,15 @@ for the UEFI and PI specifications from www.uefi.org. GCC edk2-ci - - + + - - + + - + From e92b155740cdbf10a85ed8f37f69da0991fc8275 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 11 Nov 2019 17:39:28 -0800 Subject: [PATCH 087/384] Readme.md: Update EDK II CI build branch name https://bugzilla.tianocore.org/show_bug.cgi?id=2315 Update Readme.md to indicate that that status badges are for the edk2/master branch. Cc: Sean Brogan Cc: Bret Barkelew Cc: Liming Gao Cc: Andrew Fish Cc: Laszlo Ersek Cc: Leif Lindholm Signed-off-by: Michael D Kinney Reviewed-by: Sean Brogan --- Readme.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Readme.md b/Readme.md index acbcca88d3c..594f16b2075 100644 --- a/Readme.md +++ b/Readme.md @@ -17,7 +17,7 @@ for the UEFI and PI specifications from www.uefi.org. Windows VS2019 - edk2-ci + master @@ -34,7 +34,7 @@ for the UEFI and PI specifications from www.uefi.org. Ubuntu GCC - edk2-ci + master From bfcf262488a140550a53361c225a9b2b1bee0db8 Mon Sep 17 00:00:00 2001 From: "Tan, Ming" Date: Mon, 11 Nov 2019 15:18:50 +0800 Subject: [PATCH 088/384] EmulatorPkg/PlatformSmbiosDxe: fix a spell error of platform. Old code use platfomr. Change PlatfomrSmbiosDriverEntryPoint to PlatformSmbiosDriverEntryPoint. Signed-off-by: Ming Tan Reviewed-by: Ray Ni Reviewed-by: Liming Gao Reviewed-by: Philippe Mathieu-Daude --- EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.c | 2 +- EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.inf | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.c b/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.c index e6f87346002..48a3bfb5e97 100644 --- a/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.c +++ b/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.c @@ -82,7 +82,7 @@ CreatePlatformSmbiosMemoryRecords ( **/ EFI_STATUS EFIAPI -PlatfomrSmbiosDriverEntryPoint ( +PlatformSmbiosDriverEntryPoint ( IN EFI_HANDLE ImageHandle, IN EFI_SYSTEM_TABLE *SystemTable ) diff --git a/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.inf b/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.inf index 95b119e9530..756f643c740 100644 --- a/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.inf +++ b/EmulatorPkg/PlatformSmbiosDxe/PlatformSmbiosDxe.inf @@ -15,7 +15,7 @@ FILE_GUID = 67FA951E-4FA2-9F4E-A658-4DBD954AC22E MODULE_TYPE = DXE_DRIVER VERSION_STRING = 1.0 - ENTRY_POINT = PlatfomrSmbiosDriverEntryPoint + ENTRY_POINT = PlatformSmbiosDriverEntryPoint [Sources] From d847ac1f27cca3e78698559a7c96f5f5d115bc8b Mon Sep 17 00:00:00 2001 From: "Feng, Bob C" Date: Thu, 24 Oct 2019 08:35:44 +0800 Subject: [PATCH 089/384] BaseTools: Enable MACRO for DSC Components section tag BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2308 This patch is to enable MACRO for Components section architecture modifier. Cc: Liming Gao Signed-off-by: Bob Feng Reviewed-by: Liming Gao --- BaseTools/Source/Python/Workspace/MetaFileParser.py | 1 + 1 file changed, 1 insertion(+) diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTools/Source/Python/Workspace/MetaFileParser.py index 806fc322c56..0a131fc7698 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -328,6 +328,7 @@ def _SectionHeaderParser(self): S1 = ItemList[1].upper() else: S1 = TAB_ARCH_COMMON + S1 = ReplaceMacro(S1, self._Macros) ArchList.add(S1) # S2 may be Platform or ModuleType From 49fb9f7e06b92aa2f08cc7a24370a06a01b18f85 Mon Sep 17 00:00:00 2001 From: "Ni, Ray" Date: Tue, 12 Nov 2019 14:17:35 +0800 Subject: [PATCH 090/384] BaseTools: Fix build failure when using python38 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2304 Signed-off-by: Ray Ni Cc: Bob C Feng Cc: Liming Gao Reviewed-by: Bob Feng --- BaseTools/Source/Python/build/build.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index bcd832c525f..6c8798ef93f 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -2064,7 +2064,7 @@ def SetupMakeSetting(self,Wa): if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict: FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName] for FdRegion in FdDict.RegionList: - if str(FdRegion.RegionType) is 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList): + if str(FdRegion.RegionType) == 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList): if int(FdRegion.Offset) % 8 != 0: EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset)) Wa.FdfProfile = Fdf.Profile From 4b264fbcd091ba6817a95ad53ca59ad231e27d24 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Sun, 10 Nov 2019 23:10:55 -0800 Subject: [PATCH 091/384] Add the edk2-test requirement for CI building. --- .pytool/CISettings.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index ce177937e13..70ee2a066da 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -144,7 +144,13 @@ def GetName(self): return "Edk2" def GetDependencies(self): - return [] + return [ + { + "Path": "EDK2_TEST", + "Url": "https://github.com/corthon/edk2-test-1.git", + "Branch": "edk2-host-test_v2" + } + ] def GetPackagesPath(self): return () From a660814f6f7fd5135818a4fe91941f32eef71c24 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 11 Nov 2019 12:18:30 -0800 Subject: [PATCH 092/384] Make sure that all dependencies pull down for the unittesting. --- .gitignore | 3 +++ .pytool/CISettings.py | 5 +++-- 2 files changed, 6 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index 1dd30c14106..cbd304f066c 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,6 @@ Build/ __pycache__/ tags/ .vscode/ + +# Dependencies +EDK2_TEST/ diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 70ee2a066da..079fe064a30 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -6,6 +6,7 @@ import os import logging from edk2toolext.environment import shell_environment +from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager from edk2toolext.invocables.edk2_ci_build import CiBuildSettingsManager from edk2toolext.invocables.edk2_setup import SetupSettingsManager, RequiredSubmodule from edk2toolext.invocables.edk2_update import UpdateSettingsManager @@ -13,7 +14,7 @@ from edk2toollib.utility_functions import GetHostInfo -class Settings(CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): +class Settings(CiSetupSettingsManager, CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): def __init__(self): self.ActualPackages = [] @@ -117,7 +118,7 @@ def SetTargets(self, list_of_requested_target): def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' - scopes = ("cibuild","edk2-build") + scopes = ("cibuild","edk2-build","unittest") self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") From 9bb9bf96795f64ea203bfcd0cf739820eed1ed72 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 11 Nov 2019 16:08:01 -0800 Subject: [PATCH 093/384] Drop in the plugins to run everything. --- .../HostUnitTestCompilerPlugin.py | 147 ++++++++++++++++++ .../HostUnitTestCompiler_plug_in.yaml | 12 ++ .../HostUnitTestDscCompleteCheck.py | 122 +++++++++++++++ .../HostUnitTestDscCompleteCheck_plug_in.yaml | 12 ++ .../HostBasedUnitTestRunner.py | 80 ++++++++++ .../HostBasedUnitTestRunner_plug_in.yaml | 12 ++ MdePkg/MdePkg.ci.yaml | 8 +- MdePkg/MdePkgTest.dsc | 83 ++++++++++ 8 files changed, 475 insertions(+), 1 deletion(-) create mode 100644 .pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py create mode 100644 .pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml create mode 100644 .pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py create mode 100644 .pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml create mode 100644 BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py create mode 100644 BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml create mode 100644 MdePkg/MdePkgTest.dsc diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py new file mode 100644 index 00000000000..d61073820a0 --- /dev/null +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py @@ -0,0 +1,147 @@ +# @file HostUnitTestCompilerPlugin.py +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +import logging +import os +import re +from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser +from edk2toolext.environment.var_dict import VarDict +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toolext.environment.uefi_build import UefiBuilder +from edk2toolext import edk2_logging +from edk2toollib.utility_functions import GetHostInfo + + +class HostUnitTestCompilerPlugin(ICiBuildPlugin): + """ + A CiBuildPlugin that compiles the dsc for host based unit + test apps, runs them, and collects their results. + + Configuration options: + "HostUnitTestCompilerPlugin": { + "DscPath": "" + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + """ + num,types = self.__GetHostUnitTestArch(environment) + types = types.replace(" ", "_") + + return ("Compile and Run Host-Based UnitTests for " + packagename + " on arch " + types, + packagename + ".HostUnitTestCompiler." + types) + + def RunsOnTargetList(self): + return ["NOOPT"] + + # + # Find the intersection of application types that can run on this host + # and the TARGET_ARCH being build in this request. + # + # return tuple with (number of UEFI arch types, space separated string) + def __GetHostUnitTestArch(self, environment): + requested = environment.GetValue("TARGET_ARCH").split(' ') + host = [] + if GetHostInfo().arch == 'x86': + #assume 64bit can handle 64 and 32 + #assume 32bit can only handle 32 + ## change once IA32 issues resolved host.append("IA32") + if GetHostInfo().bit == '64': + host.append("X64") + elif GetHostInfo().arch == 'ARM': + if GetHostInfo().bit == '64': + host.append("AARCH64") + elif GetHostInfo().bit == '32': + host.append("ARM") + + willrun = set(requested) & set(host) + return (len(willrun), " ".join(willrun)) + + + ## + # External function of plugin. This function is used to perform the task of the ICiBuildPlugin Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - EnvConfig Object + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + self._env = environment + environment.SetValue("CI_BUILD_TYPE", "host_unit_test", "Set in HostUnitTestCompilerPlugin") + AP = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + + # Parse the config for required DscPath element + if "DscPath" not in pkgconfig: + tc.SetSkipped() + tc.LogStdError("DscPath not found in config file. Nothing to compile for HostBasedUnitTests.") + return -1 + + APDSC = os.path.join(AP, pkgconfig["DscPath"].strip()) + AP_Path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(APDSC) + if AP is None or AP_Path is None or not os.path.isfile(APDSC): + tc.SetSkipped() + tc.LogStdError("Package HostBasedUnitTest Dsc not found.") + return -1 + + logging.info("Building {0}".format(AP_Path)) + self._env.SetValue("ACTIVE_PLATFORM", AP_Path, "Set in Compiler Plugin") + num, RUNNABLE_ARCHITECTURES = self.__GetHostUnitTestArch(environment) + if(num == 0): + tc.SetSkipped() + tc.LogStdError("No host architecture compatibility") + return -1 + + if not environment.SetValue("TARGET_ARCH", + RUNNABLE_ARCHITECTURES, + "Update Target Arch based on Host Support"): + #use AllowOverride function since this is a controlled attempt to change + environment.AllowOverride("TARGET_ARCH") + if not environment.SetValue("TARGET_ARCH", + RUNNABLE_ARCHITECTURES, + "Update Target Arch based on Host Support"): + raise RuntimeError("Can't Change TARGET_ARCH as required") + + # Parse DSC to check for SUPPORTED_ARCHITECTURES + dp = DscParser() + dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) + dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp.ParseFile(AP_Path) + if "SUPPORTED_ARCHITECTURES" in dp.LocalVars: + SUPPORTED_ARCHITECTURES = dp.LocalVars["SUPPORTED_ARCHITECTURES"].split('|') + TARGET_ARCHITECTURES = environment.GetValue("TARGET_ARCH").split(' ') + + # Skip if there is no intersection between SUPPORTED_ARCHITECTURES and TARGET_ARCHITECTURES + if len(set(SUPPORTED_ARCHITECTURES) & set(TARGET_ARCHITECTURES)) == 0: + tc.SetSkipped() + tc.LogStdError("No supported architecutres to build for host unit tests") + return -1 + + uefiBuilder = UefiBuilder() + # do all the steps + # WorkSpace, PackagesPath, PInHelper, PInManager + ret = uefiBuilder.Go(Edk2pathObj.WorkspacePath, os.pathsep.join(Edk2pathObj.PackagePathList), PLMHelper, PLM) + if ret != 0: # failure: + tc.SetFailed("Compile failed for {0}".format(packagename), "Compile_FAILED") + tc.LogStdError("{0} Compile failed with error code {1} ".format(AP_Path, ret)) + return 1 + + else: + tc.SetSuccess() + return 0 diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml new file mode 100644 index 00000000000..271d86c1ab0 --- /dev/null +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml @@ -0,0 +1,12 @@ +## +# CiBuildPlugin used to build anything that identifies +# as a unit test. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "unittest", + "name": "Host Unit Test Compiler Plugin", + "module": "HostUnitTestCompilerPlugin" +} \ No newline at end of file diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py new file mode 100644 index 00000000000..182b42675b7 --- /dev/null +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py @@ -0,0 +1,122 @@ +# @file HostUnitTestDscCompleteCheck.py +# +# This is a copy of DscCompleteCheck with different filtering logic. +# It should be discussed if this should be one plugin +# +# Copyright (c) Microsoft Corporation. All rights reserved. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +import logging +import os +from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin +from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser +from edk2toollib.uefi.edk2.parsers.inf_parser import InfParser +from edk2toolext.environment.var_dict import VarDict + + +class HostUnitTestDscCompleteCheck(ICiBuildPlugin): + """ + A CiBuildPlugin that scans the package Host Unit Test dsc file and confirms all Host application modules (inf files) are + listed in the components sections. + + Configuration options: + "HostUnitTestDscCompleteCheck": { + "DscPath": "" + "IgnoreInf": [] # Ignore INF if found in filesystem by not dsc + } + """ + + def GetTestName(self, packagename: str, environment: VarDict) -> tuple: + """ Provide the testcase name and classname for use in reporting + + Args: + packagename: string containing name of package to build + environment: The VarDict for the test to run in + Returns: + a tuple containing the testcase name and the classname + (testcasename, classname) + testclassname: a descriptive string for the testcase can include whitespace + classname: should be patterned .. + """ + return ("Check the " + packagename + " Host Unit Test DSC for a being complete", packagename + ".HostUnitTestDscCompleteCheck") + + ## + # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # + # - package is the edk2 path to package. This means workspace/packagepath relative. + # - edk2path object configured with workspace and packages path + # - PkgConfig Object (dict) for the pkg + # - VarDict containing the shell environment Build Vars + # - Plugin Manager Instance + # - Plugin Helper Obj Instance + # - Junit Logger + # - output_stream the StringIO output stream from this plugin via logging + def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): + overall_status = 0 + + # Parse the config for required DscPath element + if "DscPath" not in pkgconfig: + tc.SetSkipped() + tc.LogStdError("DscPath not found in config file. Nothing to check.") + return -1 + + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) + wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) + + if abs_dsc_path is None or wsr_dsc_path is "" or not os.path.isfile(abs_dsc_path): + tc.SetSkipped() + tc.LogStdError("Package Host Unit Test Dsc not found") + return 0 + + # Get INF Files + INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] # make edk2relative path so can compare with DSC + + # remove ignores + + if "IgnoreInf" in pkgconfig: + for a in pkgconfig["IgnoreInf"]: + a = a.replace(os.sep, "/") + try: + tc.LogStdOut("Ignoring INF {0}".format(a)) + INFFiles.remove(a) + except: + tc.LogStdError("HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + logging.info("HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + + # DSC Parser + dp = DscParser() + dp.SetBaseAbsPath(Edk2pathObj.WorkspacePath) + dp.SetPackagePaths(Edk2pathObj.PackagePathList) + dp.SetInputVars(environment.GetAllBuildKeyValues()) + dp.ParseFile(wsr_dsc_path) + + # Check if INF in component section + for INF in INFFiles: + if not any(INF.strip() in x for x in dp.ThreeMods) and \ + not any(INF.strip() in x for x in dp.SixMods) and \ + not any(INF.strip() in x for x in dp.OtherMods): + + infp = InfParser().SetBaseAbsPath(Edk2pathObj.WorkspacePath) + infp.SetPackagePaths(Edk2pathObj.PackagePathList) + infp.ParseFile(INF) + if("MODULE_TYPE" not in infp.Dict): + tc.LogStdOut("Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) + continue + + if(infp.Dict["MODULE_TYPE"] != "HOST_APPLICATION"): + tc.LogStdOut("Ignoring INF. MODULE_TYPE is not HOST_APPLICATION {0}".format(INF)) + continue + + + logging.critical(INF + " not in " + wsr_dsc_path) + tc.LogStdError("{0} not in {1}".format(INF, wsr_dsc_path)) + overall_status = overall_status + 1 + + # If XML object exists, add result + if overall_status is not 0: + tc.SetFailed("HostUnitTestDscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") + else: + tc.SetSuccess() + return overall_status diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml new file mode 100644 index 00000000000..6cf86b0578b --- /dev/null +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml @@ -0,0 +1,12 @@ +## +# CiBuildPlugin used to confirm all INFs are listed in +# the components section of package dsc +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "unittest", + "name": "Host Unit Test Dsc Complete Check Test", + "module": "HostUnitTestDscCompleteCheck" + } \ No newline at end of file diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py new file mode 100644 index 00000000000..65c19116d13 --- /dev/null +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -0,0 +1,80 @@ +## @file HostBasedUnitTestRunner.py +# Plugin to located any host-based unit tests in the output directory and execute them. +## +# Copyright (c) Microsoft Corporation +# +## +import os +import logging +import glob +import xml.etree.ElementTree +from edk2toolext.environment.plugintypes.uefi_build_plugin import IUefiBuildPlugin +from edk2toolext import edk2_logging +import edk2toollib.windows.locate_tools as locate_tools +from edk2toolext.environment import shell_environment +from edk2toollib.utility_functions import RunCmd + + +class HostBasedUnitTestRunner(IUefiBuildPlugin): + + def do_post_build(self, thebuilder): + ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') + if ci_type != 'host_unit_test': + return 0 + + shell_env = shell_environment.GetEnvironment() + logging.log(edk2_logging.get_section_level(), "Run Host based Unit Tests") + path = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + for arch in thebuilder.env.GetValue("TARGET_ARCH").split(): + logging.log(edk2_logging.get_subsection_level(), "Testing for architecture: " + arch) + cp = os.path.join(path, arch) + + # If any old results XML files exist, clean them up. + for old_result in glob.iglob(os.path.join(cp, "*.result.xml")): + os.remove(old_result) + + # Determine whether any tests exist. + testList = glob.glob(os.path.join(cp, "*Test*.exe")) + for test in testList: + # Configure output name. + shell_env.set_shell_var('CMOCKA_XML_FILE', test + ".%g." + arch + ".result.xml") + + # Run the test. + ret = RunCmd('"' + test + '"', "", workingdir=cp) + if(ret != 0): + logging.error("UnitTest Execution Error: " + os.path.basename(test)) + else: + logging.info("UnitTest Completed: " + os.path.basename(test)) + file_match_pattern = test + ".*." + arch + ".result.xml" + xml_results_list = glob.glob(file_match_pattern) + for xml_result_file in xml_results_list: + root = xml.etree.ElementTree.parse(xml_result_file).getroot() + for suite in root: + for case in suite: + for result in case: + if result.tag == 'failure': + logging.warning("%s Test Failed" % os.path.basename(test)) + logging.warning(" %s - %s" % (case.attrib['name'], result.text)) + + return 0 + + def do_pre_build(self, thebuilder): + ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') + if ci_type != 'host_unit_test': + return 0 + + shell_env = shell_environment.GetEnvironment() + # Use the tools lib to determine the correct values for the vars that interest us. + interesting_keys = ["ExtensionSdkDir", "INCLUDE", "LIB", "LIBPATH", "UniversalCRTSdkDir", + "UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath", "WindowsSdkDir", "WindowsSdkVerBinPath", + "WindowsSDKVersion","VCToolsInstallDir"] + vs_vars = locate_tools.QueryVcVariables(interesting_keys, "amd64") + for (k,v) in vs_vars.items(): + if k.upper() == "PATH": + shell_env.append_path(v) + else: + shell_env.set_shell_var(k, v) + + # Set up the reporting type for Cmocka. + shell_env.set_shell_var('CMOCKA_MESSAGE_OUTPUT', 'xml') + return 0 \ No newline at end of file diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml new file mode 100644 index 00000000000..27fe4b028a1 --- /dev/null +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml @@ -0,0 +1,12 @@ +## +# CiBuildPlugin used to run any unittests that +# were built on this CI pass. +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "scope": "host-test-win", + "name": "Windows Host-Based Unit Test Runner", + "module": "HostBasedUnitTestRunner" +} \ No newline at end of file diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 65c4ec3becc..ea32f4ed225 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -11,7 +11,7 @@ }, ## options defined ci/Plugin/CharEncodingCheck -"CharEncodingCheck": { + "CharEncodingCheck": { "IgnoreFiles": [] }, @@ -33,6 +33,12 @@ "DscPath": "MdePkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [], + "DscPath": "MdePkgTest.dsc" + }, + ## options defined ci/Plugin/GuidCheck "GuidCheck": { "IgnoreGuidName": [ diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/MdePkgTest.dsc new file mode 100644 index 00000000000..e03beeb1a6c --- /dev/null +++ b/MdePkg/MdePkgTest.dsc @@ -0,0 +1,83 @@ +## @file MdePkgTest.dsc +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdePkg + PLATFORM_GUID = 50652B4C-88CB-4481-96E8-37F2D0034440 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdePkg + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = DEBUG|RELEASE + SKUID_IDENTIFIER = DEFAULT + FLASH_DEFINITION = MdePkg/MdePkgTest.fdf + + DEFINE UNIT_TEST_FRAMEWORK_MODE = HOST + DEFINE UNIT_TEST_XML_MODE = FALSE + +[PcdsFixedAtBuild] + !if $(UNIT_TEST_XML_MODE) == FALSE + gUefiHostUnitTestPkgTokenSpaceGuid.HostUnitTestMode|0x1 + !endif + +[LibraryClasses] + CmockaLib|CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf + + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + + BaseLib|MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf + BaseMemoryLib|MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf + DebugLib|MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf + DevicePathLib|MdePkg/HostLibrary/UefiDevicePathLibHost/UefiDevicePathLibHost.inf + DxeServicesTableLib|MdePkg/HostLibrary/DxeServicesTableLibHost/DxeServicesTableLibHost.inf + MemoryAllocationLib|MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + PeiServicesTablePointerLib|MdePkg/HostLibrary/PeiServicesTablePointerLibHost/PeiServicesTablePointerLibHost.inf + SmmServicesTableLib|MdePkg/HostLibrary/SmmServicesTableLibHost/SmmServicesTableLibHost.inf + UefiBootServicesTableLib|MdePkg/HostLibrary/UefiBootServicesTableLibHost/UefiBootServicesTableLibHost.inf + UefiRuntimeServicesTableLib|MdePkg/HostLibrary/UefiRuntimeServicesTableLibHost/UefiRuntimeServicesTableLibHost.inf + + OsServiceLib|UefiHostTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf + UnitTestAssertLib|CmockaHostUnitTestPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf + UnitTestLib|CmockaHostUnitTestPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf + +[Components] + + CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf { + + MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + + GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H + GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H + } + + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf + MdePkg/Test/UnitTest/Library/PeiServicesLib/TestPeiServicesLib.inf + MdePkg/Test/UnitTest/Library/DxeServicesTableLib/TestDxeServicesTableLib.inf + MdePkg/Test/UnitTest/Library/SmmServicesTableLib/TestSmmServicesTableLib.inf + MdePkg/Test/UnitTest/Library/UefiBootServicesTableLib/TestUefiBootServicesTableLib.inf + MdePkg/Test/UnitTest/Library/MemoryAllocationLib/TestMemoryAllocationLib.inf + MdePkg/Test/UnitTest/Library/UefiRuntimeServicesTableLib/TestUefiRuntimeServicesTableLib.inf + + MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibStatic.inf { + + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + + gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidStrAsc|"StrAsc"|VOID*|12 + gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidStrUni|L"StrUni"|VOID*|28 + gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidBufAll0|{0x0, 0x0, 0x0}|VOID*|5 + gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidBufAll1|{0xFF, 0xFF, 0xFF}|VOID*|5 + } + MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibDynamic.inf { + + PcdLib|MdePkg/HostLibrary/BasePcdLibHost/BasePcdLibHost.inf + } + +!include UefiHostUnitTestPkg/UefiHostUnitTestBuildOption.dsc \ No newline at end of file From 874a3ac3cac1ddd3c2a59614c41a07a3e77e736d Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 12 Nov 2019 18:44:39 -0800 Subject: [PATCH 094/384] Set up the rest of the things. --- .pytool/CISettings.py | 2 +- .../HostUnitTestCompiler_plug_in.yaml | 2 +- .../HostUnitTestDscCompleteCheck_plug_in.yaml | 2 +- .../BaseLibHost/BaseLibHostNoAsm.inf | 76 +++++++++++++++++++ MdePkg/MdePkg.ci.yaml | 9 ++- MdePkg/MdePkgTest.dsc | 24 +++++- 6 files changed, 107 insertions(+), 8 deletions(-) create mode 100644 MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 079fe064a30..e81dc1525fa 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -154,7 +154,7 @@ def GetDependencies(self): ] def GetPackagesPath(self): - return () + return ('EDK2_TEST',) def GetWorkspaceRoot(self): ''' get WorkspacePath ''' diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml index 271d86c1ab0..6c9fa9d6998 100644 --- a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompiler_plug_in.yaml @@ -6,7 +6,7 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## { - "scope": "unittest", + "scope": "host-based-test", "name": "Host Unit Test Compiler Plugin", "module": "HostUnitTestCompilerPlugin" } \ No newline at end of file diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml index 6cf86b0578b..a93e8f43c67 100644 --- a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck_plug_in.yaml @@ -6,7 +6,7 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## { - "scope": "unittest", + "scope": "host-based-test", "name": "Host Unit Test Dsc Complete Check Test", "module": "HostUnitTestDscCompleteCheck" } \ No newline at end of file diff --git a/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf b/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf new file mode 100644 index 00000000000..1652955ae89 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf @@ -0,0 +1,76 @@ +## @file +# +# this is a special build to pass KLEE build, because KLEE cannot use ASM. +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseLibHostNoAsm + FILE_GUID = 6DF0F6CC-DF9E-4644-8C1F-5A239B598E28 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = BaseLib | HOST_APPLICATION + +[Sources] + Math64.c + RShiftU64.c + LShiftU64.c + ARShiftU64.c + MultU64x64.c + MultS64x64.c + MultU64x32.c + DivS64x64Remainder.c + DivU64x64Remainder.c + DivU64x32Remainder.c + DivU64x32.c + ModU64x32.c + SwapBytes16.c + SwapBytes32.c + SwapBytes64.c + BitField.c + GetPowerOfTwo32.c + GetPowerOfTwo64.c + HighBitSet32.c + HighBitSet64.c + LowBitSet32.c + LowBitSet64.c + LRotU32.c + LRotU64.c + RRotU32.c + RRotU64.c + SafeString.c + String.c + CheckSum.c + CpuDeadLoop.c + LinkedList.c + Unaligned.c + SetJump.c + LongJump.c + X86MemoryFenceMsvc.c | MSFT + X86MemoryFenceGcc.c | GCC + CpuBreakpointMsvc.c | MSFT + CpuBreakpointGcc.c | GCC + Cpu.c + Cache.c + X86Cr.c + X86Dr.c + X86RdRand.c + X86PatchInstruction.c + X86GdtrNull.c + X86IdtrNull.c + X86SegmentNull.c + X86DisablePaging64Null.c + SwitchStackNull.c + DummyRdRand.c + DummyReadTsc.c + +[Packages] + MdePkg/MdePkg.dec + UefiHostTestPkg/UefiHostTestPkg.dec + +[LibraryClasses] + BaseMemoryLib diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index ea32f4ed225..0066d423059 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -10,6 +10,11 @@ "DscPath": "MdePkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "MdePkgTest.dsc" + }, + ## options defined ci/Plugin/CharEncodingCheck "CharEncodingCheck": { "IgnoreFiles": [] @@ -29,13 +34,13 @@ ## options defined ci/Plugin/DscCompleteCheck "DscCompleteCheck": { - "IgnoreInf": [], + "IgnoreInf": [""], "DscPath": "MdePkg.dsc" }, ## options defined ci/Plugin/HostUnitTestDscCompleteCheck "HostUnitTestDscCompleteCheck": { - "IgnoreInf": [], + "IgnoreInf": ["MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibDynamic.inf"], "DscPath": "MdePkgTest.dsc" }, diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/MdePkgTest.dsc index e03beeb1a6c..2f6086aca26 100644 --- a/MdePkg/MdePkgTest.dsc +++ b/MdePkg/MdePkgTest.dsc @@ -12,15 +12,15 @@ DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/MdePkg SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = DEBUG|RELEASE + BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT FLASH_DEFINITION = MdePkg/MdePkgTest.fdf - DEFINE UNIT_TEST_FRAMEWORK_MODE = HOST + DEFINE UNIT_TEST_FRAMEWORK_MODE = CMOCKA DEFINE UNIT_TEST_XML_MODE = FALSE [PcdsFixedAtBuild] - !if $(UNIT_TEST_XML_MODE) == FALSE + !if $(UNIT_TEST_XML_MODE) == TRUE gUefiHostUnitTestPkgTokenSpaceGuid.HostUnitTestMode|0x1 !endif @@ -80,4 +80,22 @@ PcdLib|MdePkg/HostLibrary/BasePcdLibHost/BasePcdLibHost.inf } + MdePkg/HostLibrary/BaseCacheMaintenanceLibHost/BaseCacheMaintenanceLibHost.inf + MdePkg/HostLibrary/BaseCpuLibHost/BaseCpuLibHost.inf + MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf + MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf + MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf + MdePkg/HostLibrary/BaseTimerLibHost/BaseTimerLibHost.inf + MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf + MdePkg/HostLibrary/DxeServicesTableLibHost/DxeServicesTableLibHost.inf + MdePkg/HostLibrary/HobLibHost/HobLibHost.inf + MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + MdePkg/HostLibrary/PeimEntryPointHost/PeimEntryPointHost.inf + MdePkg/HostLibrary/PeiServicesTablePointerLibHost/PeiServicesTablePointerLibHost.inf + MdePkg/HostLibrary/SmmMemLibHost/SmmMemLibHost.inf + MdePkg/HostLibrary/SmmServicesTableLibHost/SmmServicesTableLibHost.inf + MdePkg/HostLibrary/UefiBootServicesTableLibHost/UefiBootServicesTableLibHost.inf + MdePkg/HostLibrary/UefiLibHost/UefiLibHost.inf + MdePkg/HostLibrary/UefiRuntimeServicesTableLibHost/UefiRuntimeServicesTableLibHost.inf + !include UefiHostUnitTestPkg/UefiHostUnitTestBuildOption.dsc \ No newline at end of file From a4a039a3a8c5d6cd97146df2712a73d4a51e4df6 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 12 Nov 2019 18:44:53 -0800 Subject: [PATCH 095/384] Force the scope to a known configuration. --- .pytool/CISettings.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index e81dc1525fa..a9dea3b920a 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -118,7 +118,8 @@ def SetTargets(self, list_of_requested_target): def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' - scopes = ("cibuild","edk2-build","unittest") + # scopes = ("cibuild","edk2-build","host-based-test") + scopes = ("host-based-test",) self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") From 6d17c9c24aa6d5fd78795084e5822929a88720fb Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 11 Nov 2019 10:47:47 +0800 Subject: [PATCH 096/384] UefiCpuPkg/CpuCommonFeaturesLib: Remove XD enable/disable logic REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2329 XD (ExecutionDisable) feature, when turned on, allows page table entry BIT63 set to 1 indicating the memory pointed by the page table is disallowed to execute. DxeIpl::CreateIdentityMappingPageTables() enables the XD when CPU supports it. Later DxeCore modifies the page table to set the BIT63 to protect the stack/heap to disallow code execution in stack/heap. UefiCpuPkg/CpuCommonFeaturesLib enables/disables the XD feature according to PcdCpuFeaturesSetting. When XD is disabled, GP fault is generated immediately because some page entries have BIT63 set. To fix this issue, this patch removes the XD feature logic from UefiCpuPkg/CpuCommonFeaturesLib so the XD feature is only taken care of by DxeIpl. Signed-off-by: Ray Ni Reviewed-by: Eric Dong Acked-by: Laszlo Ersek --- .../CpuCommonFeaturesLib.c | 11 --- .../CpuCommonFeaturesLib.inf | 3 +- .../CpuCommonFeaturesLib/ExecuteDisable.c | 95 ------------------- 3 files changed, 1 insertion(+), 108 deletions(-) delete mode 100644 UefiCpuPkg/Library/CpuCommonFeaturesLib/ExecuteDisable.c diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.c b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.c index 238632f88af..3ebd9392a9e 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.c +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.c @@ -66,17 +66,6 @@ CpuCommonFeaturesLibConstructor ( ); ASSERT_EFI_ERROR (Status); } - if (IsCpuFeatureSupported (CPU_FEATURE_XD)) { - Status = RegisterCpuFeature ( - "Execute Disable", - NULL, - ExecuteDisableSupport, - ExecuteDisableInitialize, - CPU_FEATURE_XD, - CPU_FEATURE_END - ); - ASSERT_EFI_ERROR (Status); - } if (IsCpuFeatureSupported (CPU_FEATURE_FASTSTRINGS)) { Status = RegisterCpuFeature ( "FastStrings", diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf index 6347c8997d5..7fbcd8da0e5 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/CpuCommonFeaturesLib.inf @@ -4,7 +4,7 @@ # This library registers CPU features defined in Intel(R) 64 and IA-32 # Architectures Software Developer's Manual. # -# Copyright (c) 2017 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2017 - 2019, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -34,7 +34,6 @@ C1e.c ClockModulation.c Eist.c - ExecuteDisable.c FastStrings.c FeatureControl.c LimitCpuIdMaxval.c diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ExecuteDisable.c b/UefiCpuPkg/Library/CpuCommonFeaturesLib/ExecuteDisable.c deleted file mode 100644 index 75ea16309d6..00000000000 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/ExecuteDisable.c +++ /dev/null @@ -1,95 +0,0 @@ -/** @file - Execute Disable feature. - - Copyright (c) 2017, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include "CpuCommonFeatures.h" - -/** - Detects if Execute Disable feature supported on current processor. - - @param[in] ProcessorNumber The index of the CPU executing this function. - @param[in] CpuInfo A pointer to the REGISTER_CPU_FEATURE_INFORMATION - structure for the CPU executing this function. - @param[in] ConfigData A pointer to the configuration buffer returned - by CPU_FEATURE_GET_CONFIG_DATA. NULL if - CPU_FEATURE_GET_CONFIG_DATA was not provided in - RegisterCpuFeature(). - - @retval TRUE Execute Disable feature is supported. - @retval FALSE Execute Disable feature is not supported. - - @note This service could be called by BSP/APs. -**/ -BOOLEAN -EFIAPI -ExecuteDisableSupport ( - IN UINTN ProcessorNumber, - IN REGISTER_CPU_FEATURE_INFORMATION *CpuInfo, - IN VOID *ConfigData OPTIONAL - ) -{ - UINT32 Eax; - CPUID_EXTENDED_CPU_SIG_EDX Edx; - - AsmCpuid (CPUID_EXTENDED_FUNCTION, &Eax, NULL, NULL, NULL); - if (Eax <= CPUID_EXTENDED_FUNCTION) { - // - // Extended CPUID functions are not supported on this processor. - // - return FALSE; - } - - AsmCpuid (CPUID_EXTENDED_CPU_SIG, NULL, NULL, NULL, &Edx.Uint32); - return (Edx.Bits.NX != 0); -} - -/** - Initializes Execute Disable feature to specific state. - - @param[in] ProcessorNumber The index of the CPU executing this function. - @param[in] CpuInfo A pointer to the REGISTER_CPU_FEATURE_INFORMATION - structure for the CPU executing this function. - @param[in] ConfigData A pointer to the configuration buffer returned - by CPU_FEATURE_GET_CONFIG_DATA. NULL if - CPU_FEATURE_GET_CONFIG_DATA was not provided in - RegisterCpuFeature(). - @param[in] State If TRUE, then the Execute Disable feature must be enabled. - If FALSE, then the Execute Disable feature must be disabled. - - @retval RETURN_SUCCESS Execute Disable feature is initialized. - - @note This service could be called by BSP only. -**/ -RETURN_STATUS -EFIAPI -ExecuteDisableInitialize ( - IN UINTN ProcessorNumber, - IN REGISTER_CPU_FEATURE_INFORMATION *CpuInfo, - IN VOID *ConfigData, OPTIONAL - IN BOOLEAN State - ) -{ - // - // The scope of the MSR_IA32_EFER is core for below processor type, only program - // MSR_IA32_EFER for thread 0 in each core. - // - if (IS_SILVERMONT_PROCESSOR (CpuInfo->DisplayFamily, CpuInfo->DisplayModel)) { - if (CpuInfo->ProcessorInfo.Location.Thread != 0) { - return RETURN_SUCCESS; - } - } - - CPU_REGISTER_TABLE_WRITE_FIELD ( - ProcessorNumber, - Msr, - MSR_IA32_EFER, - MSR_IA32_EFER_REGISTER, - Bits.NXE, - (State) ? 1 : 0 - ); - return RETURN_SUCCESS; -} From c801f33d818b8010fabb93092c661c6f30d42b13 Mon Sep 17 00:00:00 2001 From: Ray Ni Date: Mon, 11 Nov 2019 11:05:48 +0800 Subject: [PATCH 097/384] UefiCpuPkg/RegisterCpuFeature: Remove CPU_FEATURE_XD macro REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2329 Signed-off-by: Ray Ni Reviewed-by: Eric Dong Acked-by: Laszlo Ersek --- UefiCpuPkg/Include/Library/RegisterCpuFeaturesLib.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UefiCpuPkg/Include/Library/RegisterCpuFeaturesLib.h b/UefiCpuPkg/Include/Library/RegisterCpuFeaturesLib.h index 5bd464b32e2..f370373d630 100644 --- a/UefiCpuPkg/Include/Library/RegisterCpuFeaturesLib.h +++ b/UefiCpuPkg/Include/Library/RegisterCpuFeaturesLib.h @@ -25,7 +25,7 @@ #define CPU_FEATURE_MWAIT 2 #define CPU_FEATURE_ACPI 3 #define CPU_FEATURE_EIST 4 -#define CPU_FEATURE_XD 5 +#define CPU_FEATURE_RESERVED_5 5 #define CPU_FEATURE_FASTSTRINGS 6 #define CPU_FEATURE_VMX 7 #define CPU_FEATURE_SMX 8 From 1bb27157f55a30a6f0469e196c576d8b777c1ac8 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Wed, 13 Nov 2019 00:08:47 -0800 Subject: [PATCH 098/384] Fix scopes so plugin runs Auto format plugin python code --- .pytool/CISettings.py | 11 ++++--- .../HostBasedUnitTestRunner.py | 32 ++++++++++++------- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index a9dea3b920a..e52620c0797 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -119,7 +119,7 @@ def SetTargets(self, list_of_requested_target): def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' # scopes = ("cibuild","edk2-build","host-based-test") - scopes = ("host-based-test",) + scopes = ("host-based-test", "host-test-win", "edk2-build") self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") @@ -135,7 +135,7 @@ def GetRequiredSubmodules(self): ''' return iterable containing RequiredSubmodule objects. If no RequiredSubmodules return an empty iterable ''' - rs=[] + rs = [] rs.append(RequiredSubmodule( "ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3", False)) rs.append(RequiredSubmodule( @@ -163,10 +163,11 @@ def GetWorkspaceRoot(self): def FilterPackagesToTest(self, changedFilesList: list, potentialPackagesList: list) -> list: ''' Filter potential packages to test based on changed files. ''' - build_these_packages=[] - possible_packages=potentialPackagesList.copy() + build_these_packages = [] + possible_packages = potentialPackagesList.copy() for f in changedFilesList: - nodes=f.split("/") # split each part of path for comparison later + # split each part of path for comparison later + nodes = f.split("/") # python file change in .pytool folder causes building all if f.endswith(".py") and ".pytool" in nodes: diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index 65c19116d13..2acc9ffdec3 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -1,4 +1,4 @@ -## @file HostBasedUnitTestRunner.py +# @file HostBasedUnitTestRunner.py # Plugin to located any host-based unit tests in the output directory and execute them. ## # Copyright (c) Microsoft Corporation @@ -23,10 +23,12 @@ def do_post_build(self, thebuilder): return 0 shell_env = shell_environment.GetEnvironment() - logging.log(edk2_logging.get_section_level(), "Run Host based Unit Tests") + logging.log(edk2_logging.get_section_level(), + "Run Host based Unit Tests") path = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") for arch in thebuilder.env.GetValue("TARGET_ARCH").split(): - logging.log(edk2_logging.get_subsection_level(), "Testing for architecture: " + arch) + logging.log(edk2_logging.get_subsection_level(), + "Testing for architecture: " + arch) cp = os.path.join(path, arch) # If any old results XML files exist, clean them up. @@ -37,24 +39,30 @@ def do_post_build(self, thebuilder): testList = glob.glob(os.path.join(cp, "*Test*.exe")) for test in testList: # Configure output name. - shell_env.set_shell_var('CMOCKA_XML_FILE', test + ".%g." + arch + ".result.xml") + shell_env.set_shell_var( + 'CMOCKA_XML_FILE', test + ".%g." + arch + ".result.xml") # Run the test. ret = RunCmd('"' + test + '"', "", workingdir=cp) if(ret != 0): - logging.error("UnitTest Execution Error: " + os.path.basename(test)) + logging.error("UnitTest Execution Error: " + + os.path.basename(test)) else: - logging.info("UnitTest Completed: " + os.path.basename(test)) + logging.info("UnitTest Completed: " + + os.path.basename(test)) file_match_pattern = test + ".*." + arch + ".result.xml" xml_results_list = glob.glob(file_match_pattern) for xml_result_file in xml_results_list: - root = xml.etree.ElementTree.parse(xml_result_file).getroot() + root = xml.etree.ElementTree.parse( + xml_result_file).getroot() for suite in root: for case in suite: for result in case: if result.tag == 'failure': - logging.warning("%s Test Failed" % os.path.basename(test)) - logging.warning(" %s - %s" % (case.attrib['name'], result.text)) + logging.warning( + "%s Test Failed" % os.path.basename(test)) + logging.warning( + " %s - %s" % (case.attrib['name'], result.text)) return 0 @@ -67,9 +75,9 @@ def do_pre_build(self, thebuilder): # Use the tools lib to determine the correct values for the vars that interest us. interesting_keys = ["ExtensionSdkDir", "INCLUDE", "LIB", "LIBPATH", "UniversalCRTSdkDir", "UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath", "WindowsSdkDir", "WindowsSdkVerBinPath", - "WindowsSDKVersion","VCToolsInstallDir"] + "WindowsSDKVersion", "VCToolsInstallDir"] vs_vars = locate_tools.QueryVcVariables(interesting_keys, "amd64") - for (k,v) in vs_vars.items(): + for (k, v) in vs_vars.items(): if k.upper() == "PATH": shell_env.append_path(v) else: @@ -77,4 +85,4 @@ def do_pre_build(self, thebuilder): # Set up the reporting type for Cmocka. shell_env.set_shell_var('CMOCKA_MESSAGE_OUTPUT', 'xml') - return 0 \ No newline at end of file + return 0 From a115e10cff2335cae4a5dd7b96ccbad4af99158d Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Wed, 13 Nov 2019 00:10:35 -0800 Subject: [PATCH 099/384] Add simple Test for safe int lib Add Host libs needed for basic usage. Update MdePkgTest.dsc to be minimal --- MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c | 44 + .../HostLibrary/BaseLibHost/BaseLibHost.inf | 79 + .../BaseLibHost/BaseLibHostNoAsm.inf | 1 - MdePkg/HostLibrary/BaseLibHost/BitField.c | 1004 +++++ MdePkg/HostLibrary/BaseLibHost/Cache.c | 40 + MdePkg/HostLibrary/BaseLibHost/CheckSum.c | 628 +++ MdePkg/HostLibrary/BaseLibHost/Cpu.c | 95 + .../BaseLibHost/CpuBreakpointGcc.c | 26 + .../BaseLibHost/CpuBreakpointMsvc.c | 35 + MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c | 32 + .../BaseLibHost/DivS64x64Remainder.c | 54 + MdePkg/HostLibrary/BaseLibHost/DivU64x32.c | 45 + .../BaseLibHost/DivU64x32Remainder.c | 50 + .../BaseLibHost/DivU64x64Remainder.c | 50 + MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c | 65 + MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c | 19 + .../HostLibrary/BaseLibHost/GetPowerOfTwo32.c | 37 + .../HostLibrary/BaseLibHost/GetPowerOfTwo64.c | 37 + MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c | 40 + MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c | 47 + .../HostLibrary/BaseLibHost/Ia32/RdRand.nasm | 84 + .../HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm | 31 + MdePkg/HostLibrary/BaseLibHost/LRotU32.c | 38 + MdePkg/HostLibrary/BaseLibHost/LRotU64.c | 45 + MdePkg/HostLibrary/BaseLibHost/LShiftU64.c | 44 + MdePkg/HostLibrary/BaseLibHost/Lfence.c | 10 + MdePkg/HostLibrary/BaseLibHost/LinkedList.c | 536 +++ MdePkg/HostLibrary/BaseLibHost/LongJump.c | 46 + MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c | 40 + MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c | 43 + MdePkg/HostLibrary/BaseLibHost/Math64.c | 364 ++ MdePkg/HostLibrary/BaseLibHost/ModU64x32.c | 45 + MdePkg/HostLibrary/BaseLibHost/MultS64x64.c | 35 + MdePkg/HostLibrary/BaseLibHost/MultU64x32.c | 46 + MdePkg/HostLibrary/BaseLibHost/MultU64x64.c | 46 + MdePkg/HostLibrary/BaseLibHost/RRotU32.c | 38 + MdePkg/HostLibrary/BaseLibHost/RRotU64.c | 45 + MdePkg/HostLibrary/BaseLibHost/RShiftU64.c | 44 + MdePkg/HostLibrary/BaseLibHost/SafeString.c | 3693 +++++++++++++++++ MdePkg/HostLibrary/BaseLibHost/SetJump.c | 54 + MdePkg/HostLibrary/BaseLibHost/String.c | 1163 ++++++ MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c | 31 + MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c | 37 + MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c | 37 + .../HostLibrary/BaseLibHost/SwitchStackNull.c | 52 + MdePkg/HostLibrary/BaseLibHost/Unaligned.c | 216 + .../HostLibrary/BaseLibHost/X64/RdRand.nasm | 77 + .../HostLibrary/BaseLibHost/X64/ReadTsc.nasm | 34 + MdePkg/HostLibrary/BaseLibHost/X86Cr.c | 180 + .../BaseLibHost/X86DisablePaging64Null.c | 53 + MdePkg/HostLibrary/BaseLibHost/X86Dr.c | 170 + MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c | 50 + MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c | 50 + .../BaseLibHost/X86MemoryFenceGcc.c | 29 + .../BaseLibHost/X86MemoryFenceMsvc.c | 27 + .../BaseLibHost/X86PatchInstruction.c | 84 + MdePkg/HostLibrary/BaseLibHost/X86RdRand.c | 121 + .../HostLibrary/BaseLibHost/X86SegmentNull.c | 163 + .../BaseMemoryLibHost/BaseMemoryLibHost.c | 160 + .../BaseMemoryLibHost/BaseMemoryLibHost.inf | 24 + .../HostLibrary/DebugLibHost/DebugLibHost.c | 182 + .../HostLibrary/DebugLibHost/DebugLibHost.inf | 30 + .../MemoryAllocationLibHost.c | 302 ++ .../MemoryAllocationLibHost.inf | 24 + MdePkg/MdePkgTest.dsc | 81 +- .../IA32/SafeIntLibUintnIntnUnitTests.c | 538 +++ .../BaseSafeIntLib/TestBaseSafeIntLib.c | 2911 +++++++++++++ .../BaseSafeIntLib/TestBaseSafeIntLib.h | 162 + .../BaseSafeIntLib/TestBaseSafeIntLib.inf | 59 + .../X64/SafeIntLibUintnIntnUnitTests.c | 542 +++ 70 files changed, 15286 insertions(+), 58 deletions(-) create mode 100644 MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf create mode 100644 MdePkg/HostLibrary/BaseLibHost/BitField.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Cache.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/CheckSum.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Cpu.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DivU64x32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm create mode 100644 MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm create mode 100644 MdePkg/HostLibrary/BaseLibHost/LRotU32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LRotU64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LShiftU64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Lfence.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LinkedList.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LongJump.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Math64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/ModU64x32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/MultS64x64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/MultU64x32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/MultU64x64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/RRotU32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/RRotU64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/RShiftU64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SafeString.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SetJump.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/String.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/Unaligned.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm create mode 100644 MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86Cr.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86Dr.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86RdRand.c create mode 100644 MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c create mode 100644 MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c create mode 100644 MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf create mode 100644 MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c create mode 100644 MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf create mode 100644 MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c create mode 100644 MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c diff --git a/MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c b/MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c new file mode 100644 index 00000000000..82aa010ea76 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c @@ -0,0 +1,44 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathARShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ); + +/** + Shifts a 64-bit integer right between 0 and 63 bits. The high bits are filled + with the original integer's bit 63. The shifted value is returned. + + This function shifts the 64-bit value Operand to the right by Count bits. The + high Count bits are set to bit 63 of Operand. The shifted value is returned. + + If Count is greater than 63, then ASSERT(). + + @param Operand The 64-bit operand to shift right. + @param Count The number of bits to shift right. + + @return Operand >> Count + +**/ +UINT64 +EFIAPI +ARShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 64); + return InternalMathARShiftU64 (Operand, Count); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf b/MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf new file mode 100644 index 00000000000..405d1ddab06 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf @@ -0,0 +1,79 @@ +## @file +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseLibHost + FILE_GUID = FA4A8DE0-8D55-44AA-8368-07D24BDA6A7D + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = BaseLib | HOST_APPLICATION + +[Sources] + Math64.c + RShiftU64.c + LShiftU64.c + ARShiftU64.c + MultU64x64.c + MultS64x64.c + MultU64x32.c + DivS64x64Remainder.c + DivU64x64Remainder.c + DivU64x32Remainder.c + DivU64x32.c + ModU64x32.c + SwapBytes16.c + SwapBytes32.c + SwapBytes64.c + BitField.c + GetPowerOfTwo32.c + GetPowerOfTwo64.c + HighBitSet32.c + HighBitSet64.c + LowBitSet32.c + LowBitSet64.c + LRotU32.c + LRotU64.c + RRotU32.c + RRotU64.c + SafeString.c + String.c + CheckSum.c + CpuDeadLoop.c + LinkedList.c + Unaligned.c + SetJump.c + LongJump.c + X86MemoryFenceMsvc.c | MSFT + X86MemoryFenceGcc.c | GCC + CpuBreakpointMsvc.c | MSFT + CpuBreakpointGcc.c | GCC + Cpu.c + Cache.c + X86Cr.c + X86Dr.c + X86RdRand.c + X86PatchInstruction.c + X86GdtrNull.c + X86IdtrNull.c + X86SegmentNull.c + X86DisablePaging64Null.c + SwitchStackNull.c + +[Sources.Ia32] + Ia32/RdRand.nasm + Ia32/ReadTsc.nasm + +[Sources.X64] + X64/RdRand.nasm + X64/ReadTsc.nasm + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseMemoryLib diff --git a/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf b/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf index 1652955ae89..9de6c389c9b 100644 --- a/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf +++ b/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf @@ -70,7 +70,6 @@ [Packages] MdePkg/MdePkg.dec - UefiHostTestPkg/UefiHostTestPkg.dec [LibraryClasses] BaseMemoryLib diff --git a/MdePkg/HostLibrary/BaseLibHost/BitField.c b/MdePkg/HostLibrary/BaseLibHost/BitField.c new file mode 100644 index 00000000000..8d044e0e742 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/BitField.c @@ -0,0 +1,1004 @@ +/** @file + Bit field functions of BaseLib. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Worker function that returns a bit field from Operand. + + Returns the bitfield specified by the StartBit and the EndBit from Operand. + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + @param EndBit The ordinal of the most significant bit in the bit field. + + @return The bit field read. + +**/ +UINTN +EFIAPI +InternalBaseLibBitFieldReadUint ( + IN UINTN Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + // + // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] + // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. + // + return (Operand & ~((UINTN)-2 << EndBit)) >> StartBit; +} + +/** + Worker function that reads a bit field from Operand, performs a bitwise OR, + and returns the result. + + Performs a bitwise OR between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new value is returned. + + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + @param EndBit The ordinal of the most significant bit in the bit field. + @param OrData The value to OR with the read value from the value. + + @return The new value. + +**/ +UINTN +EFIAPI +InternalBaseLibBitFieldOrUint ( + IN UINTN Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINTN OrData + ) +{ + // + // Higher bits in OrData those are not used must be zero. + // + // EndBit - StartBit + 1 might be 32 while the result right shifting 32 on a 32bit integer is undefined, + // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. + // + ASSERT ((OrData >> (EndBit - StartBit)) == ((OrData >> (EndBit - StartBit)) & 1)); + + // + // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] + // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. + // + return Operand | ((OrData << StartBit) & ~((UINTN) -2 << EndBit)); +} + +/** + Worker function that reads a bit field from Operand, performs a bitwise AND, + and returns the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new value is returned. + + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + @param EndBit The ordinal of the most significant bit in the bit field. + @param AndData The value to And with the read value from the value. + + @return The new value. + +**/ +UINTN +EFIAPI +InternalBaseLibBitFieldAndUint ( + IN UINTN Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINTN AndData + ) +{ + // + // Higher bits in AndData those are not used must be zero. + // + // EndBit - StartBit + 1 might be 32 while the result right shifting 32 on a 32bit integer is undefined, + // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. + // + ASSERT ((AndData >> (EndBit - StartBit)) == ((AndData >> (EndBit - StartBit)) & 1)); + + // + // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] + // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. + // + return Operand & ~((~AndData << StartBit) & ~((UINTN)-2 << EndBit)); +} + +/** + Returns a bit field from an 8-bit value. + + Returns the bitfield specified by the StartBit and the EndBit from Operand. + + If 8-bit operations are not supported, then ASSERT(). + If StartBit is greater than 7, then ASSERT(). + If EndBit is greater than 7, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..7. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..7. + + @return The bit field read. + +**/ +UINT8 +EFIAPI +BitFieldRead8 ( + IN UINT8 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + ASSERT (EndBit < 8); + ASSERT (StartBit <= EndBit); + return (UINT8)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); +} + +/** + Writes a bit field to an 8-bit value, and returns the result. + + Writes Value to the bit field specified by the StartBit and the EndBit in + Operand. All other bits in Operand are preserved. The new 8-bit value is + returned. + + If 8-bit operations are not supported, then ASSERT(). + If StartBit is greater than 7, then ASSERT(). + If EndBit is greater than 7, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..7. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..7. + @param Value The new value of the bit field. + + @return The new 8-bit value. + +**/ +UINT8 +EFIAPI +BitFieldWrite8 ( + IN UINT8 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 Value + ) +{ + ASSERT (EndBit < 8); + ASSERT (StartBit <= EndBit); + return BitFieldAndThenOr8 (Operand, StartBit, EndBit, 0, Value); +} + +/** + Reads a bit field from an 8-bit value, performs a bitwise OR, and returns the + result. + + Performs a bitwise OR between the bit field specified by StartBit + and EndBit in Operand and the value specified by OrData. All other bits in + Operand are preserved. The new 8-bit value is returned. + + If 8-bit operations are not supported, then ASSERT(). + If StartBit is greater than 7, then ASSERT(). + If EndBit is greater than 7, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..7. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..7. + @param OrData The value to OR with the read value from the value. + + @return The new 8-bit value. + +**/ +UINT8 +EFIAPI +BitFieldOr8 ( + IN UINT8 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 OrData + ) +{ + ASSERT (EndBit < 8); + ASSERT (StartBit <= EndBit); + return (UINT8)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); +} + +/** + Reads a bit field from an 8-bit value, performs a bitwise AND, and returns + the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new 8-bit value is returned. + + If 8-bit operations are not supported, then ASSERT(). + If StartBit is greater than 7, then ASSERT(). + If EndBit is greater than 7, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..7. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..7. + @param AndData The value to AND with the read value from the value. + + @return The new 8-bit value. + +**/ +UINT8 +EFIAPI +BitFieldAnd8 ( + IN UINT8 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 AndData + ) +{ + ASSERT (EndBit < 8); + ASSERT (StartBit <= EndBit); + return (UINT8)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); +} + +/** + Reads a bit field from an 8-bit value, performs a bitwise AND followed by a + bitwise OR, and returns the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData, followed by a bitwise + OR with value specified by OrData. All other bits in Operand are + preserved. The new 8-bit value is returned. + + If 8-bit operations are not supported, then ASSERT(). + If StartBit is greater than 7, then ASSERT(). + If EndBit is greater than 7, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..7. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..7. + @param AndData The value to AND with the read value from the value. + @param OrData The value to OR with the result of the AND operation. + + @return The new 8-bit value. + +**/ +UINT8 +EFIAPI +BitFieldAndThenOr8 ( + IN UINT8 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT8 AndData, + IN UINT8 OrData + ) +{ + ASSERT (EndBit < 8); + ASSERT (StartBit <= EndBit); + return BitFieldOr8 ( + BitFieldAnd8 (Operand, StartBit, EndBit, AndData), + StartBit, + EndBit, + OrData + ); +} + +/** + Returns a bit field from a 16-bit value. + + Returns the bitfield specified by the StartBit and the EndBit from Operand. + + If 16-bit operations are not supported, then ASSERT(). + If StartBit is greater than 15, then ASSERT(). + If EndBit is greater than 15, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..15. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..15. + + @return The bit field read. + +**/ +UINT16 +EFIAPI +BitFieldRead16 ( + IN UINT16 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + ASSERT (EndBit < 16); + ASSERT (StartBit <= EndBit); + return (UINT16)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); +} + +/** + Writes a bit field to a 16-bit value, and returns the result. + + Writes Value to the bit field specified by the StartBit and the EndBit in + Operand. All other bits in Operand are preserved. The new 16-bit value is + returned. + + If 16-bit operations are not supported, then ASSERT(). + If StartBit is greater than 15, then ASSERT(). + If EndBit is greater than 15, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..15. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..15. + @param Value The new value of the bit field. + + @return The new 16-bit value. + +**/ +UINT16 +EFIAPI +BitFieldWrite16 ( + IN UINT16 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 Value + ) +{ + ASSERT (EndBit < 16); + ASSERT (StartBit <= EndBit); + return BitFieldAndThenOr16 (Operand, StartBit, EndBit, 0, Value); +} + +/** + Reads a bit field from a 16-bit value, performs a bitwise OR, and returns the + result. + + Performs a bitwise OR between the bit field specified by StartBit + and EndBit in Operand and the value specified by OrData. All other bits in + Operand are preserved. The new 16-bit value is returned. + + If 16-bit operations are not supported, then ASSERT(). + If StartBit is greater than 15, then ASSERT(). + If EndBit is greater than 15, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..15. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..15. + @param OrData The value to OR with the read value from the value. + + @return The new 16-bit value. + +**/ +UINT16 +EFIAPI +BitFieldOr16 ( + IN UINT16 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 OrData + ) +{ + ASSERT (EndBit < 16); + ASSERT (StartBit <= EndBit); + return (UINT16)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); +} + +/** + Reads a bit field from a 16-bit value, performs a bitwise AND, and returns + the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new 16-bit value is returned. + + If 16-bit operations are not supported, then ASSERT(). + If StartBit is greater than 15, then ASSERT(). + If EndBit is greater than 15, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..15. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..15. + @param AndData The value to AND with the read value from the value. + + @return The new 16-bit value. + +**/ +UINT16 +EFIAPI +BitFieldAnd16 ( + IN UINT16 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 AndData + ) +{ + ASSERT (EndBit < 16); + ASSERT (StartBit <= EndBit); + return (UINT16)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); +} + +/** + Reads a bit field from a 16-bit value, performs a bitwise AND followed by a + bitwise OR, and returns the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData, followed by a bitwise + OR with value specified by OrData. All other bits in Operand are + preserved. The new 16-bit value is returned. + + If 16-bit operations are not supported, then ASSERT(). + If StartBit is greater than 15, then ASSERT(). + If EndBit is greater than 15, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..15. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..15. + @param AndData The value to AND with the read value from the value. + @param OrData The value to OR with the result of the AND operation. + + @return The new 16-bit value. + +**/ +UINT16 +EFIAPI +BitFieldAndThenOr16 ( + IN UINT16 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT16 AndData, + IN UINT16 OrData + ) +{ + ASSERT (EndBit < 16); + ASSERT (StartBit <= EndBit); + return BitFieldOr16 ( + BitFieldAnd16 (Operand, StartBit, EndBit, AndData), + StartBit, + EndBit, + OrData + ); +} + +/** + Returns a bit field from a 32-bit value. + + Returns the bitfield specified by the StartBit and the EndBit from Operand. + + If 32-bit operations are not supported, then ASSERT(). + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + + @return The bit field read. + +**/ +UINT32 +EFIAPI +BitFieldRead32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + return (UINT32)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); +} + +/** + Writes a bit field to a 32-bit value, and returns the result. + + Writes Value to the bit field specified by the StartBit and the EndBit in + Operand. All other bits in Operand are preserved. The new 32-bit value is + returned. + + If 32-bit operations are not supported, then ASSERT(). + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + @param Value The new value of the bit field. + + @return The new 32-bit value. + +**/ +UINT32 +EFIAPI +BitFieldWrite32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 Value + ) +{ + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + return BitFieldAndThenOr32 (Operand, StartBit, EndBit, 0, Value); +} + +/** + Reads a bit field from a 32-bit value, performs a bitwise OR, and returns the + result. + + Performs a bitwise OR between the bit field specified by StartBit + and EndBit in Operand and the value specified by OrData. All other bits in + Operand are preserved. The new 32-bit value is returned. + + If 32-bit operations are not supported, then ASSERT(). + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + @param OrData The value to OR with the read value from the value. + + @return The new 32-bit value. + +**/ +UINT32 +EFIAPI +BitFieldOr32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 OrData + ) +{ + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + return (UINT32)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); +} + +/** + Reads a bit field from a 32-bit value, performs a bitwise AND, and returns + the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new 32-bit value is returned. + + If 32-bit operations are not supported, then ASSERT(). + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + @param AndData The value to AND with the read value from the value. + + @return The new 32-bit value. + +**/ +UINT32 +EFIAPI +BitFieldAnd32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 AndData + ) +{ + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + return (UINT32)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); +} + +/** + Reads a bit field from a 32-bit value, performs a bitwise AND followed by a + bitwise OR, and returns the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData, followed by a bitwise + OR with value specified by OrData. All other bits in Operand are + preserved. The new 32-bit value is returned. + + If 32-bit operations are not supported, then ASSERT(). + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + @param AndData The value to AND with the read value from the value. + @param OrData The value to OR with the result of the AND operation. + + @return The new 32-bit value. + +**/ +UINT32 +EFIAPI +BitFieldAndThenOr32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT32 AndData, + IN UINT32 OrData + ) +{ + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + return BitFieldOr32 ( + BitFieldAnd32 (Operand, StartBit, EndBit, AndData), + StartBit, + EndBit, + OrData + ); +} + +/** + Returns a bit field from a 64-bit value. + + Returns the bitfield specified by the StartBit and the EndBit from Operand. + + If 64-bit operations are not supported, then ASSERT(). + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + + @return The bit field read. + +**/ +UINT64 +EFIAPI +BitFieldRead64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + return RShiftU64 (Operand & ~LShiftU64 ((UINT64)-2, EndBit), StartBit); +} + +/** + Writes a bit field to a 64-bit value, and returns the result. + + Writes Value to the bit field specified by the StartBit and the EndBit in + Operand. All other bits in Operand are preserved. The new 64-bit value is + returned. + + If 64-bit operations are not supported, then ASSERT(). + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + @param Value The new value of the bit field. + + @return The new 64-bit value. + +**/ +UINT64 +EFIAPI +BitFieldWrite64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT64 Value + ) +{ + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + return BitFieldAndThenOr64 (Operand, StartBit, EndBit, 0, Value); +} + +/** + Reads a bit field from a 64-bit value, performs a bitwise OR, and returns the + result. + + Performs a bitwise OR between the bit field specified by StartBit + and EndBit in Operand and the value specified by OrData. All other bits in + Operand are preserved. The new 64-bit value is returned. + + If 64-bit operations are not supported, then ASSERT(). + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + @param OrData The value to OR with the read value from the value + + @return The new 64-bit value. + +**/ +UINT64 +EFIAPI +BitFieldOr64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT64 OrData + ) +{ + UINT64 Value1; + UINT64 Value2; + + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + // + // Higher bits in OrData those are not used must be zero. + // + // EndBit - StartBit + 1 might be 64 while the result right shifting 64 on RShiftU64() API is invalid, + // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. + // + ASSERT (RShiftU64 (OrData, EndBit - StartBit) == (RShiftU64 (OrData, EndBit - StartBit) & 1)); + + Value1 = LShiftU64 (OrData, StartBit); + Value2 = LShiftU64 ((UINT64) - 2, EndBit); + + return Operand | (Value1 & ~Value2); +} + +/** + Reads a bit field from a 64-bit value, performs a bitwise AND, and returns + the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData. All other bits in Operand are + preserved. The new 64-bit value is returned. + + If 64-bit operations are not supported, then ASSERT(). + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + @param AndData The value to AND with the read value from the value. + + @return The new 64-bit value. + +**/ +UINT64 +EFIAPI +BitFieldAnd64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT64 AndData + ) +{ + UINT64 Value1; + UINT64 Value2; + + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + // + // Higher bits in AndData those are not used must be zero. + // + // EndBit - StartBit + 1 might be 64 while the right shifting 64 on RShiftU64() API is invalid, + // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. + // + ASSERT (RShiftU64 (AndData, EndBit - StartBit) == (RShiftU64 (AndData, EndBit - StartBit) & 1)); + + Value1 = LShiftU64 (~AndData, StartBit); + Value2 = LShiftU64 ((UINT64)-2, EndBit); + + return Operand & ~(Value1 & ~Value2); +} + +/** + Reads a bit field from a 64-bit value, performs a bitwise AND followed by a + bitwise OR, and returns the result. + + Performs a bitwise AND between the bit field specified by StartBit and EndBit + in Operand and the value specified by AndData, followed by a bitwise + OR with value specified by OrData. All other bits in Operand are + preserved. The new 64-bit value is returned. + + If 64-bit operations are not supported, then ASSERT(). + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + @param AndData The value to AND with the read value from the value. + @param OrData The value to OR with the result of the AND operation. + + @return The new 64-bit value. + +**/ +UINT64 +EFIAPI +BitFieldAndThenOr64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit, + IN UINT64 AndData, + IN UINT64 OrData + ) +{ + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + return BitFieldOr64 ( + BitFieldAnd64 (Operand, StartBit, EndBit, AndData), + StartBit, + EndBit, + OrData + ); +} + +/** + Reads a bit field from a 32-bit value, counts and returns + the number of set bits. + + Counts the number of set bits in the bit field specified by + StartBit and EndBit in Operand. The count is returned. + + If StartBit is greater than 31, then ASSERT(). + If EndBit is greater than 31, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..31. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..31. + + @return The number of bits set between StartBit and EndBit. + +**/ +UINT8 +EFIAPI +BitFieldCountOnes32 ( + IN UINT32 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + UINT32 Count; + + ASSERT (EndBit < 32); + ASSERT (StartBit <= EndBit); + + Count = BitFieldRead32 (Operand, StartBit, EndBit); + Count -= ((Count >> 1) & 0x55555555); + Count = (Count & 0x33333333) + ((Count >> 2) & 0x33333333); + Count += Count >> 4; + Count &= 0x0F0F0F0F; + Count += Count >> 8; + Count += Count >> 16; + + return (UINT8) Count & 0x3F; +} + +/** + Reads a bit field from a 64-bit value, counts and returns + the number of set bits. + + Counts the number of set bits in the bit field specified by + StartBit and EndBit in Operand. The count is returned. + + If StartBit is greater than 63, then ASSERT(). + If EndBit is greater than 63, then ASSERT(). + If EndBit is less than StartBit, then ASSERT(). + + @param Operand Operand on which to perform the bitfield operation. + @param StartBit The ordinal of the least significant bit in the bit field. + Range 0..63. + @param EndBit The ordinal of the most significant bit in the bit field. + Range 0..63. + + @return The number of bits set between StartBit and EndBit. + +**/ +UINT8 +EFIAPI +BitFieldCountOnes64 ( + IN UINT64 Operand, + IN UINTN StartBit, + IN UINTN EndBit + ) +{ + UINT64 BitField; + UINT8 Count; + + ASSERT (EndBit < 64); + ASSERT (StartBit <= EndBit); + + BitField = BitFieldRead64 (Operand, StartBit, EndBit); + Count = BitFieldCountOnes32 ((UINT32) BitField, 0, 31); + Count += BitFieldCountOnes32 ((UINT32) RShiftU64(BitField, 32), 0, 31); + + return Count; +} + diff --git a/MdePkg/HostLibrary/BaseLibHost/Cache.c b/MdePkg/HostLibrary/BaseLibHost/Cache.c new file mode 100644 index 00000000000..ff787e3f24f --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Cache.c @@ -0,0 +1,40 @@ +/** @file + Base Library CPU Functions for all architectures. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +/** + Set CD bit and clear NW bit of CR0 followed by a WBINVD. + + Disables the caches by setting the CD bit of CR0 to 1, clearing the NW bit of CR0 to 0, + and executing a WBINVD instruction. This function is only available on IA-32 and x64. + +**/ +VOID +EFIAPI +AsmDisableCache ( + VOID + ) +{ +} + + +/** + Perform a WBINVD and clear both the CD and NW bits of CR0. + + Enables the caches by executing a WBINVD instruction and then clear both the CD and NW + bits of CR0 to 0. This function is only available on IA-32 and x64. + +**/ +VOID +EFIAPI +AsmEnableCache ( + VOID + ) +{ +} diff --git a/MdePkg/HostLibrary/BaseLibHost/CheckSum.c b/MdePkg/HostLibrary/BaseLibHost/CheckSum.c new file mode 100644 index 00000000000..0dd3cc95c2d --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/CheckSum.c @@ -0,0 +1,628 @@ +/** @file + Utility functions to generate checksum based on 2's complement + algorithm. + + Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the sum of all elements in a buffer in unit of UINT8. + During calculation, the carry bits are dropped. + + This function calculates the sum of all elements in a buffer + in unit of UINT8. The carry bits in result of addition are dropped. + The result is returned as UINT8. If Length is Zero, then Zero is + returned. + + If Buffer is NULL, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the sum operation. + @param Length The size, in bytes, of Buffer. + + @return Sum The sum of Buffer with carry bits dropped during additions. + +**/ +UINT8 +EFIAPI +CalculateSum8 ( + IN CONST UINT8 *Buffer, + IN UINTN Length + ) +{ + UINT8 Sum; + UINTN Count; + + ASSERT (Buffer != NULL); + ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); + + for (Sum = 0, Count = 0; Count < Length; Count++) { + Sum = (UINT8) (Sum + *(Buffer + Count)); + } + + return Sum; +} + + +/** + Returns the two's complement checksum of all elements in a buffer + of 8-bit values. + + This function first calculates the sum of the 8-bit values in the + buffer specified by Buffer and Length. The carry bits in the result + of addition are dropped. Then, the two's complement of the sum is + returned. If Length is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the checksum operation. + @param Length The size, in bytes, of Buffer. + + @return Checksum The 2's complement checksum of Buffer. + +**/ +UINT8 +EFIAPI +CalculateCheckSum8 ( + IN CONST UINT8 *Buffer, + IN UINTN Length + ) +{ + UINT8 CheckSum; + + CheckSum = CalculateSum8 (Buffer, Length); + + // + // Return the checksum based on 2's complement. + // + return (UINT8) (0x100 - CheckSum); +} + +/** + Returns the sum of all elements in a buffer of 16-bit values. During + calculation, the carry bits are dropped. + + This function calculates the sum of the 16-bit values in the buffer + specified by Buffer and Length. The carry bits in result of addition are dropped. + The 16-bit result is returned. If Length is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 16-bit boundary, then ASSERT(). + If Length is not aligned on a 16-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the sum operation. + @param Length The size, in bytes, of Buffer. + + @return Sum The sum of Buffer with carry bits dropped during additions. + +**/ +UINT16 +EFIAPI +CalculateSum16 ( + IN CONST UINT16 *Buffer, + IN UINTN Length + ) +{ + UINT16 Sum; + UINTN Count; + UINTN Total; + + ASSERT (Buffer != NULL); + ASSERT (((UINTN) Buffer & 0x1) == 0); + ASSERT ((Length & 0x1) == 0); + ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); + + Total = Length / sizeof (*Buffer); + for (Sum = 0, Count = 0; Count < Total; Count++) { + Sum = (UINT16) (Sum + *(Buffer + Count)); + } + + return Sum; +} + + +/** + Returns the two's complement checksum of all elements in a buffer of + 16-bit values. + + This function first calculates the sum of the 16-bit values in the buffer + specified by Buffer and Length. The carry bits in the result of addition + are dropped. Then, the two's complement of the sum is returned. If Length + is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 16-bit boundary, then ASSERT(). + If Length is not aligned on a 16-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the checksum operation. + @param Length The size, in bytes, of Buffer. + + @return Checksum The 2's complement checksum of Buffer. + +**/ +UINT16 +EFIAPI +CalculateCheckSum16 ( + IN CONST UINT16 *Buffer, + IN UINTN Length + ) +{ + UINT16 CheckSum; + + CheckSum = CalculateSum16 (Buffer, Length); + + // + // Return the checksum based on 2's complement. + // + return (UINT16) (0x10000 - CheckSum); +} + + +/** + Returns the sum of all elements in a buffer of 32-bit values. During + calculation, the carry bits are dropped. + + This function calculates the sum of the 32-bit values in the buffer + specified by Buffer and Length. The carry bits in result of addition are dropped. + The 32-bit result is returned. If Length is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 32-bit boundary, then ASSERT(). + If Length is not aligned on a 32-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the sum operation. + @param Length The size, in bytes, of Buffer. + + @return Sum The sum of Buffer with carry bits dropped during additions. + +**/ +UINT32 +EFIAPI +CalculateSum32 ( + IN CONST UINT32 *Buffer, + IN UINTN Length + ) +{ + UINT32 Sum; + UINTN Count; + UINTN Total; + + ASSERT (Buffer != NULL); + ASSERT (((UINTN) Buffer & 0x3) == 0); + ASSERT ((Length & 0x3) == 0); + ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); + + Total = Length / sizeof (*Buffer); + for (Sum = 0, Count = 0; Count < Total; Count++) { + Sum = Sum + *(Buffer + Count); + } + + return Sum; +} + + +/** + Returns the two's complement checksum of all elements in a buffer of + 32-bit values. + + This function first calculates the sum of the 32-bit values in the buffer + specified by Buffer and Length. The carry bits in the result of addition + are dropped. Then, the two's complement of the sum is returned. If Length + is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 32-bit boundary, then ASSERT(). + If Length is not aligned on a 32-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the checksum operation. + @param Length The size, in bytes, of Buffer. + + @return Checksum The 2's complement checksum of Buffer. + +**/ +UINT32 +EFIAPI +CalculateCheckSum32 ( + IN CONST UINT32 *Buffer, + IN UINTN Length + ) +{ + UINT32 CheckSum; + + CheckSum = CalculateSum32 (Buffer, Length); + + // + // Return the checksum based on 2's complement. + // + return (UINT32) ((UINT32)(-1) - CheckSum + 1); +} + + +/** + Returns the sum of all elements in a buffer of 64-bit values. During + calculation, the carry bits are dropped. + + This function calculates the sum of the 64-bit values in the buffer + specified by Buffer and Length. The carry bits in result of addition are dropped. + The 64-bit result is returned. If Length is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 64-bit boundary, then ASSERT(). + If Length is not aligned on a 64-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the sum operation. + @param Length The size, in bytes, of Buffer. + + @return Sum The sum of Buffer with carry bits dropped during additions. + +**/ +UINT64 +EFIAPI +CalculateSum64 ( + IN CONST UINT64 *Buffer, + IN UINTN Length + ) +{ + UINT64 Sum; + UINTN Count; + UINTN Total; + + ASSERT (Buffer != NULL); + ASSERT (((UINTN) Buffer & 0x7) == 0); + ASSERT ((Length & 0x7) == 0); + ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); + + Total = Length / sizeof (*Buffer); + for (Sum = 0, Count = 0; Count < Total; Count++) { + Sum = Sum + *(Buffer + Count); + } + + return Sum; +} + + +/** + Returns the two's complement checksum of all elements in a buffer of + 64-bit values. + + This function first calculates the sum of the 64-bit values in the buffer + specified by Buffer and Length. The carry bits in the result of addition + are dropped. Then, the two's complement of the sum is returned. If Length + is 0, then 0 is returned. + + If Buffer is NULL, then ASSERT(). + If Buffer is not aligned on a 64-bit boundary, then ASSERT(). + If Length is not aligned on a 64-bit boundary, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the buffer to carry out the checksum operation. + @param Length The size, in bytes, of Buffer. + + @return Checksum The 2's complement checksum of Buffer. + +**/ +UINT64 +EFIAPI +CalculateCheckSum64 ( + IN CONST UINT64 *Buffer, + IN UINTN Length + ) +{ + UINT64 CheckSum; + + CheckSum = CalculateSum64 (Buffer, Length); + + // + // Return the checksum based on 2's complement. + // + return (UINT64) ((UINT64)(-1) - CheckSum + 1); +} + +GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT32 mCrcTable[256] = { + 0x00000000, + 0x77073096, + 0xEE0E612C, + 0x990951BA, + 0x076DC419, + 0x706AF48F, + 0xE963A535, + 0x9E6495A3, + 0x0EDB8832, + 0x79DCB8A4, + 0xE0D5E91E, + 0x97D2D988, + 0x09B64C2B, + 0x7EB17CBD, + 0xE7B82D07, + 0x90BF1D91, + 0x1DB71064, + 0x6AB020F2, + 0xF3B97148, + 0x84BE41DE, + 0x1ADAD47D, + 0x6DDDE4EB, + 0xF4D4B551, + 0x83D385C7, + 0x136C9856, + 0x646BA8C0, + 0xFD62F97A, + 0x8A65C9EC, + 0x14015C4F, + 0x63066CD9, + 0xFA0F3D63, + 0x8D080DF5, + 0x3B6E20C8, + 0x4C69105E, + 0xD56041E4, + 0xA2677172, + 0x3C03E4D1, + 0x4B04D447, + 0xD20D85FD, + 0xA50AB56B, + 0x35B5A8FA, + 0x42B2986C, + 0xDBBBC9D6, + 0xACBCF940, + 0x32D86CE3, + 0x45DF5C75, + 0xDCD60DCF, + 0xABD13D59, + 0x26D930AC, + 0x51DE003A, + 0xC8D75180, + 0xBFD06116, + 0x21B4F4B5, + 0x56B3C423, + 0xCFBA9599, + 0xB8BDA50F, + 0x2802B89E, + 0x5F058808, + 0xC60CD9B2, + 0xB10BE924, + 0x2F6F7C87, + 0x58684C11, + 0xC1611DAB, + 0xB6662D3D, + 0x76DC4190, + 0x01DB7106, + 0x98D220BC, + 0xEFD5102A, + 0x71B18589, + 0x06B6B51F, + 0x9FBFE4A5, + 0xE8B8D433, + 0x7807C9A2, + 0x0F00F934, + 0x9609A88E, + 0xE10E9818, + 0x7F6A0DBB, + 0x086D3D2D, + 0x91646C97, + 0xE6635C01, + 0x6B6B51F4, + 0x1C6C6162, + 0x856530D8, + 0xF262004E, + 0x6C0695ED, + 0x1B01A57B, + 0x8208F4C1, + 0xF50FC457, + 0x65B0D9C6, + 0x12B7E950, + 0x8BBEB8EA, + 0xFCB9887C, + 0x62DD1DDF, + 0x15DA2D49, + 0x8CD37CF3, + 0xFBD44C65, + 0x4DB26158, + 0x3AB551CE, + 0xA3BC0074, + 0xD4BB30E2, + 0x4ADFA541, + 0x3DD895D7, + 0xA4D1C46D, + 0xD3D6F4FB, + 0x4369E96A, + 0x346ED9FC, + 0xAD678846, + 0xDA60B8D0, + 0x44042D73, + 0x33031DE5, + 0xAA0A4C5F, + 0xDD0D7CC9, + 0x5005713C, + 0x270241AA, + 0xBE0B1010, + 0xC90C2086, + 0x5768B525, + 0x206F85B3, + 0xB966D409, + 0xCE61E49F, + 0x5EDEF90E, + 0x29D9C998, + 0xB0D09822, + 0xC7D7A8B4, + 0x59B33D17, + 0x2EB40D81, + 0xB7BD5C3B, + 0xC0BA6CAD, + 0xEDB88320, + 0x9ABFB3B6, + 0x03B6E20C, + 0x74B1D29A, + 0xEAD54739, + 0x9DD277AF, + 0x04DB2615, + 0x73DC1683, + 0xE3630B12, + 0x94643B84, + 0x0D6D6A3E, + 0x7A6A5AA8, + 0xE40ECF0B, + 0x9309FF9D, + 0x0A00AE27, + 0x7D079EB1, + 0xF00F9344, + 0x8708A3D2, + 0x1E01F268, + 0x6906C2FE, + 0xF762575D, + 0x806567CB, + 0x196C3671, + 0x6E6B06E7, + 0xFED41B76, + 0x89D32BE0, + 0x10DA7A5A, + 0x67DD4ACC, + 0xF9B9DF6F, + 0x8EBEEFF9, + 0x17B7BE43, + 0x60B08ED5, + 0xD6D6A3E8, + 0xA1D1937E, + 0x38D8C2C4, + 0x4FDFF252, + 0xD1BB67F1, + 0xA6BC5767, + 0x3FB506DD, + 0x48B2364B, + 0xD80D2BDA, + 0xAF0A1B4C, + 0x36034AF6, + 0x41047A60, + 0xDF60EFC3, + 0xA867DF55, + 0x316E8EEF, + 0x4669BE79, + 0xCB61B38C, + 0xBC66831A, + 0x256FD2A0, + 0x5268E236, + 0xCC0C7795, + 0xBB0B4703, + 0x220216B9, + 0x5505262F, + 0xC5BA3BBE, + 0xB2BD0B28, + 0x2BB45A92, + 0x5CB36A04, + 0xC2D7FFA7, + 0xB5D0CF31, + 0x2CD99E8B, + 0x5BDEAE1D, + 0x9B64C2B0, + 0xEC63F226, + 0x756AA39C, + 0x026D930A, + 0x9C0906A9, + 0xEB0E363F, + 0x72076785, + 0x05005713, + 0x95BF4A82, + 0xE2B87A14, + 0x7BB12BAE, + 0x0CB61B38, + 0x92D28E9B, + 0xE5D5BE0D, + 0x7CDCEFB7, + 0x0BDBDF21, + 0x86D3D2D4, + 0xF1D4E242, + 0x68DDB3F8, + 0x1FDA836E, + 0x81BE16CD, + 0xF6B9265B, + 0x6FB077E1, + 0x18B74777, + 0x88085AE6, + 0xFF0F6A70, + 0x66063BCA, + 0x11010B5C, + 0x8F659EFF, + 0xF862AE69, + 0x616BFFD3, + 0x166CCF45, + 0xA00AE278, + 0xD70DD2EE, + 0x4E048354, + 0x3903B3C2, + 0xA7672661, + 0xD06016F7, + 0x4969474D, + 0x3E6E77DB, + 0xAED16A4A, + 0xD9D65ADC, + 0x40DF0B66, + 0x37D83BF0, + 0xA9BCAE53, + 0xDEBB9EC5, + 0x47B2CF7F, + 0x30B5FFE9, + 0xBDBDF21C, + 0xCABAC28A, + 0x53B39330, + 0x24B4A3A6, + 0xBAD03605, + 0xCDD70693, + 0x54DE5729, + 0x23D967BF, + 0xB3667A2E, + 0xC4614AB8, + 0x5D681B02, + 0x2A6F2B94, + 0xB40BBE37, + 0xC30C8EA1, + 0x5A05DF1B, + 0x2D02EF8D +}; + +/** + Computes and returns a 32-bit CRC for a data buffer. + CRC32 value bases on ITU-T V.42. + + If Buffer is NULL, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param[in] Buffer A pointer to the buffer on which the 32-bit CRC is to be computed. + @param[in] Length The number of bytes in the buffer Data. + + @retval Crc32 The 32-bit CRC was computed for the data buffer. + +**/ +UINT32 +EFIAPI +CalculateCrc32( + IN VOID *Buffer, + IN UINTN Length + ) +{ + UINTN Index; + UINT32 Crc; + UINT8 *Ptr; + + ASSERT (Buffer != NULL); + ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); + + // + // Compute CRC + // + Crc = 0xffffffff; + for (Index = 0, Ptr = Buffer; Index < Length; Index++, Ptr++) { + Crc = (Crc >> 8) ^ mCrcTable[(UINT8) Crc ^ *Ptr]; + } + + return Crc ^ 0xffffffff; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/Cpu.c b/MdePkg/HostLibrary/BaseLibHost/Cpu.c new file mode 100644 index 00000000000..727fd9084b7 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Cpu.c @@ -0,0 +1,95 @@ +/** @file + Base Library CPU Functions for all architectures. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +/** + Disables CPU interrupts and returns the interrupt state prior to the disable + operation. + + @retval TRUE CPU interrupts were enabled on entry to this call. + @retval FALSE CPU interrupts were disabled on entry to this call. + +**/ +BOOLEAN +EFIAPI +SaveAndDisableInterrupts ( + VOID + ) +{ + return FALSE; +} + +/** + Set the current CPU interrupt state. + + Sets the current CPU interrupt state to the state specified by + InterruptState. If InterruptState is TRUE, then interrupts are enabled. If + InterruptState is FALSE, then interrupts are disabled. InterruptState is + returned. + + @param InterruptState TRUE if interrupts should be enabled. FALSE if + interrupts should be disabled. + + @return InterruptState + +**/ +BOOLEAN +EFIAPI +SetInterruptState ( + IN BOOLEAN InterruptState + ) +{ + return InterruptState; +} + +/** + Uses as a barrier to stop speculative execution. + + Ensures that no later instruction will execute speculatively, until all prior + instructions have completed. + +**/ +VOID +EFIAPI +SpeculationBarrier ( + VOID + ) +{ +} + +/** + Requests CPU to pause for a short period of time. + + Requests CPU to pause for a short period of time. Typically used in MP + systems to prevent memory starvation while waiting for a spin lock. + +**/ +VOID +EFIAPI +CpuPause ( + VOID + ) +{ +} + +/** + Performs a serializing operation on all load-from-memory instructions that + were issued prior the AsmLfence function. + + Executes a LFENCE instruction. This function is only available on IA-32 and x64. + +**/ +VOID +EFIAPI +AsmLfence ( + VOID + ) +{ + return; +} \ No newline at end of file diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c b/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c new file mode 100644 index 00000000000..20edc0c4dfd --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c @@ -0,0 +1,26 @@ +/** @file + CpuBreakpoint function. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + + + +/** + Generates a breakpoint on the CPU. + + Generates a breakpoint on the CPU. The breakpoint must be implemented such + that code can resume normal execution after the breakpoint. + +**/ +VOID +EFIAPI +CpuBreakpoint ( + VOID + ) +{ + __asm__ __volatile__ ("int $3"); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c b/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c new file mode 100644 index 00000000000..a59da0ceef9 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c @@ -0,0 +1,35 @@ +/** @file + CpuBreakpoint function. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + + + +/** + Microsoft Visual Studio 7.1 Function Prototypes for I/O Intrinsics. +**/ + +void __debugbreak (VOID); + +#pragma intrinsic(__debugbreak) + +/** + Generates a breakpoint on the CPU. + + Generates a breakpoint on the CPU. The breakpoint must be implemented such + that code can resume normal execution after the breakpoint. + +**/ +VOID +EFIAPI +CpuBreakpoint ( + VOID + ) +{ + __debugbreak (); +} + diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c b/MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c new file mode 100644 index 00000000000..9e110cacbc9 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c @@ -0,0 +1,32 @@ +/** @file + Base Library CPU Functions for all architectures. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + + +#include +#include + +/** + Executes an infinite loop. + + Forces the CPU to execute an infinite loop. A debugger may be used to skip + past the loop and the code that follows the loop must execute properly. This + implies that the infinite loop must not cause the code that follow it to be + optimized away. + +**/ +VOID +EFIAPI +CpuDeadLoop ( + VOID + ) +{ + volatile UINTN Index; + + for (Index = 0; Index == 0;); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c b/MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c new file mode 100644 index 00000000000..3048df52d31 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c @@ -0,0 +1,54 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +INT64 +EFIAPI +InternalMathDivRemS64x64 ( + IN INT64 Dividend, + IN INT64 Divisor, + OUT INT64 *Remainder OPTIONAL + ); + +/** + Divides a 64-bit signed integer by a 64-bit signed integer and generates a + 64-bit signed result and a optional 64-bit signed remainder. + + This function divides the 64-bit signed value Dividend by the 64-bit signed + value Divisor and generates a 64-bit signed quotient. If Remainder is not + NULL, then the 64-bit signed remainder is returned in Remainder. This + function returns the 64-bit signed quotient. + + It is the caller's responsibility to not call this function with a Divisor of 0. + If Divisor is 0, then the quotient and remainder should be assumed to be + the largest negative integer. + + If Divisor is 0, then ASSERT(). + + @param Dividend A 64-bit signed value. + @param Divisor A 64-bit signed value. + @param Remainder A pointer to a 64-bit signed value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor + +**/ +INT64 +EFIAPI +DivS64x64Remainder ( + IN INT64 Dividend, + IN INT64 Divisor, + OUT INT64 *Remainder OPTIONAL + ) +{ + ASSERT (Divisor != 0); + return InternalMathDivRemS64x64 (Dividend, Divisor, Remainder); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x32.c b/MdePkg/HostLibrary/BaseLibHost/DivU64x32.c new file mode 100644 index 00000000000..b63fb6d968a --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DivU64x32.c @@ -0,0 +1,45 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathDivU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ); + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates + a 64-bit unsigned result. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. This + function returns the 64-bit unsigned quotient. + + If Divisor is 0, then ASSERT(). + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + + @return Dividend / Divisor + +**/ +UINT64 +EFIAPI +DivU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ) +{ + ASSERT (Divisor != 0); + return InternalMathDivU64x32 (Dividend, Divisor); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c b/MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c new file mode 100644 index 00000000000..03ce598beb3 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c @@ -0,0 +1,50 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathDivRemU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor, + OUT UINT32 *Remainder OPTIONAL + ); + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates + a 64-bit unsigned result and an optional 32-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder + is not NULL, then the 32-bit unsigned remainder is returned in Remainder. + This function returns the 64-bit unsigned quotient. + + If Divisor is 0, then ASSERT(). + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + @param Remainder A pointer to a 32-bit unsigned value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor + +**/ +UINT64 +EFIAPI +DivU64x32Remainder ( + IN UINT64 Dividend, + IN UINT32 Divisor, + OUT UINT32 *Remainder OPTIONAL + ) +{ + ASSERT (Divisor != 0); + return InternalMathDivRemU64x32 (Dividend, Divisor, Remainder); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c b/MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c new file mode 100644 index 00000000000..ee3fd264be2 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c @@ -0,0 +1,50 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathDivRemU64x64 ( + IN UINT64 Dividend, + IN UINT64 Divisor, + OUT UINT64 *Remainder OPTIONAL + ); + +/** + Divides a 64-bit unsigned integer by a 64-bit unsigned integer and generates + a 64-bit unsigned result and an optional 64-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 64-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder + is not NULL, then the 64-bit unsigned remainder is returned in Remainder. + This function returns the 64-bit unsigned quotient. + + If Divisor is 0, then ASSERT(). + + @param Dividend A 64-bit unsigned value. + @param Divisor A 64-bit unsigned value. + @param Remainder A pointer to a 64-bit unsigned value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor + +**/ +UINT64 +EFIAPI +DivU64x64Remainder ( + IN UINT64 Dividend, + IN UINT64 Divisor, + OUT UINT64 *Remainder OPTIONAL + ) +{ + ASSERT (Divisor != 0); + return InternalMathDivRemU64x64 (Dividend, Divisor, Remainder); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c b/MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c new file mode 100644 index 00000000000..1e880d56e95 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c @@ -0,0 +1,65 @@ +/** @file + + Copyright (c) 2016, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Generates a 16-bit random number through RDRAND instruction. + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + + **/ +BOOLEAN +EFIAPI +InternalX86RdRand16 ( + OUT UINT16 *Rand + ) +{ + return TRUE; +} + +/** + Generates a 32-bit random number through RDRAND instruction. + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +InternalX86RdRand32 ( + OUT UINT32 *Rand + ) +{ + return TRUE; +} + +/** + Generates a 64-bit random number through RDRAND instruction. + + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +InternalX86RdRand64 ( + OUT UINT64 *Rand + ) +{ + return TRUE; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c b/MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c new file mode 100644 index 00000000000..62650dd7a5d --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c @@ -0,0 +1,19 @@ +/** @file + + Copyright (c) 2016, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +AsmReadTsc ( + VOID + ) +{ + return 0; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c b/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c new file mode 100644 index 00000000000..90e5d5fb8a9 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c @@ -0,0 +1,37 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the value of the highest bit set in a 32-bit value. Equivalent to + 1 << log2(x). + + This function computes the value of the highest bit set in the 32-bit value + specified by Operand. If Operand is zero, then zero is returned. + + @param Operand The 32-bit operand to evaluate. + + @return 1 << HighBitSet32(Operand) + @retval 0 Operand is zero. + +**/ +UINT32 +EFIAPI +GetPowerOfTwo32 ( + IN UINT32 Operand + ) +{ + if (0 == Operand) { + return 0; + } + + return 1ul << HighBitSet32 (Operand); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c b/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c new file mode 100644 index 00000000000..680a82d0d57 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c @@ -0,0 +1,37 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the value of the highest bit set in a 64-bit value. Equivalent to + 1 << log2(x). + + This function computes the value of the highest bit set in the 64-bit value + specified by Operand. If Operand is zero, then zero is returned. + + @param Operand The 64-bit operand to evaluate. + + @return 1 << HighBitSet64(Operand) + @retval 0 Operand is zero. + +**/ +UINT64 +EFIAPI +GetPowerOfTwo64 ( + IN UINT64 Operand + ) +{ + if (Operand == 0) { + return 0; + } + + return LShiftU64 (1, (UINTN) HighBitSet64 (Operand)); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c b/MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c new file mode 100644 index 00000000000..610de67f062 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c @@ -0,0 +1,40 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the bit position of the highest bit set in a 32-bit value. Equivalent + to log2(x). + + This function computes the bit position of the highest bit set in the 32-bit + value specified by Operand. If Operand is zero, then -1 is returned. + Otherwise, a value between 0 and 31 is returned. + + @param Operand The 32-bit operand to evaluate. + + @retval 0..31 Position of the highest bit set in Operand if found. + @retval -1 Operand is zero. + +**/ +INTN +EFIAPI +HighBitSet32 ( + IN UINT32 Operand + ) +{ + INTN BitIndex; + + if (Operand == 0) { + return - 1; + } + for (BitIndex = 31; (INT32)Operand > 0; BitIndex--, Operand <<= 1); + return BitIndex; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c b/MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c new file mode 100644 index 00000000000..28be7cfb302 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c @@ -0,0 +1,47 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Returns the bit position of the highest bit set in a 64-bit value. Equivalent + to log2(x). + + This function computes the bit position of the highest bit set in the 64-bit + value specified by Operand. If Operand is zero, then -1 is returned. + Otherwise, a value between 0 and 63 is returned. + + @param Operand The 64-bit operand to evaluate. + + @retval 0..63 Position of the highest bit set in Operand if found. + @retval -1 Operand is zero. + +**/ +INTN +EFIAPI +HighBitSet64 ( + IN UINT64 Operand + ) +{ + if (Operand == (UINT32)Operand) { + // + // Operand is just a 32-bit integer + // + return HighBitSet32 ((UINT32)Operand); + } + + // + // Operand is really a 64-bit integer + // + if (sizeof (UINTN) == sizeof (UINT32)) { + return HighBitSet32 (((UINT32*)&Operand)[1]) + 32; + } else { + return HighBitSet32 ((UINT32)RShiftU64 (Operand, 32)) + 32; + } +} diff --git a/MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm b/MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm new file mode 100644 index 00000000000..e12b8e96119 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm @@ -0,0 +1,84 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; RdRand.nasm +; +; Abstract: +; +; Generates random number through CPU RdRand instruction under 32-bit platform. +; +; Notes: +; +;------------------------------------------------------------------------------ + +SECTION .text + +;------------------------------------------------------------------------------ +; Generates a 16 bit random number through RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand16 (UINT16 *Rand); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand16) +ASM_PFX(InternalX86RdRand16): + ; rdrand ax ; generate a 16 bit RN into ax + ; CF=1 if RN generated ok, otherwise CF=0 + db 0xf, 0xc7, 0xf0 ; rdrand r16: "0f c7 /6 ModRM:r/m(w)" + jc rn16_ok ; jmp if CF=1 + xor eax, eax ; reg=0 if CF=0 + ret ; return with failure status +rn16_ok: + mov edx, dword [esp + 4] + mov [edx], ax + mov eax, 1 + ret + +;------------------------------------------------------------------------------ +; Generates a 32 bit random number through RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand32 (UINT32 *Rand); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand32) +ASM_PFX(InternalX86RdRand32): + ; rdrand eax ; generate a 32 bit RN into eax + ; CF=1 if RN generated ok, otherwise CF=0 + db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" + jc rn32_ok ; jmp if CF=1 + xor eax, eax ; reg=0 if CF=0 + ret ; return with failure status +rn32_ok: + mov edx, dword [esp + 4] + mov [edx], eax + mov eax, 1 + ret + +;------------------------------------------------------------------------------ +; Generates a 64 bit random number through RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand64 (UINT64 *Rand); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand64) +ASM_PFX(InternalX86RdRand64): + ; rdrand eax ; generate a 32 bit RN into eax + ; CF=1 if RN generated ok, otherwise CF=0 + db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" + jnc rn64_ret ; jmp if CF=0 + mov edx, dword [esp + 4] + mov [edx], eax + + db 0xf, 0xc7, 0xf0 ; generate another 32 bit RN + jnc rn64_ret ; jmp if CF=0 + mov [edx + 4], eax + + mov eax, 1 + ret +rn64_ret: + xor eax, eax + ret ; return with failure status + diff --git a/MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm b/MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm new file mode 100644 index 00000000000..1bc875bd363 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm @@ -0,0 +1,31 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2006, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; ReadTsc.Asm +; +; Abstract: +; +; AsmReadTsc function +; +; Notes: +; +;------------------------------------------------------------------------------ + + SECTION .text + +;------------------------------------------------------------------------------ +; UINT64 +; EFIAPI +; AsmReadTsc ( +; VOID +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(AsmReadTsc) +ASM_PFX(AsmReadTsc): + rdtsc + ret + diff --git a/MdePkg/HostLibrary/BaseLibHost/LRotU32.c b/MdePkg/HostLibrary/BaseLibHost/LRotU32.c new file mode 100644 index 00000000000..8c189817296 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LRotU32.c @@ -0,0 +1,38 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Rotates a 32-bit integer left between 0 and 31 bits, filling the low bits + with the high bits that were rotated. + + This function rotates the 32-bit value Operand to the left by Count bits. The + low Count bits are fill with the high Count bits of Operand. The rotated + value is returned. + + If Count is greater than 31, then ASSERT(). + + @param Operand The 32-bit operand to rotate left. + @param Count The number of bits to rotate left. + + @return Operand << Count + +**/ +UINT32 +EFIAPI +LRotU32 ( + IN UINT32 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 32); + return (Operand << Count) | (Operand >> (32 - Count)); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/LRotU64.c b/MdePkg/HostLibrary/BaseLibHost/LRotU64.c new file mode 100644 index 00000000000..c58cdeb6211 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LRotU64.c @@ -0,0 +1,45 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathLRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ); + +/** + Rotates a 64-bit integer left between 0 and 63 bits, filling the low bits + with the high bits that were rotated. + + This function rotates the 64-bit value Operand to the left by Count bits. The + low Count bits are fill with the high Count bits of Operand. The rotated + value is returned. + + If Count is greater than 63, then ASSERT(). + + @param Operand The 64-bit operand to rotate left. + @param Count The number of bits to rotate left. + + @return Operand << Count + +**/ +UINT64 +EFIAPI +LRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 64); + return InternalMathLRotU64 (Operand, Count); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/LShiftU64.c b/MdePkg/HostLibrary/BaseLibHost/LShiftU64.c new file mode 100644 index 00000000000..220e5c13910 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LShiftU64.c @@ -0,0 +1,44 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathLShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ); + +/** + Shifts a 64-bit integer left between 0 and 63 bits. The low bits are filled + with zeros. The shifted value is returned. + + This function shifts the 64-bit value Operand to the left by Count bits. The + low Count bits are set to zero. The shifted value is returned. + + If Count is greater than 63, then ASSERT(). + + @param Operand The 64-bit operand to shift left. + @param Count The number of bits to shift left. + + @return Operand << Count. + +**/ +UINT64 +EFIAPI +LShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 64); + return InternalMathLShiftU64 (Operand, Count); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/Lfence.c b/MdePkg/HostLibrary/BaseLibHost/Lfence.c new file mode 100644 index 00000000000..e894b4e22c4 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Lfence.c @@ -0,0 +1,10 @@ +/** @file + + Copyright (c) 2016, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include diff --git a/MdePkg/HostLibrary/BaseLibHost/LinkedList.c b/MdePkg/HostLibrary/BaseLibHost/LinkedList.c new file mode 100644 index 00000000000..550d5de5405 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LinkedList.c @@ -0,0 +1,536 @@ +/** @file + Linked List Library Functions. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +#define ASSERT_VERIFY_NODE_IN_VALID_LIST(FirstEntry, SecondEntry, InList) + +/** + Worker function that verifies the validity of this list. + + If List is NULL, then ASSERT(). + If List->ForwardLink is NULL, then ASSERT(). + If List->BackLink is NULL, then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and List contains more than + PcdMaximumLinkedListLength nodes, then ASSERT(). + + @param List A pointer to a node in a linked list. + + @retval TRUE if PcdVerifyNodeInList is FALSE + @retval TRUE if DoMembershipCheck is FALSE + @retval TRUE if PcdVerifyNodeInList is TRUE and DoMembershipCheck is TRUE + and Node is a member of List. + @retval FALSE if PcdVerifyNodeInList is TRUE and DoMembershipCheck is TRUE + and Node is in not a member of List. + +**/ +BOOLEAN +EFIAPI +InternalBaseLibIsListValid ( + IN CONST LIST_ENTRY *List + ) +{ + // + // Test the validity of List and Node + // + ASSERT (List != NULL); + ASSERT (List->ForwardLink != NULL); + ASSERT (List->BackLink != NULL); + + return TRUE; +} + +/** + Checks whether FirstEntry and SecondEntry are part of the same doubly-linked + list. + + If FirstEntry is NULL, then ASSERT(). + If FirstEntry->ForwardLink is NULL, then ASSERT(). + If FirstEntry->BackLink is NULL, then ASSERT(). + If SecondEntry is NULL, then ASSERT(); + If PcdMaximumLinkedListLength is not zero, and List contains more than + PcdMaximumLinkedListLength nodes, then ASSERT(). + + @param FirstEntry A pointer to a node in a linked list. + @param SecondEntry A pointer to the node to locate. + + @retval TRUE SecondEntry is in the same doubly-linked list as FirstEntry. + @retval FALSE SecondEntry isn't in the same doubly-linked list as FirstEntry, + or FirstEntry is invalid. + +**/ +BOOLEAN +EFIAPI +IsNodeInList ( + IN CONST LIST_ENTRY *FirstEntry, + IN CONST LIST_ENTRY *SecondEntry + ) +{ + CONST LIST_ENTRY *Ptr; + + // + // ASSERT List not too long + // + ASSERT (InternalBaseLibIsListValid (FirstEntry)); + + ASSERT (SecondEntry != NULL); + + Ptr = FirstEntry; + + // + // Check to see if SecondEntry is a member of FirstEntry. + // Exit early if the number of nodes in List >= PcdMaximumLinkedListLength + // + do { + Ptr = Ptr->ForwardLink; + if (Ptr == SecondEntry) { + return TRUE; + } + } while (Ptr != FirstEntry); + + return FALSE; +} + +/** + Initializes the head node of a doubly-linked list, and returns the pointer to + the head node of the doubly-linked list. + + Initializes the forward and backward links of a new linked list. After + initializing a linked list with this function, the other linked list + functions may be used to add and remove nodes from the linked list. It is up + to the caller of this function to allocate the memory for ListHead. + + If ListHead is NULL, then ASSERT(). + + @param ListHead A pointer to the head node of a new doubly-linked list. + + @return ListHead + +**/ +LIST_ENTRY * +EFIAPI +InitializeListHead ( + IN OUT LIST_ENTRY *ListHead + ) + +{ + ASSERT (ListHead != NULL); + + ListHead->ForwardLink = ListHead; + ListHead->BackLink = ListHead; + return ListHead; +} + +/** + Adds a node to the beginning of a doubly-linked list, and returns the pointer + to the head node of the doubly-linked list. + + Adds the node Entry at the beginning of the doubly-linked list denoted by + ListHead, and returns ListHead. + + If ListHead is NULL, then ASSERT(). + If Entry is NULL, then ASSERT(). + If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and prior to insertion the number + of nodes in ListHead, including the ListHead node, is greater than or + equal to PcdMaximumLinkedListLength, then ASSERT(). + + @param ListHead A pointer to the head node of a doubly-linked list. + @param Entry A pointer to a node that is to be inserted at the beginning + of a doubly-linked list. + + @return ListHead + +**/ +LIST_ENTRY * +EFIAPI +InsertHeadList ( + IN OUT LIST_ENTRY *ListHead, + IN OUT LIST_ENTRY *Entry + ) +{ + // + // ASSERT List not too long and Entry is not one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (ListHead, Entry, FALSE); + + Entry->ForwardLink = ListHead->ForwardLink; + Entry->BackLink = ListHead; + Entry->ForwardLink->BackLink = Entry; + ListHead->ForwardLink = Entry; + return ListHead; +} + +/** + Adds a node to the end of a doubly-linked list, and returns the pointer to + the head node of the doubly-linked list. + + Adds the node Entry to the end of the doubly-linked list denoted by ListHead, + and returns ListHead. + + If ListHead is NULL, then ASSERT(). + If Entry is NULL, then ASSERT(). + If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and prior to insertion the number + of nodes in ListHead, including the ListHead node, is greater than or + equal to PcdMaximumLinkedListLength, then ASSERT(). + + @param ListHead A pointer to the head node of a doubly-linked list. + @param Entry A pointer to a node that is to be added at the end of the + doubly-linked list. + + @return ListHead + +**/ +LIST_ENTRY * +EFIAPI +InsertTailList ( + IN OUT LIST_ENTRY *ListHead, + IN OUT LIST_ENTRY *Entry + ) +{ + // + // ASSERT List not too long and Entry is not one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (ListHead, Entry, FALSE); + + Entry->ForwardLink = ListHead; + Entry->BackLink = ListHead->BackLink; + Entry->BackLink->ForwardLink = Entry; + ListHead->BackLink = Entry; + return ListHead; +} + +/** + Retrieves the first node of a doubly-linked list. + + Returns the first node of a doubly-linked list. List must have been + initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). + If List is empty, then List is returned. + + If List is NULL, then ASSERT(). + If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes + in List, including the List node, is greater than or equal to + PcdMaximumLinkedListLength, then ASSERT(). + + @param List A pointer to the head node of a doubly-linked list. + + @return The first node of a doubly-linked list. + @retval List The list is empty. + +**/ +LIST_ENTRY * +EFIAPI +GetFirstNode ( + IN CONST LIST_ENTRY *List + ) +{ + // + // ASSERT List not too long + // + ASSERT (InternalBaseLibIsListValid (List)); + + return List->ForwardLink; +} + +/** + Retrieves the next node of a doubly-linked list. + + Returns the node of a doubly-linked list that follows Node. + List must have been initialized with INTIALIZE_LIST_HEAD_VARIABLE() + or InitializeListHead(). If List is empty, then List is returned. + + If List is NULL, then ASSERT(). + If Node is NULL, then ASSERT(). + If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and List contains more than + PcdMaximumLinkedListLength nodes, then ASSERT(). + If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). + + @param List A pointer to the head node of a doubly-linked list. + @param Node A pointer to a node in the doubly-linked list. + + @return A pointer to the next node if one exists. Otherwise List is returned. + +**/ +LIST_ENTRY * +EFIAPI +GetNextNode ( + IN CONST LIST_ENTRY *List, + IN CONST LIST_ENTRY *Node + ) +{ + // + // ASSERT List not too long and Node is one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); + + return Node->ForwardLink; +} + +/** + Retrieves the previous node of a doubly-linked list. + + Returns the node of a doubly-linked list that precedes Node. + List must have been initialized with INTIALIZE_LIST_HEAD_VARIABLE() + or InitializeListHead(). If List is empty, then List is returned. + + If List is NULL, then ASSERT(). + If Node is NULL, then ASSERT(). + If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and List contains more than + PcdMaximumLinkedListLength nodes, then ASSERT(). + If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). + + @param List A pointer to the head node of a doubly-linked list. + @param Node A pointer to a node in the doubly-linked list. + + @return A pointer to the previous node if one exists. Otherwise List is returned. + +**/ +LIST_ENTRY * +EFIAPI +GetPreviousNode ( + IN CONST LIST_ENTRY *List, + IN CONST LIST_ENTRY *Node + ) +{ + // + // ASSERT List not too long and Node is one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); + + return Node->BackLink; +} + +/** + Checks to see if a doubly-linked list is empty or not. + + Checks to see if the doubly-linked list is empty. If the linked list contains + zero nodes, this function returns TRUE. Otherwise, it returns FALSE. + + If ListHead is NULL, then ASSERT(). + If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes + in List, including the List node, is greater than or equal to + PcdMaximumLinkedListLength, then ASSERT(). + + @param ListHead A pointer to the head node of a doubly-linked list. + + @retval TRUE The linked list is empty. + @retval FALSE The linked list is not empty. + +**/ +BOOLEAN +EFIAPI +IsListEmpty ( + IN CONST LIST_ENTRY *ListHead + ) +{ + // + // ASSERT List not too long + // + ASSERT (InternalBaseLibIsListValid (ListHead)); + + return (BOOLEAN)(ListHead->ForwardLink == ListHead); +} + +/** + Determines if a node in a doubly-linked list is the head node of a the same + doubly-linked list. This function is typically used to terminate a loop that + traverses all the nodes in a doubly-linked list starting with the head node. + + Returns TRUE if Node is equal to List. Returns FALSE if Node is one of the + nodes in the doubly-linked list specified by List. List must have been + initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). + + If List is NULL, then ASSERT(). + If Node is NULL, then ASSERT(). + If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(), + then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes + in List, including the List node, is greater than or equal to + PcdMaximumLinkedListLength, then ASSERT(). + If PcdVerifyNodeInList is TRUE and Node is not a node in List and Node is not + equal to List, then ASSERT(). + + @param List A pointer to the head node of a doubly-linked list. + @param Node A pointer to a node in the doubly-linked list. + + @retval TRUE Node is the head of the doubly-linked list pointed by List. + @retval FALSE Node is not the head of the doubly-linked list pointed by List. + +**/ +BOOLEAN +EFIAPI +IsNull ( + IN CONST LIST_ENTRY *List, + IN CONST LIST_ENTRY *Node + ) +{ + // + // ASSERT List not too long and Node is one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); + + return (BOOLEAN)(Node == List); +} + +/** + Determines if a node the last node in a doubly-linked list. + + Returns TRUE if Node is the last node in the doubly-linked list specified by + List. Otherwise, FALSE is returned. List must have been initialized with + INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). + + If List is NULL, then ASSERT(). + If Node is NULL, then ASSERT(). + If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or + InitializeListHead(), then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes + in List, including the List node, is greater than or equal to + PcdMaximumLinkedListLength, then ASSERT(). + If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). + + @param List A pointer to the head node of a doubly-linked list. + @param Node A pointer to a node in the doubly-linked list. + + @retval TRUE Node is the last node in the linked list. + @retval FALSE Node is not the last node in the linked list. + +**/ +BOOLEAN +EFIAPI +IsNodeAtEnd ( + IN CONST LIST_ENTRY *List, + IN CONST LIST_ENTRY *Node + ) +{ + // + // ASSERT List not too long and Node is one of the nodes of List + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); + + return (BOOLEAN)(!IsNull (List, Node) && List->BackLink == Node); +} + +/** + Swaps the location of two nodes in a doubly-linked list, and returns the + first node after the swap. + + If FirstEntry is identical to SecondEntry, then SecondEntry is returned. + Otherwise, the location of the FirstEntry node is swapped with the location + of the SecondEntry node in a doubly-linked list. SecondEntry must be in the + same double linked list as FirstEntry and that double linked list must have + been initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). + SecondEntry is returned after the nodes are swapped. + + If FirstEntry is NULL, then ASSERT(). + If SecondEntry is NULL, then ASSERT(). + If PcdVerifyNodeInList is TRUE and SecondEntry and FirstEntry are not in the + same linked list, then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes in the + linked list containing the FirstEntry and SecondEntry nodes, including + the FirstEntry and SecondEntry nodes, is greater than or equal to + PcdMaximumLinkedListLength, then ASSERT(). + + @param FirstEntry A pointer to a node in a linked list. + @param SecondEntry A pointer to another node in the same linked list. + + @return SecondEntry. + +**/ +LIST_ENTRY * +EFIAPI +SwapListEntries ( + IN OUT LIST_ENTRY *FirstEntry, + IN OUT LIST_ENTRY *SecondEntry + ) +{ + LIST_ENTRY *Ptr; + + if (FirstEntry == SecondEntry) { + return SecondEntry; + } + + // + // ASSERT Entry1 and Entry2 are in the same linked list + // + ASSERT_VERIFY_NODE_IN_VALID_LIST (FirstEntry, SecondEntry, TRUE); + + // + // Ptr is the node pointed to by FirstEntry->ForwardLink + // + Ptr = RemoveEntryList (FirstEntry); + + // + // If FirstEntry immediately follows SecondEntry, FirstEntry will be placed + // immediately in front of SecondEntry + // + if (Ptr->BackLink == SecondEntry) { + return InsertTailList (SecondEntry, FirstEntry); + } + + // + // Ptr == SecondEntry means SecondEntry immediately follows FirstEntry, + // then there are no further steps necessary + // + if (Ptr == InsertHeadList (SecondEntry, FirstEntry)) { + return Ptr; + } + + // + // Move SecondEntry to the front of Ptr + // + RemoveEntryList (SecondEntry); + InsertTailList (Ptr, SecondEntry); + return SecondEntry; +} + +/** + Removes a node from a doubly-linked list, and returns the node that follows + the removed node. + + Removes the node Entry from a doubly-linked list. It is up to the caller of + this function to release the memory used by this node if that is required. On + exit, the node following Entry in the doubly-linked list is returned. If + Entry is the only node in the linked list, then the head node of the linked + list is returned. + + If Entry is NULL, then ASSERT(). + If Entry is the head node of an empty list, then ASSERT(). + If PcdMaximumLinkedListLength is not zero, and the number of nodes in the + linked list containing Entry, including the Entry node, is greater than + or equal to PcdMaximumLinkedListLength, then ASSERT(). + + @param Entry A pointer to a node in a linked list. + + @return Entry. + +**/ +LIST_ENTRY * +EFIAPI +RemoveEntryList ( + IN CONST LIST_ENTRY *Entry + ) +{ + ASSERT (!IsListEmpty (Entry)); + + Entry->ForwardLink->BackLink = Entry->BackLink; + Entry->BackLink->ForwardLink = Entry->ForwardLink; + return Entry->ForwardLink; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/LongJump.c b/MdePkg/HostLibrary/BaseLibHost/LongJump.c new file mode 100644 index 00000000000..fec7056e92f --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LongJump.c @@ -0,0 +1,46 @@ +/** @file + Long Jump functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + +#include +#include +#include +#include +#include + +/** + Restores the CPU context that was saved with SetJump(). + + Restores the CPU context from the buffer specified by JumpBuffer. This + function never returns to the caller. Instead is resumes execution based on + the state of JumpBuffer. + + If JumpBuffer is NULL, then ASSERT(). + For Itanium processors, if JumpBuffer is not aligned on a 16-byte boundary, then ASSERT(). + If Value is 0, then ASSERT(). + + @param JumpBuffer A pointer to CPU context buffer. + @param Value The value to return when the SetJump() context is + restored and must be non-zero. + +**/ +VOID +EFIAPI +LongJump ( + IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer, + IN UINTN Value + ) +{ + jmp_buf local_buf; + jmp_buf *buf; + + buf = *(VOID **)JumpBuffer; + memcpy (&local_buf, buf, sizeof(jmp_buf)); + free (buf); + longjmp (local_buf, (int)Value); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c b/MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c new file mode 100644 index 00000000000..bb7f49df29c --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c @@ -0,0 +1,40 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the bit position of the lowest bit set in a 32-bit value. + + This function computes the bit position of the lowest bit set in the 32-bit + value specified by Operand. If Operand is zero, then -1 is returned. + Otherwise, a value between 0 and 31 is returned. + + @param Operand The 32-bit operand to evaluate. + + @retval 0..31 The lowest bit set in Operand was found. + @retval -1 Operand is zero. + +**/ +INTN +EFIAPI +LowBitSet32 ( + IN UINT32 Operand + ) +{ + INTN BitIndex; + + if (Operand == 0) { + return -1; + } + + for (BitIndex = 0; 0 == (Operand & 1); BitIndex++, Operand >>= 1); + return BitIndex; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c b/MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c new file mode 100644 index 00000000000..860670f130f --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c @@ -0,0 +1,43 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the bit position of the lowest bit set in a 64-bit value. + + This function computes the bit position of the lowest bit set in the 64-bit + value specified by Operand. If Operand is zero, then -1 is returned. + Otherwise, a value between 0 and 63 is returned. + + @param Operand The 64-bit operand to evaluate. + + @retval 0..63 The lowest bit set in Operand was found. + @retval -1 Operand is zero. + + +**/ +INTN +EFIAPI +LowBitSet64 ( + IN UINT64 Operand + ) +{ + INTN BitIndex; + + if (Operand == 0) { + return -1; + } + + for (BitIndex = 0; + (Operand & 1) == 0; + BitIndex++, Operand = RShiftU64 (Operand, 1)); + return BitIndex; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/Math64.c b/MdePkg/HostLibrary/BaseLibHost/Math64.c new file mode 100644 index 00000000000..7308dec22bf --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Math64.c @@ -0,0 +1,364 @@ +/** @file + Leaf math worker functions that require 64-bit arithmetic support from the + compiler. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Shifts a 64-bit integer left between 0 and 63 bits. The low bits + are filled with zeros. The shifted value is returned. + + This function shifts the 64-bit value Operand to the left by Count bits. The + low Count bits are set to zero. The shifted value is returned. + + @param Operand The 64-bit operand to shift left. + @param Count The number of bits to shift left. + + @return Operand << Count. + +**/ +UINT64 +EFIAPI +InternalMathLShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + return Operand << Count; +} + +/** + Shifts a 64-bit integer right between 0 and 63 bits. This high bits + are filled with zeros. The shifted value is returned. + + This function shifts the 64-bit value Operand to the right by Count bits. The + high Count bits are set to zero. The shifted value is returned. + + @param Operand The 64-bit operand to shift right. + @param Count The number of bits to shift right. + + @return Operand >> Count. + +**/ +UINT64 +EFIAPI +InternalMathRShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + return Operand >> Count; +} + +/** + Shifts a 64-bit integer right between 0 and 63 bits. The high bits + are filled with original integer's bit 63. The shifted value is returned. + + This function shifts the 64-bit value Operand to the right by Count bits. The + high Count bits are set to bit 63 of Operand. The shifted value is returned. + + @param Operand The 64-bit operand to shift right. + @param Count The number of bits to shift right. + + @return Operand arithmetically shifted right by Count. + +**/ +UINT64 +EFIAPI +InternalMathARShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + INTN TestValue; + + // + // Test if this compiler supports arithmetic shift + // + TestValue = (INTN)((INT64)(1ULL << 63) >> 63); + if (TestValue == -1) { + // + // Arithmetic shift is supported + // + return (UINT64)((INT64)Operand >> Count); + } + + // + // Arithmetic is not supported + // + return (Operand >> Count) | + ((INTN)Operand < 0 ? ~((UINTN)-1 >> Count) : 0); +} + + +/** + Rotates a 64-bit integer left between 0 and 63 bits, filling + the low bits with the high bits that were rotated. + + This function rotates the 64-bit value Operand to the left by Count bits. The + low Count bits are fill with the high Count bits of Operand. The rotated + value is returned. + + @param Operand The 64-bit operand to rotate left. + @param Count The number of bits to rotate left. + + @return Operand <<< Count. + +**/ +UINT64 +EFIAPI +InternalMathLRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + return (Operand << Count) | (Operand >> (64 - Count)); +} + +/** + Rotates a 64-bit integer right between 0 and 63 bits, filling + the high bits with the high low bits that were rotated. + + This function rotates the 64-bit value Operand to the right by Count bits. + The high Count bits are fill with the low Count bits of Operand. The rotated + value is returned. + + @param Operand The 64-bit operand to rotate right. + @param Count The number of bits to rotate right. + + @return Operand >>> Count. + +**/ +UINT64 +EFIAPI +InternalMathRRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + return (Operand >> Count) | (Operand << (64 - Count)); +} + +/** + Switches the endianess of a 64-bit integer. + + This function swaps the bytes in a 64-bit unsigned value to switch the value + from little endian to big endian or vice versa. The byte swapped value is + returned. + + @param Operand A 64-bit unsigned value. + + @return The byte swapped Operand. + +**/ +UINT64 +EFIAPI +InternalMathSwapBytes64 ( + IN UINT64 Operand + ) +{ + UINT64 LowerBytes; + UINT64 HigherBytes; + + LowerBytes = (UINT64) SwapBytes32 ((UINT32) Operand); + HigherBytes = (UINT64) SwapBytes32 ((UINT32) (Operand >> 32)); + + return (LowerBytes << 32 | HigherBytes); +} + +/** + Multiplies a 64-bit unsigned integer by a 32-bit unsigned integer + and generates a 64-bit unsigned result. + + This function multiplies the 64-bit unsigned value Multiplicand by the 32-bit + unsigned value Multiplier and generates a 64-bit unsigned result. This 64- + bit unsigned result is returned. + + @param Multiplicand A 64-bit unsigned value. + @param Multiplier A 32-bit unsigned value. + + @return Multiplicand * Multiplier + +**/ +UINT64 +EFIAPI +InternalMathMultU64x32 ( + IN UINT64 Multiplicand, + IN UINT32 Multiplier + ) +{ + return Multiplicand * Multiplier; +} + + +/** + Multiplies a 64-bit unsigned integer by a 64-bit unsigned integer + and generates a 64-bit unsigned result. + + This function multiplies the 64-bit unsigned value Multiplicand by the 64-bit + unsigned value Multiplier and generates a 64-bit unsigned result. This 64- + bit unsigned result is returned. + + @param Multiplicand A 64-bit unsigned value. + @param Multiplier A 64-bit unsigned value. + + @return Multiplicand * Multiplier. + +**/ +UINT64 +EFIAPI +InternalMathMultU64x64 ( + IN UINT64 Multiplicand, + IN UINT64 Multiplier + ) +{ + return Multiplicand * Multiplier; +} + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and + generates a 64-bit unsigned result. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. This + function returns the 64-bit unsigned quotient. + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + + @return Dividend / Divisor. + +**/ +UINT64 +EFIAPI +InternalMathDivU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ) +{ + return Dividend / Divisor; +} + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and + generates a 32-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 32-bit remainder. This function + returns the 32-bit unsigned remainder. + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + + @return Dividend % Divisor. + +**/ +UINT32 +EFIAPI +InternalMathModU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ) +{ + return (UINT32)(Dividend % Divisor); +} + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and + generates a 64-bit unsigned result and an optional 32-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder + is not NULL, then the 32-bit unsigned remainder is returned in Remainder. + This function returns the 64-bit unsigned quotient. + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + @param Remainder A pointer to a 32-bit unsigned value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor. + +**/ +UINT64 +EFIAPI +InternalMathDivRemU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor, + OUT UINT32 *Remainder OPTIONAL + ) +{ + if (Remainder != NULL) { + *Remainder = (UINT32)(Dividend % Divisor); + } + return Dividend / Divisor; +} + +/** + Divides a 64-bit unsigned integer by a 64-bit unsigned integer and + generates a 64-bit unsigned result and an optional 64-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 64-bit + unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder + is not NULL, then the 64-bit unsigned remainder is returned in Remainder. + This function returns the 64-bit unsigned quotient. + + @param Dividend A 64-bit unsigned value. + @param Divisor A 64-bit unsigned value. + @param Remainder A pointer to a 64-bit unsigned value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor + +**/ +UINT64 +EFIAPI +InternalMathDivRemU64x64 ( + IN UINT64 Dividend, + IN UINT64 Divisor, + OUT UINT64 *Remainder OPTIONAL + ) +{ + if (Remainder != NULL) { + *Remainder = Dividend % Divisor; + } + return Dividend / Divisor; +} + +/** + Divides a 64-bit signed integer by a 64-bit signed integer and + generates a 64-bit signed result and an optional 64-bit signed remainder. + + This function divides the 64-bit signed value Dividend by the 64-bit + signed value Divisor and generates a 64-bit signed quotient. If Remainder + is not NULL, then the 64-bit signed remainder is returned in Remainder. + This function returns the 64-bit signed quotient. + + @param Dividend A 64-bit signed value. + @param Divisor A 64-bit signed value. + @param Remainder A pointer to a 64-bit signed value. This parameter is + optional and may be NULL. + + @return Dividend / Divisor. + +**/ +INT64 +EFIAPI +InternalMathDivRemS64x64 ( + IN INT64 Dividend, + IN INT64 Divisor, + OUT INT64 *Remainder OPTIONAL + ) +{ + if (Remainder != NULL) { + *Remainder = Dividend % Divisor; + } + return Dividend / Divisor; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/ModU64x32.c b/MdePkg/HostLibrary/BaseLibHost/ModU64x32.c new file mode 100644 index 00000000000..b64a1fc4f37 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/ModU64x32.c @@ -0,0 +1,45 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT32 +EFIAPI +InternalMathModU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ); + +/** + Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates + a 32-bit unsigned remainder. + + This function divides the 64-bit unsigned value Dividend by the 32-bit + unsigned value Divisor and generates a 32-bit remainder. This function + returns the 32-bit unsigned remainder. + + If Divisor is 0, then ASSERT(). + + @param Dividend A 64-bit unsigned value. + @param Divisor A 32-bit unsigned value. + + @return Dividend % Divisor. + +**/ +UINT32 +EFIAPI +ModU64x32 ( + IN UINT64 Dividend, + IN UINT32 Divisor + ) +{ + ASSERT (Divisor != 0); + return InternalMathModU64x32 (Dividend, Divisor); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/MultS64x64.c b/MdePkg/HostLibrary/BaseLibHost/MultS64x64.c new file mode 100644 index 00000000000..a64790fb150 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/MultS64x64.c @@ -0,0 +1,35 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Multiplies a 64-bit signed integer by a 64-bit signed integer and generates a + 64-bit signed result. + + This function multiplies the 64-bit signed value Multiplicand by the 64-bit + signed value Multiplier and generates a 64-bit signed result. This 64-bit + signed result is returned. + + @param Multiplicand A 64-bit signed value. + @param Multiplier A 64-bit signed value. + + @return Multiplicand * Multiplier. + +**/ +INT64 +EFIAPI +MultS64x64 ( + IN INT64 Multiplicand, + IN INT64 Multiplier + ) +{ + return (INT64)MultU64x64 ((UINT64) Multiplicand, (UINT64) Multiplier); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/MultU64x32.c b/MdePkg/HostLibrary/BaseLibHost/MultU64x32.c new file mode 100644 index 00000000000..ba56b3a0e70 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/MultU64x32.c @@ -0,0 +1,46 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathMultU64x32 ( + IN UINT64 Multiplicand, + IN UINT32 Multiplier + ); + +/** + Multiplies a 64-bit unsigned integer by a 32-bit unsigned integer and + generates a 64-bit unsigned result. + + This function multiplies the 64-bit unsigned value Multiplicand by the 32-bit + unsigned value Multiplier and generates a 64-bit unsigned result. This 64- + bit unsigned result is returned. + + @param Multiplicand A 64-bit unsigned value. + @param Multiplier A 32-bit unsigned value. + + @return Multiplicand * Multiplier. + +**/ +UINT64 +EFIAPI +MultU64x32 ( + IN UINT64 Multiplicand, + IN UINT32 Multiplier + ) +{ + UINT64 Result; + + Result = InternalMathMultU64x32 (Multiplicand, Multiplier); + + return Result; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/MultU64x64.c b/MdePkg/HostLibrary/BaseLibHost/MultU64x64.c new file mode 100644 index 00000000000..0d30efea869 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/MultU64x64.c @@ -0,0 +1,46 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathMultU64x64 ( + IN UINT64 Multiplicand, + IN UINT64 Multiplier + ); + +/** + Multiplies a 64-bit unsigned integer by a 64-bit unsigned integer and + generates a 64-bit unsigned result. + + This function multiplies the 64-bit unsigned value Multiplicand by the 64-bit + unsigned value Multiplier and generates a 64-bit unsigned result. This 64- + bit unsigned result is returned. + + @param Multiplicand A 64-bit unsigned value. + @param Multiplier A 64-bit unsigned value. + + @return Multiplicand * Multiplier. + +**/ +UINT64 +EFIAPI +MultU64x64 ( + IN UINT64 Multiplicand, + IN UINT64 Multiplier + ) +{ + UINT64 Result; + + Result = InternalMathMultU64x64 (Multiplicand, Multiplier); + + return Result; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/RRotU32.c b/MdePkg/HostLibrary/BaseLibHost/RRotU32.c new file mode 100644 index 00000000000..8dddf95c09a --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/RRotU32.c @@ -0,0 +1,38 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Rotates a 32-bit integer right between 0 and 31 bits, filling the high bits + with the low bits that were rotated. + + This function rotates the 32-bit value Operand to the right by Count bits. + The high Count bits are fill with the low Count bits of Operand. The rotated + value is returned. + + If Count is greater than 31, then ASSERT(). + + @param Operand The 32-bit operand to rotate right. + @param Count The number of bits to rotate right. + + @return Operand >> Count. + +**/ +UINT32 +EFIAPI +RRotU32 ( + IN UINT32 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 32); + return (Operand >> Count) | (Operand << (32 - Count)); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/RRotU64.c b/MdePkg/HostLibrary/BaseLibHost/RRotU64.c new file mode 100644 index 00000000000..88fe7622153 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/RRotU64.c @@ -0,0 +1,45 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathRRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ); + +/** + Rotates a 64-bit integer right between 0 and 63 bits, filling the high bits + with the high low bits that were rotated. + + This function rotates the 64-bit value Operand to the right by Count bits. + The high Count bits are fill with the low Count bits of Operand. The rotated + value is returned. + + If Count is greater than 63, then ASSERT(). + + @param Operand The 64-bit operand to rotate right. + @param Count The number of bits to rotate right. + + @return Operand >> Count. + +**/ +UINT64 +EFIAPI +RRotU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 64); + return InternalMathRRotU64 (Operand, Count); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/RShiftU64.c b/MdePkg/HostLibrary/BaseLibHost/RShiftU64.c new file mode 100644 index 00000000000..0a081b31208 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/RShiftU64.c @@ -0,0 +1,44 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +UINT64 +EFIAPI +InternalMathRShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ); + +/** + Shifts a 64-bit integer right between 0 and 63 bits. This high bits are + filled with zeros. The shifted value is returned. + + This function shifts the 64-bit value Operand to the right by Count bits. The + high Count bits are set to zero. The shifted value is returned. + + If Count is greater than 63, then ASSERT(). + + @param Operand The 64-bit operand to shift right. + @param Count The number of bits to shift right. + + @return Operand >> Count. + +**/ +UINT64 +EFIAPI +RShiftU64 ( + IN UINT64 Operand, + IN UINTN Count + ) +{ + ASSERT (Count < 64); + return InternalMathRShiftU64 (Operand, Count); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/SafeString.c b/MdePkg/HostLibrary/BaseLibHost/SafeString.c new file mode 100644 index 00000000000..954cf2cf22b --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SafeString.c @@ -0,0 +1,3693 @@ +/** @file + Safe String functions. + + Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include + +#ifndef RSIZE_MAX +#define RSIZE_MAX (0x1000000) +#endif + +#ifndef ASCII_RSIZE_MAX +#define ASCII_RSIZE_MAX (0x1000000) +#endif + +#define SAFE_STRING_CONSTRAINT_CHECK(Expression, Status) \ + do { \ + ASSERT (Expression); \ + if (!(Expression)) { \ + return Status; \ + } \ + } while (FALSE) + +BOOLEAN +EFIAPI +InternalIsDecimalDigitCharacter ( + IN CHAR16 Char + ); +CHAR16 +EFIAPI +InternalCharToUpper ( + IN CHAR16 Char + ); +BOOLEAN +EFIAPI +InternalIsHexaDecimalDigitCharacter ( + IN CHAR16 Char + ); +UINTN +EFIAPI +InternalHexCharToUintn ( + IN CHAR16 Char + ); +BOOLEAN +EFIAPI +InternalAsciiIsDecimalDigitCharacter ( + IN CHAR8 Char + ); +CHAR8 +EFIAPI +InternalBaseLibAsciiToUpper ( + IN CHAR8 Chr + ); +BOOLEAN +EFIAPI +InternalAsciiIsHexaDecimalDigitCharacter ( + IN CHAR8 Char + ); +UINTN +EFIAPI +InternalAsciiHexCharToUintn ( + IN CHAR8 Char + ); + + +/** + Returns if 2 memory blocks are overlapped. + + @param Base1 Base address of 1st memory block. + @param Size1 Size of 1st memory block. + @param Base2 Base address of 2nd memory block. + @param Size2 Size of 2nd memory block. + + @retval TRUE 2 memory blocks are overlapped. + @retval FALSE 2 memory blocks are not overlapped. +**/ +BOOLEAN +InternalSafeStringIsOverlap ( + IN VOID *Base1, + IN UINTN Size1, + IN VOID *Base2, + IN UINTN Size2 + ) +{ + if ((((UINTN)Base1 >= (UINTN)Base2) && ((UINTN)Base1 < (UINTN)Base2 + Size2)) || + (((UINTN)Base2 >= (UINTN)Base1) && ((UINTN)Base2 < (UINTN)Base1 + Size1))) { + return TRUE; + } + return FALSE; +} + +/** + Returns if 2 Unicode strings are not overlapped. + + @param Str1 Start address of 1st Unicode string. + @param Size1 The number of char in 1st Unicode string, + including terminating null char. + @param Str2 Start address of 2nd Unicode string. + @param Size2 The number of char in 2nd Unicode string, + including terminating null char. + + @retval TRUE 2 Unicode strings are NOT overlapped. + @retval FALSE 2 Unicode strings are overlapped. +**/ +BOOLEAN +InternalSafeStringNoStrOverlap ( + IN CHAR16 *Str1, + IN UINTN Size1, + IN CHAR16 *Str2, + IN UINTN Size2 + ) +{ + return !InternalSafeStringIsOverlap (Str1, Size1 * sizeof(CHAR16), Str2, Size2 * sizeof(CHAR16)); +} + +/** + Returns if 2 Ascii strings are not overlapped. + + @param Str1 Start address of 1st Ascii string. + @param Size1 The number of char in 1st Ascii string, + including terminating null char. + @param Str2 Start address of 2nd Ascii string. + @param Size2 The number of char in 2nd Ascii string, + including terminating null char. + + @retval TRUE 2 Ascii strings are NOT overlapped. + @retval FALSE 2 Ascii strings are overlapped. +**/ +BOOLEAN +InternalSafeStringNoAsciiStrOverlap ( + IN CHAR8 *Str1, + IN UINTN Size1, + IN CHAR8 *Str2, + IN UINTN Size2 + ) +{ + return !InternalSafeStringIsOverlap (Str1, Size1, Str2, Size2); +} + +/** + Returns the length of a Null-terminated Unicode string. + + This function is similar as strlen_s defined in C11. + + If String is not aligned on a 16-bit boundary, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + @param MaxSize The maximum number of Destination Unicode + char, including terminating null char. + + @retval 0 If String is NULL. + @retval MaxSize If there is no null character in the first MaxSize characters of String. + @return The number of characters that percede the terminating null character. + +**/ +UINTN +EFIAPI +StrnLenS ( + IN CONST CHAR16 *String, + IN UINTN MaxSize + ) +{ + UINTN Length; + + ASSERT (((UINTN) String & BIT0) == 0); + + // + // If String is a null pointer or MaxSize is 0, then the StrnLenS function returns zero. + // + if ((String == NULL) || (MaxSize == 0)) { + return 0; + } + + // + // Otherwise, the StrnLenS function returns the number of characters that precede the + // terminating null character. If there is no null character in the first MaxSize characters of + // String then StrnLenS returns MaxSize. At most the first MaxSize characters of String shall + // be accessed by StrnLenS. + // + Length = 0; + while (String[Length] != 0) { + if (Length >= MaxSize - 1) { + return MaxSize; + } + Length++; + } + return Length; +} + +/** + Returns the size of a Null-terminated Unicode string in bytes, including the + Null terminator. + + This function returns the size of the Null-terminated Unicode string + specified by String in bytes, including the Null terminator. + + If String is not aligned on a 16-bit boundary, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + @param MaxSize The maximum number of Destination Unicode + char, including the Null terminator. + + @retval 0 If String is NULL. + @retval (sizeof (CHAR16) * (MaxSize + 1)) + If there is no Null terminator in the first MaxSize characters of + String. + @return The size of the Null-terminated Unicode string in bytes, including + the Null terminator. + +**/ +UINTN +EFIAPI +StrnSizeS ( + IN CONST CHAR16 *String, + IN UINTN MaxSize + ) +{ + // + // If String is a null pointer, then the StrnSizeS function returns zero. + // + if (String == NULL) { + return 0; + } + + // + // Otherwise, the StrnSizeS function returns the size of the Null-terminated + // Unicode string in bytes, including the Null terminator. If there is no + // Null terminator in the first MaxSize characters of String, then StrnSizeS + // returns (sizeof (CHAR16) * (MaxSize + 1)) to keep a consistent map with + // the StrnLenS function. + // + return (StrnLenS (String, MaxSize) + 1) * sizeof (*String); +} + +/** + Copies the string pointed to by Source (including the terminating null char) + to the array pointed to by Destination. + + This function is similar as strcpy_s defined in C11. + + If Destination is not aligned on a 16-bit boundary, then ASSERT(). + If Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode + char, including terminating null char. + @param Source A pointer to a Null-terminated Unicode string. + + @retval RETURN_SUCCESS String is copied. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +StrCpyS ( + OUT CHAR16 *Destination, + IN UINTN DestMax, + IN CONST CHAR16 *Source + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. DestMax shall be greater than StrnLenS(Source, DestMax). + // + SourceLen = StrnLenS (Source, DestMax); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 5. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The StrCpyS function copies the string pointed to by Source (including the terminating + // null character) into the array pointed to by Destination. + // + while (*Source != 0) { + *(Destination++) = *(Source++); + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Copies not more than Length successive char from the string pointed to by + Source to the array pointed to by Destination. If no null char is copied from + Source, then Destination[Length] is always set to null. + + This function is similar as strncpy_s defined in C11. + + If Length > 0 and Destination is not aligned on a 16-bit boundary, then ASSERT(). + If Length > 0 and Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode + char, including terminating null char. + @param Source A pointer to a Null-terminated Unicode string. + @param Length The maximum number of Unicode characters to copy. + + @retval RETURN_SUCCESS String is copied. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than + MIN(StrLen(Source), Length). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +StrnCpyS ( + OUT CHAR16 *Destination, + IN UINTN DestMax, + IN CONST CHAR16 *Source, + IN UINTN Length + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither DestMax nor Length shall be greater than RSIZE_MAX + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. If Length is not less than DestMax, then DestMax shall be greater than StrnLenS(Source, DestMax). + // + SourceLen = StrnLenS (Source, MIN (DestMax, Length)); + if (Length >= DestMax) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 5. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The StrnCpyS function copies not more than Length successive characters (characters that + // follow a null character are not copied) from the array pointed to by Source to the array + // pointed to by Destination. If no null character was copied from Source, then Destination[Length] is set to a null + // character. + // + while ((SourceLen > 0) && (*Source != 0)) { + *(Destination++) = *(Source++); + SourceLen--; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Appends a copy of the string pointed to by Source (including the terminating + null char) to the end of the string pointed to by Destination. + + This function is similar as strcat_s defined in C11. + + If Destination is not aligned on a 16-bit boundary, then ASSERT(). + If Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode + char, including terminating null char. + @param Source A pointer to a Null-terminated Unicode string. + + @retval RETURN_SUCCESS String is appended. + @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than + StrLen(Destination). + @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT + greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +StrCatS ( + IN OUT CHAR16 *Destination, + IN UINTN DestMax, + IN CONST CHAR16 *Source + ) +{ + UINTN DestLen; + UINTN CopyLen; + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // Let CopyLen denote the value DestMax - StrnLenS(Destination, DestMax) upon entry to StrCatS. + // + DestLen = StrnLenS (Destination, DestMax); + CopyLen = DestMax - DestLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. CopyLen shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); + + // + // 5. CopyLen shall be greater than StrnLenS(Source, CopyLen). + // + SourceLen = StrnLenS (Source, CopyLen); + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 6. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The StrCatS function appends a copy of the string pointed to by Source (including the + // terminating null character) to the end of the string pointed to by Destination. The initial character + // from Source overwrites the null character at the end of Destination. + // + Destination = Destination + DestLen; + while (*Source != 0) { + *(Destination++) = *(Source++); + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Appends not more than Length successive char from the string pointed to by + Source to the end of the string pointed to by Destination. If no null char is + copied from Source, then Destination[StrLen(Destination) + Length] is always + set to null. + + This function is similar as strncat_s defined in C11. + + If Destination is not aligned on a 16-bit boundary, then ASSERT(). + If Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode + char, including terminating null char. + @param Source A pointer to a Null-terminated Unicode string. + @param Length The maximum number of Unicode characters to copy. + + @retval RETURN_SUCCESS String is appended. + @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than + StrLen(Destination). + @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT + greater than MIN(StrLen(Source), Length). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +StrnCatS ( + IN OUT CHAR16 *Destination, + IN UINTN DestMax, + IN CONST CHAR16 *Source, + IN UINTN Length + ) +{ + UINTN DestLen; + UINTN CopyLen; + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // Let CopyLen denote the value DestMax - StrnLenS(Destination, DestMax) upon entry to StrnCatS. + // + DestLen = StrnLenS (Destination, DestMax); + CopyLen = DestMax - DestLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither DestMax nor Length shall be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. CopyLen shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); + + // + // 5. If Length is not less than CopyLen, then CopyLen shall be greater than StrnLenS(Source, CopyLen). + // + SourceLen = StrnLenS (Source, MIN (CopyLen, Length)); + if (Length >= CopyLen) { + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 6. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The StrnCatS function appends not more than Length successive characters (characters + // that follow a null character are not copied) from the array pointed to by Source to the end of + // the string pointed to by Destination. The initial character from Source overwrites the null character at + // the end of Destination. If no null character was copied from Source, then Destination[DestMax-CopyLen+Length] is set to + // a null character. + // + Destination = Destination + DestLen; + while ((SourceLen > 0) && (*Source != 0)) { + *(Destination++) = *(Source++); + SourceLen--; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode decimal string to a value of type UINTN. + + This function outputs a value of type UINTN by interpreting the contents of + the Unicode string specified by String as a decimal number. The format of the + input Unicode string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before + [decimal digits]. The running zero in the beginning of [decimal digits] will + be ignored. Then, the function stops at the first character that is a not a + valid decimal character or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid decimal digits in the above format, then 0 is stored + at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINTN, then + MAX_UINTN is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + decimal digits right after the optional pad spaces, the value of String is + stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumUnicodeStringLength is not + zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINTN. + +**/ +RETURN_STATUS +EFIAPI +StrDecimalToUintnS ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT UINTN *Data + ) +{ + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == L' ') || (*String == L'\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == L'0') { + String++; + } + + *Data = 0; + + while (InternalIsDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINTN, then MAX_UINTN is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > ((MAX_UINTN - (*String - L'0')) / 10)) { + *Data = MAX_UINTN; + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = *Data * 10 + (*String - L'0'); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode decimal string to a value of type UINT64. + + This function outputs a value of type UINT64 by interpreting the contents of + the Unicode string specified by String as a decimal number. The format of the + input Unicode string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before + [decimal digits]. The running zero in the beginning of [decimal digits] will + be ignored. Then, the function stops at the first character that is a not a + valid decimal character or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid decimal digits in the above format, then 0 is stored + at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINT64, then + MAX_UINT64 is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + decimal digits right after the optional pad spaces, the value of String is + stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumUnicodeStringLength is not + zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINT64. + +**/ +RETURN_STATUS +EFIAPI +StrDecimalToUint64S ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT UINT64 *Data + ) +{ + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == L' ') || (*String == L'\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == L'0') { + String++; + } + + *Data = 0; + + while (InternalIsDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINT64, then MAX_UINT64 is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > DivU64x32 (MAX_UINT64 - (*String - L'0'), 10)) { + *Data = MAX_UINT64; + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = MultU64x32 (*Data, 10) + (*String - L'0'); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode hexadecimal string to a value of type + UINTN. + + This function outputs a value of type UINTN by interpreting the contents of + the Unicode string specified by String as a hexadecimal number. The format of + the input Unicode string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. + If "x" appears in the input string, it must be prefixed with at least one 0. + The function will ignore the pad space, which includes spaces or tab + characters, before [zeros], [x] or [hexadecimal digit]. The running zero + before [x] or [hexadecimal digit] will be ignored. Then, the decoding starts + after [x] or the first valid hexadecimal digit. Then, the function stops at + the first character that is a not a valid hexadecimal character or NULL, + whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid hexadecimal digits in the above format, then 0 is + stored at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINTN, then + MAX_UINTN is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + hexadecimal digits right after the optional pad spaces, the value of String + is stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumUnicodeStringLength is not + zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINTN. + +**/ +RETURN_STATUS +EFIAPI +StrHexToUintnS ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT UINTN *Data + ) +{ + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == L' ') || (*String == L'\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == L'0') { + String++; + } + + if (InternalCharToUpper (*String) == L'X') { + if (*(String - 1) != L'0') { + *Data = 0; + return RETURN_SUCCESS; + } + // + // Skip the 'X' + // + String++; + } + + *Data = 0; + + while (InternalIsHexaDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINTN, then MAX_UINTN is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > ((MAX_UINTN - InternalHexCharToUintn (*String)) >> 4)) { + *Data = MAX_UINTN; + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = (*Data << 4) + InternalHexCharToUintn (*String); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode hexadecimal string to a value of type + UINT64. + + This function outputs a value of type UINT64 by interpreting the contents of + the Unicode string specified by String as a hexadecimal number. The format of + the input Unicode string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. + If "x" appears in the input string, it must be prefixed with at least one 0. + The function will ignore the pad space, which includes spaces or tab + characters, before [zeros], [x] or [hexadecimal digit]. The running zero + before [x] or [hexadecimal digit] will be ignored. Then, the decoding starts + after [x] or the first valid hexadecimal digit. Then, the function stops at + the first character that is a not a valid hexadecimal character or NULL, + whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid hexadecimal digits in the above format, then 0 is + stored at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINT64, then + MAX_UINT64 is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + hexadecimal digits right after the optional pad spaces, the value of String + is stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumUnicodeStringLength is not + zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINT64. + +**/ +RETURN_STATUS +EFIAPI +StrHexToUint64S ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT UINT64 *Data + ) +{ + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == L' ') || (*String == L'\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == L'0') { + String++; + } + + if (InternalCharToUpper (*String) == L'X') { + if (*(String - 1) != L'0') { + *Data = 0; + return RETURN_SUCCESS; + } + // + // Skip the 'X' + // + String++; + } + + *Data = 0; + + while (InternalIsHexaDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINT64, then MAX_UINT64 is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > RShiftU64 (MAX_UINT64 - InternalHexCharToUintn (*String), 4)) { + *Data = MAX_UINT64; + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = LShiftU64 (*Data, 4) + InternalHexCharToUintn (*String); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode string to IPv6 address and prefix length. + + This function outputs a value of type IPv6_ADDRESS and may output a value + of type UINT8 by interpreting the contents of the Unicode string specified + by String. The format of the input Unicode string String is as follows: + + X:X:X:X:X:X:X:X[/P] + + X contains one to four hexadecimal digit characters in the range [0-9], [a-f] and + [A-F]. X is converted to a value of type UINT16, whose low byte is stored in low + memory address and high byte is stored in high memory address. P contains decimal + digit characters in the range [0-9]. The running zero in the beginning of P will + be ignored. /P is optional. + + When /P is not in the String, the function stops at the first character that is + not a valid hexadecimal digit character after eight X's are converted. + + When /P is in the String, the function stops at the first character that is not + a valid decimal digit character after P is converted. + + "::" can be used to compress one or more groups of X when X contains only 0. + The "::" can only appear once in the String. + + If String is NULL, then ASSERT(). + + If Address is NULL, then ASSERT(). + + If String is not aligned in a 16-bit boundary, then ASSERT(). + + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If EndPointer is not NULL and Address is translated from String, a pointer + to the character that stopped the scan is stored at the location pointed to + by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Address Pointer to the converted IPv6 address. + @param PrefixLength Pointer to the converted IPv6 address prefix + length. MAX_UINT8 is returned when /P is + not in the String. + + @retval RETURN_SUCCESS Address is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If X contains more than four hexadecimal + digit characters. + If String contains "::" and number of X + is not less than 8. + If P starts with character that is not a + valid decimal digit character. + If the decimal number converted from P + exceeds 128. + +**/ +RETURN_STATUS +EFIAPI +StrToIpv6Address ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT IPv6_ADDRESS *Address, + OUT UINT8 *PrefixLength OPTIONAL + ) +{ + RETURN_STATUS Status; + UINTN AddressIndex; + UINTN Uintn; + IPv6_ADDRESS LocalAddress; + UINT8 LocalPrefixLength; + CONST CHAR16 *Pointer; + CHAR16 *End; + UINTN CompressStart; + BOOLEAN ExpectPrefix; + + LocalPrefixLength = MAX_UINT8; + CompressStart = ARRAY_SIZE (Address->Addr); + ExpectPrefix = FALSE; + + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. None of String or Guid shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); + + for (Pointer = String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { + if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) { + if (*Pointer != L':') { + // + // ":" or "/" should be followed by digit characters. + // + return RETURN_UNSUPPORTED; + } + + // + // Meet second ":" after previous ":" or "/" + // or meet first ":" in the beginning of String. + // + if (ExpectPrefix) { + // + // ":" shall not be after "/" + // + return RETURN_UNSUPPORTED; + } + + if (CompressStart != ARRAY_SIZE (Address->Addr) || AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // "::" can only appear once. + // "::" can only appear when address is not full length. + // + return RETURN_UNSUPPORTED; + } else { + // + // Remember the start of zero compressing. + // + CompressStart = AddressIndex; + Pointer++; + + if (CompressStart == 0) { + if (*Pointer != L':') { + // + // Single ":" shall not be in the beginning of String. + // + return RETURN_UNSUPPORTED; + } + Pointer++; + } + } + } + + if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) { + if (*Pointer == L'/') { + // + // Might be optional "/P" after "::". + // + if (CompressStart != AddressIndex) { + return RETURN_UNSUPPORTED; + } + } else { + break; + } + } else { + if (!ExpectPrefix) { + // + // Get X. + // + Status = StrHexToUintnS (Pointer, &End, &Uintn); + if (RETURN_ERROR (Status) || End - Pointer > 4) { + // + // Number of hexadecimal digit characters is no more than 4. + // + return RETURN_UNSUPPORTED; + } + Pointer = End; + // + // Uintn won't exceed MAX_UINT16 if number of hexadecimal digit characters is no more than 4. + // + ASSERT (AddressIndex + 1 < ARRAY_SIZE (Address->Addr)); + LocalAddress.Addr[AddressIndex] = (UINT8) ((UINT16) Uintn >> 8); + LocalAddress.Addr[AddressIndex + 1] = (UINT8) Uintn; + AddressIndex += 2; + } else { + // + // Get P, then exit the loop. + // + Status = StrDecimalToUintnS (Pointer, &End, &Uintn); + if (RETURN_ERROR (Status) || End == Pointer || Uintn > 128) { + // + // Prefix length should not exceed 128. + // + return RETURN_UNSUPPORTED; + } + LocalPrefixLength = (UINT8) Uintn; + Pointer = End; + break; + } + } + + // + // Skip ':' or "/" + // + if (*Pointer == L'/') { + ExpectPrefix = TRUE; + } else if (*Pointer == L':') { + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // Meet additional ":" after all 8 16-bit address + // + break; + } + } else { + // + // Meet other character that is not "/" or ":" after all 8 16-bit address + // + break; + } + Pointer++; + } + + if ((AddressIndex == ARRAY_SIZE (Address->Addr) && CompressStart != ARRAY_SIZE (Address->Addr)) || + (AddressIndex != ARRAY_SIZE (Address->Addr) && CompressStart == ARRAY_SIZE (Address->Addr)) + ) { + // + // Full length of address shall not have compressing zeros. + // Non-full length of address shall have compressing zeros. + // + return RETURN_UNSUPPORTED; + } + CopyMem (&Address->Addr[0], &LocalAddress.Addr[0], CompressStart); + ZeroMem (&Address->Addr[CompressStart], ARRAY_SIZE (Address->Addr) - AddressIndex); + if (AddressIndex > CompressStart) { + CopyMem ( + &Address->Addr[CompressStart + ARRAY_SIZE (Address->Addr) - AddressIndex], + &LocalAddress.Addr[CompressStart], + AddressIndex - CompressStart + ); + } + + if (PrefixLength != NULL) { + *PrefixLength = LocalPrefixLength; + } + if (EndPointer != NULL) { + *EndPointer = (CHAR16 *) Pointer; + } + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode string to IPv4 address and prefix length. + + This function outputs a value of type IPv4_ADDRESS and may output a value + of type UINT8 by interpreting the contents of the Unicode string specified + by String. The format of the input Unicode string String is as follows: + + D.D.D.D[/P] + + D and P are decimal digit characters in the range [0-9]. The running zero in + the beginning of D and P will be ignored. /P is optional. + + When /P is not in the String, the function stops at the first character that is + not a valid decimal digit character after four D's are converted. + + When /P is in the String, the function stops at the first character that is not + a valid decimal digit character after P is converted. + + If String is NULL, then ASSERT(). + + If Address is NULL, then ASSERT(). + + If String is not aligned in a 16-bit boundary, then ASSERT(). + + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + If EndPointer is not NULL and Address is translated from String, a pointer + to the character that stopped the scan is stored at the location pointed to + by EndPointer. + + @param String Pointer to a Null-terminated Unicode string. + @param EndPointer Pointer to character that stops scan. + @param Address Pointer to the converted IPv4 address. + @param PrefixLength Pointer to the converted IPv4 address prefix + length. MAX_UINT8 is returned when /P is + not in the String. + + @retval RETURN_SUCCESS Address is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If String is not in the correct format. + If any decimal number converted from D + exceeds 255. + If the decimal number converted from P + exceeds 32. + +**/ +RETURN_STATUS +EFIAPI +StrToIpv4Address ( + IN CONST CHAR16 *String, + OUT CHAR16 **EndPointer, OPTIONAL + OUT IPv4_ADDRESS *Address, + OUT UINT8 *PrefixLength OPTIONAL + ) +{ + RETURN_STATUS Status; + UINTN AddressIndex; + UINTN Uintn; + IPv4_ADDRESS LocalAddress; + UINT8 LocalPrefixLength; + CHAR16 *Pointer; + + LocalPrefixLength = MAX_UINT8; + + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. None of String or Guid shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); + + for (Pointer = (CHAR16 *) String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { + if (!InternalIsDecimalDigitCharacter (*Pointer)) { + // + // D or P contains invalid characters. + // + break; + } + + // + // Get D or P. + // + Status = StrDecimalToUintnS ((CONST CHAR16 *) Pointer, &Pointer, &Uintn); + if (RETURN_ERROR (Status)) { + return RETURN_UNSUPPORTED; + } + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // It's P. + // + if (Uintn > 32) { + return RETURN_UNSUPPORTED; + } + LocalPrefixLength = (UINT8) Uintn; + } else { + // + // It's D. + // + if (Uintn > MAX_UINT8) { + return RETURN_UNSUPPORTED; + } + LocalAddress.Addr[AddressIndex] = (UINT8) Uintn; + AddressIndex++; + } + + // + // Check the '.' or '/', depending on the AddressIndex. + // + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + if (*Pointer == L'/') { + // + // '/P' is in the String. + // Skip "/" and get P in next loop. + // + Pointer++; + } else { + // + // '/P' is not in the String. + // + break; + } + } else if (AddressIndex < ARRAY_SIZE (Address->Addr)) { + if (*Pointer == L'.') { + // + // D should be followed by '.' + // + Pointer++; + } else { + return RETURN_UNSUPPORTED; + } + } + } + + if (AddressIndex < ARRAY_SIZE (Address->Addr)) { + return RETURN_UNSUPPORTED; + } + + CopyMem (Address, &LocalAddress, sizeof (*Address)); + if (PrefixLength != NULL) { + *PrefixLength = LocalPrefixLength; + } + if (EndPointer != NULL) { + *EndPointer = Pointer; + } + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode GUID string to a value of type + EFI_GUID. + + This function outputs a GUID value by interpreting the contents of + the Unicode string specified by String. The format of the input + Unicode string String consists of 36 characters, as follows: + + aabbccdd-eeff-gghh-iijj-kkllmmnnoopp + + The pairs aa - pp are two characters in the range [0-9], [a-f] and + [A-F], with each pair representing a single byte hexadecimal value. + + The mapping between String and the EFI_GUID structure is as follows: + aa Data1[24:31] + bb Data1[16:23] + cc Data1[8:15] + dd Data1[0:7] + ee Data2[8:15] + ff Data2[0:7] + gg Data3[8:15] + hh Data3[0:7] + ii Data4[0:7] + jj Data4[8:15] + kk Data4[16:23] + ll Data4[24:31] + mm Data4[32:39] + nn Data4[40:47] + oo Data4[48:55] + pp Data4[56:63] + + If String is NULL, then ASSERT(). + If Guid is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + + @param String Pointer to a Null-terminated Unicode string. + @param Guid Pointer to the converted GUID. + + @retval RETURN_SUCCESS Guid is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If String is not as the above format. + +**/ +RETURN_STATUS +EFIAPI +StrToGuid ( + IN CONST CHAR16 *String, + OUT GUID *Guid + ) +{ + RETURN_STATUS Status; + GUID LocalGuid; + + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. None of String or Guid shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Guid != NULL), RETURN_INVALID_PARAMETER); + + // + // Get aabbccdd in big-endian. + // + Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data1), (UINT8 *) &LocalGuid.Data1, sizeof (LocalGuid.Data1)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data1)] != L'-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data1 = SwapBytes32 (LocalGuid.Data1); + String += 2 * sizeof (LocalGuid.Data1) + 1; + + // + // Get eeff in big-endian. + // + Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data2), (UINT8 *) &LocalGuid.Data2, sizeof (LocalGuid.Data2)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data2)] != L'-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data2 = SwapBytes16 (LocalGuid.Data2); + String += 2 * sizeof (LocalGuid.Data2) + 1; + + // + // Get gghh in big-endian. + // + Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data3), (UINT8 *) &LocalGuid.Data3, sizeof (LocalGuid.Data3)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data3)] != L'-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data3 = SwapBytes16 (LocalGuid.Data3); + String += 2 * sizeof (LocalGuid.Data3) + 1; + + // + // Get iijj. + // + Status = StrHexToBytes (String, 2 * 2, &LocalGuid.Data4[0], 2); + if (RETURN_ERROR (Status) || String[2 * 2] != L'-') { + return RETURN_UNSUPPORTED; + } + String += 2 * 2 + 1; + + // + // Get kkllmmnnoopp. + // + Status = StrHexToBytes (String, 2 * 6, &LocalGuid.Data4[2], 6); + if (RETURN_ERROR (Status)) { + return RETURN_UNSUPPORTED; + } + + CopyGuid (Guid, &LocalGuid); + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode hexadecimal string to a byte array. + + This function outputs a byte array by interpreting the contents of + the Unicode string specified by String in hexadecimal format. The format of + the input Unicode string String is: + + [XX]* + + X is a hexadecimal digit character in the range [0-9], [a-f] and [A-F]. + The function decodes every two hexadecimal digit characters as one byte. The + decoding stops after Length of characters and outputs Buffer containing + (Length / 2) bytes. + + If String is not aligned in a 16-bit boundary, then ASSERT(). + + If String is NULL, then ASSERT(). + + If Buffer is NULL, then ASSERT(). + + If Length is not multiple of 2, then ASSERT(). + + If PcdMaximumUnicodeStringLength is not zero and Length is greater than + PcdMaximumUnicodeStringLength, then ASSERT(). + + If MaxBufferSize is less than (Length / 2), then ASSERT(). + + @param String Pointer to a Null-terminated Unicode string. + @param Length The number of Unicode characters to decode. + @param Buffer Pointer to the converted bytes array. + @param MaxBufferSize The maximum size of Buffer. + + @retval RETURN_SUCCESS Buffer is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If Length is not multiple of 2. + If PcdMaximumUnicodeStringLength is not zero, + and Length is greater than + PcdMaximumUnicodeStringLength. + @retval RETURN_UNSUPPORTED If Length of characters from String contain + a character that is not valid hexadecimal + digit characters, or a Null-terminator. + @retval RETURN_BUFFER_TOO_SMALL If MaxBufferSize is less than (Length / 2). +**/ +RETURN_STATUS +EFIAPI +StrHexToBytes ( + IN CONST CHAR16 *String, + IN UINTN Length, + OUT UINT8 *Buffer, + IN UINTN MaxBufferSize + ) +{ + UINTN Index; + + ASSERT (((UINTN) String & BIT0) == 0); + + // + // 1. None of String or Buffer shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Buffer != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Length shall not be greater than RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. Length shall not be odd. + // + SAFE_STRING_CONSTRAINT_CHECK (((Length & BIT0) == 0), RETURN_INVALID_PARAMETER); + + // + // 4. MaxBufferSize shall equal to or greater than Length / 2. + // + SAFE_STRING_CONSTRAINT_CHECK ((MaxBufferSize >= Length / 2), RETURN_BUFFER_TOO_SMALL); + + // + // 5. String shall not contains invalid hexadecimal digits. + // + for (Index = 0; Index < Length; Index++) { + if (!InternalIsHexaDecimalDigitCharacter (String[Index])) { + break; + } + } + if (Index != Length) { + return RETURN_UNSUPPORTED; + } + + // + // Convert the hex string to bytes. + // + for(Index = 0; Index < Length; Index++) { + + // + // For even characters, write the upper nibble for each buffer byte, + // and for even characters, the lower nibble. + // + if ((Index & BIT0) == 0) { + Buffer[Index / 2] = (UINT8) InternalHexCharToUintn (String[Index]) << 4; + } else { + Buffer[Index / 2] |= (UINT8) InternalHexCharToUintn (String[Index]); + } + } + return RETURN_SUCCESS; +} + +/** + Returns the length of a Null-terminated Ascii string. + + This function is similar as strlen_s defined in C11. + + @param String A pointer to a Null-terminated Ascii string. + @param MaxSize The maximum number of Destination Ascii + char, including terminating null char. + + @retval 0 If String is NULL. + @retval MaxSize If there is no null character in the first MaxSize characters of String. + @return The number of characters that percede the terminating null character. + +**/ +UINTN +EFIAPI +AsciiStrnLenS ( + IN CONST CHAR8 *String, + IN UINTN MaxSize + ) +{ + UINTN Length; + + // + // If String is a null pointer or MaxSize is 0, then the AsciiStrnLenS function returns zero. + // + if ((String == NULL) || (MaxSize == 0)) { + return 0; + } + + // + // Otherwise, the AsciiStrnLenS function returns the number of characters that precede the + // terminating null character. If there is no null character in the first MaxSize characters of + // String then AsciiStrnLenS returns MaxSize. At most the first MaxSize characters of String shall + // be accessed by AsciiStrnLenS. + // + Length = 0; + while (String[Length] != 0) { + if (Length >= MaxSize - 1) { + return MaxSize; + } + Length++; + } + return Length; +} + +/** + Returns the size of a Null-terminated Ascii string in bytes, including the + Null terminator. + + This function returns the size of the Null-terminated Ascii string specified + by String in bytes, including the Null terminator. + + @param String A pointer to a Null-terminated Ascii string. + @param MaxSize The maximum number of Destination Ascii + char, including the Null terminator. + + @retval 0 If String is NULL. + @retval (sizeof (CHAR8) * (MaxSize + 1)) + If there is no Null terminator in the first MaxSize characters of + String. + @return The size of the Null-terminated Ascii string in bytes, including the + Null terminator. + +**/ +UINTN +EFIAPI +AsciiStrnSizeS ( + IN CONST CHAR8 *String, + IN UINTN MaxSize + ) +{ + // + // If String is a null pointer, then the AsciiStrnSizeS function returns + // zero. + // + if (String == NULL) { + return 0; + } + + // + // Otherwise, the AsciiStrnSizeS function returns the size of the + // Null-terminated Ascii string in bytes, including the Null terminator. If + // there is no Null terminator in the first MaxSize characters of String, + // then AsciiStrnSizeS returns (sizeof (CHAR8) * (MaxSize + 1)) to keep a + // consistent map with the AsciiStrnLenS function. + // + return (AsciiStrnLenS (String, MaxSize) + 1) * sizeof (*String); +} + +/** + Copies the string pointed to by Source (including the terminating null char) + to the array pointed to by Destination. + + This function is similar as strcpy_s defined in C11. + + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Ascii string. + @param DestMax The maximum number of Destination Ascii + char, including terminating null char. + @param Source A pointer to a Null-terminated Ascii string. + + @retval RETURN_SUCCESS String is copied. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +AsciiStrCpyS ( + OUT CHAR8 *Destination, + IN UINTN DestMax, + IN CONST CHAR8 *Source + ) +{ + UINTN SourceLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. DestMax shall be greater than AsciiStrnLenS(Source, DestMax). + // + SourceLen = AsciiStrnLenS (Source, DestMax); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 5. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The AsciiStrCpyS function copies the string pointed to by Source (including the terminating + // null character) into the array pointed to by Destination. + // + while (*Source != 0) { + *(Destination++) = *(Source++); + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Copies not more than Length successive char from the string pointed to by + Source to the array pointed to by Destination. If no null char is copied from + Source, then Destination[Length] is always set to null. + + This function is similar as strncpy_s defined in C11. + + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Ascii string. + @param DestMax The maximum number of Destination Ascii + char, including terminating null char. + @param Source A pointer to a Null-terminated Ascii string. + @param Length The maximum number of Ascii characters to copy. + + @retval RETURN_SUCCESS String is copied. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than + MIN(StrLen(Source), Length). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +AsciiStrnCpyS ( + OUT CHAR8 *Destination, + IN UINTN DestMax, + IN CONST CHAR8 *Source, + IN UINTN Length + ) +{ + UINTN SourceLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. If Length is not less than DestMax, then DestMax shall be greater than AsciiStrnLenS(Source, DestMax). + // + SourceLen = AsciiStrnLenS (Source, MIN (DestMax, Length)); + if (Length >= DestMax) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 5. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The AsciiStrnCpyS function copies not more than Length successive characters (characters that + // follow a null character are not copied) from the array pointed to by Source to the array + // pointed to by Destination. If no null character was copied from Source, then Destination[Length] is set to a null + // character. + // + while ((SourceLen > 0) && (*Source != 0)) { + *(Destination++) = *(Source++); + SourceLen--; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Appends a copy of the string pointed to by Source (including the terminating + null char) to the end of the string pointed to by Destination. + + This function is similar as strcat_s defined in C11. + + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Ascii string. + @param DestMax The maximum number of Destination Ascii + char, including terminating null char. + @param Source A pointer to a Null-terminated Ascii string. + + @retval RETURN_SUCCESS String is appended. + @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than + StrLen(Destination). + @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT + greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +AsciiStrCatS ( + IN OUT CHAR8 *Destination, + IN UINTN DestMax, + IN CONST CHAR8 *Source + ) +{ + UINTN DestLen; + UINTN CopyLen; + UINTN SourceLen; + + // + // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrCatS. + // + DestLen = AsciiStrnLenS (Destination, DestMax); + CopyLen = DestMax - DestLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. CopyLen shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); + + // + // 5. CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). + // + SourceLen = AsciiStrnLenS (Source, CopyLen); + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 6. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The AsciiStrCatS function appends a copy of the string pointed to by Source (including the + // terminating null character) to the end of the string pointed to by Destination. The initial character + // from Source overwrites the null character at the end of Destination. + // + Destination = Destination + DestLen; + while (*Source != 0) { + *(Destination++) = *(Source++); + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Appends not more than Length successive char from the string pointed to by + Source to the end of the string pointed to by Destination. If no null char is + copied from Source, then Destination[StrLen(Destination) + Length] is always + set to null. + + This function is similar as strncat_s defined in C11. + + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Destination A pointer to a Null-terminated Ascii string. + @param DestMax The maximum number of Destination Ascii + char, including terminating null char. + @param Source A pointer to a Null-terminated Ascii string. + @param Length The maximum number of Ascii characters to copy. + + @retval RETURN_SUCCESS String is appended. + @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than + StrLen(Destination). + @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT + greater than MIN(StrLen(Source), Length). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. +**/ +RETURN_STATUS +EFIAPI +AsciiStrnCatS ( + IN OUT CHAR8 *Destination, + IN UINTN DestMax, + IN CONST CHAR8 *Source, + IN UINTN Length + ) +{ + UINTN DestLen; + UINTN CopyLen; + UINTN SourceLen; + + // + // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrnCatS. + // + DestLen = AsciiStrnLenS (Destination, DestMax); + CopyLen = DestMax - DestLen; + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. CopyLen shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); + + // + // 5. If Length is not less than CopyLen, then CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). + // + SourceLen = AsciiStrnLenS (Source, MIN (CopyLen, Length)); + if (Length >= CopyLen) { + SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 6. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // The AsciiStrnCatS function appends not more than Length successive characters (characters + // that follow a null character are not copied) from the array pointed to by Source to the end of + // the string pointed to by Destination. The initial character from Source overwrites the null character at + // the end of Destination. If no null character was copied from Source, then Destination[DestMax-CopyLen+Length] is set to + // a null character. + // + Destination = Destination + DestLen; + while ((SourceLen > 0) && (*Source != 0)) { + *(Destination++) = *(Source++); + SourceLen--; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Ascii decimal string to a value of type UINTN. + + This function outputs a value of type UINTN by interpreting the contents of + the Ascii string specified by String as a decimal number. The format of the + input Ascii string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before + [decimal digits]. The running zero in the beginning of [decimal digits] will + be ignored. Then, the function stops at the first character that is a not a + valid decimal character or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength Ascii characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid decimal digits in the above format, then 0 is stored + at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINTN, then + MAX_UINTN is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + decimal digits right after the optional pad spaces, the value of String is + stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Ascii string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumAsciiStringLength is not zero, + and String contains more than + PcdMaximumAsciiStringLength Ascii + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINTN. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrDecimalToUintnS ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT UINTN *Data + ) +{ + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == ' ') || (*String == '\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == '0') { + String++; + } + + *Data = 0; + + while (InternalAsciiIsDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINTN, then MAX_UINTN is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > ((MAX_UINTN - (*String - '0')) / 10)) { + *Data = MAX_UINTN; + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = *Data * 10 + (*String - '0'); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Ascii decimal string to a value of type UINT64. + + This function outputs a value of type UINT64 by interpreting the contents of + the Ascii string specified by String as a decimal number. The format of the + input Ascii string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before + [decimal digits]. The running zero in the beginning of [decimal digits] will + be ignored. Then, the function stops at the first character that is a not a + valid decimal character or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength Ascii characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid decimal digits in the above format, then 0 is stored + at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINT64, then + MAX_UINT64 is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + decimal digits right after the optional pad spaces, the value of String is + stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Ascii string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumAsciiStringLength is not zero, + and String contains more than + PcdMaximumAsciiStringLength Ascii + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINT64. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrDecimalToUint64S ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT UINT64 *Data + ) +{ + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == ' ') || (*String == '\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == '0') { + String++; + } + + *Data = 0; + + while (InternalAsciiIsDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINT64, then MAX_UINT64 is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > DivU64x32 (MAX_UINT64 - (*String - '0'), 10)) { + *Data = MAX_UINT64; + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = MultU64x32 (*Data, 10) + (*String - '0'); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Ascii hexadecimal string to a value of type UINTN. + + This function outputs a value of type UINTN by interpreting the contents of + the Ascii string specified by String as a hexadecimal number. The format of + the input Ascii string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If + "x" appears in the input string, it must be prefixed with at least one 0. The + function will ignore the pad space, which includes spaces or tab characters, + before [zeros], [x] or [hexadecimal digits]. The running zero before [x] or + [hexadecimal digits] will be ignored. Then, the decoding starts after [x] or + the first valid hexadecimal digit. Then, the function stops at the first + character that is a not a valid hexadecimal character or Null-terminator, + whichever on comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength Ascii characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid hexadecimal digits in the above format, then 0 is + stored at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINTN, then + MAX_UINTN is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + hexadecimal digits right after the optional pad spaces, the value of String + is stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Ascii string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumAsciiStringLength is not zero, + and String contains more than + PcdMaximumAsciiStringLength Ascii + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINTN. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrHexToUintnS ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT UINTN *Data + ) +{ + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == ' ') || (*String == '\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == '0') { + String++; + } + + if (InternalBaseLibAsciiToUpper (*String) == 'X') { + if (*(String - 1) != '0') { + *Data = 0; + return RETURN_SUCCESS; + } + // + // Skip the 'X' + // + String++; + } + + *Data = 0; + + while (InternalAsciiIsHexaDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINTN, then MAX_UINTN is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > ((MAX_UINTN - InternalAsciiHexCharToUintn (*String)) >> 4)) { + *Data = MAX_UINTN; + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = (*Data << 4) + InternalAsciiHexCharToUintn (*String); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Ascii hexadecimal string to a value of type UINT64. + + This function outputs a value of type UINT64 by interpreting the contents of + the Ascii string specified by String as a hexadecimal number. The format of + the input Ascii string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If + "x" appears in the input string, it must be prefixed with at least one 0. The + function will ignore the pad space, which includes spaces or tab characters, + before [zeros], [x] or [hexadecimal digits]. The running zero before [x] or + [hexadecimal digits] will be ignored. Then, the decoding starts after [x] or + the first valid hexadecimal digit. Then, the function stops at the first + character that is a not a valid hexadecimal character or Null-terminator, + whichever on comes first. + + If String is NULL, then ASSERT(). + If Data is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength Ascii characters, not including the + Null-terminator, then ASSERT(). + + If String has no valid hexadecimal digits in the above format, then 0 is + stored at the location pointed to by Data. + If the number represented by String exceeds the range defined by UINT64, then + MAX_UINT64 is stored at the location pointed to by Data. + + If EndPointer is not NULL, a pointer to the character that stopped the scan + is stored at the location pointed to by EndPointer. If String has no valid + hexadecimal digits right after the optional pad spaces, the value of String + is stored at the location pointed to by EndPointer. + + @param String Pointer to a Null-terminated Ascii string. + @param EndPointer Pointer to character that stops scan. + @param Data Pointer to the converted value. + + @retval RETURN_SUCCESS Value is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If PcdMaximumAsciiStringLength is not zero, + and String contains more than + PcdMaximumAsciiStringLength Ascii + characters, not including the + Null-terminator. + @retval RETURN_UNSUPPORTED If the number represented by String exceeds + the range defined by UINT64. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrHexToUint64S ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT UINT64 *Data + ) +{ + // + // 1. Neither String nor Data shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + + // + // Ignore the pad spaces (space or tab) + // + while ((*String == ' ') || (*String == '\t')) { + String++; + } + + // + // Ignore leading Zeros after the spaces + // + while (*String == '0') { + String++; + } + + if (InternalBaseLibAsciiToUpper (*String) == 'X') { + if (*(String - 1) != '0') { + *Data = 0; + return RETURN_SUCCESS; + } + // + // Skip the 'X' + // + String++; + } + + *Data = 0; + + while (InternalAsciiIsHexaDecimalDigitCharacter (*String)) { + // + // If the number represented by String overflows according to the range + // defined by UINT64, then MAX_UINT64 is stored in *Data and + // RETURN_UNSUPPORTED is returned. + // + if (*Data > RShiftU64 (MAX_UINT64 - InternalAsciiHexCharToUintn (*String), 4)) { + *Data = MAX_UINT64; + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_UNSUPPORTED; + } + + *Data = LShiftU64 (*Data, 4) + InternalAsciiHexCharToUintn (*String); + String++; + } + + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) String; + } + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated Unicode string to a Null-terminated + ASCII string. + + This function is similar to AsciiStrCpyS. + + This function converts the content of the Unicode string Source + to the ASCII string Destination by copying the lower 8 bits of + each Unicode character. The function terminates the ASCII string + Destination by appending a Null-terminator character at the end. + + The caller is responsible to make sure Destination points to a buffer with size + equal or greater than ((StrLen (Source) + 1) * sizeof (CHAR8)) in bytes. + + If any Unicode characters in Source contain non-zero value in + the upper 8 bits, then ASSERT(). + + If Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Source The pointer to a Null-terminated Unicode string. + @param Destination The pointer to a Null-terminated ASCII string. + @param DestMax The maximum number of Destination Ascii + char, including terminating null char. + + @retval RETURN_SUCCESS String is converted. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. + +**/ +RETURN_STATUS +EFIAPI +UnicodeStrToAsciiStrS ( + IN CONST CHAR16 *Source, + OUT CHAR8 *Destination, + IN UINTN DestMax + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than ASCII_RSIZE_MAX or RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. DestMax shall be greater than StrnLenS (Source, DestMax). + // + SourceLen = StrnLenS (Source, DestMax); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 5. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax, (VOID *)Source, (SourceLen + 1) * sizeof(CHAR16)), RETURN_ACCESS_DENIED); + + // + // convert string + // + while (*Source != '\0') { + // + // If any Unicode characters in Source contain + // non-zero value in the upper 8 bits, then ASSERT(). + // + ASSERT (*Source < 0x100); + *(Destination++) = (CHAR8) *(Source++); + } + *Destination = '\0'; + + return RETURN_SUCCESS; +} + +/** + Convert not more than Length successive characters from a Null-terminated + Unicode string to a Null-terminated Ascii string. If no null char is copied + from Source, then Destination[Length] is always set to null. + + This function converts not more than Length successive characters from the + Unicode string Source to the Ascii string Destination by copying the lower 8 + bits of each Unicode character. The function terminates the Ascii string + Destination by appending a Null-terminator character at the end. + + The caller is responsible to make sure Destination points to a buffer with + size not smaller than ((MIN(StrLen(Source), Length) + 1) * sizeof (CHAR8)) + in bytes. + + If any Unicode characters in Source contain non-zero value in the upper 8 + bits, then ASSERT(). + If Source is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then Destination and DestinationLength are + unmodified. + + @param Source The pointer to a Null-terminated Unicode string. + @param Length The maximum number of Unicode characters to + convert. + @param Destination The pointer to a Null-terminated Ascii string. + @param DestMax The maximum number of Destination Ascii char, + including terminating null char. + @param DestinationLength The number of Unicode characters converted. + + @retval RETURN_SUCCESS String is converted. + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If DestinationLength is NULL. + If PcdMaximumAsciiStringLength is not zero, + and Length or DestMax is greater than + PcdMaximumAsciiStringLength. + If PcdMaximumUnicodeStringLength is not + zero, and Length or DestMax is greater than + PcdMaximumUnicodeStringLength. + If DestMax is 0. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than + MIN(StrLen(Source), Length). + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. + +**/ +RETURN_STATUS +EFIAPI +UnicodeStrnToAsciiStrS ( + IN CONST CHAR16 *Source, + IN UINTN Length, + OUT CHAR8 *Destination, + IN UINTN DestMax, + OUT UINTN *DestinationLength + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Source & BIT0) == 0); + + // + // 1. None of Destination, Source or DestinationLength shall be a null + // pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestinationLength != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither Length nor DestMax shall be greater than ASCII_RSIZE_MAX or + // RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. If Length is not less than DestMax, then DestMax shall be greater than + // StrnLenS(Source, DestMax). + // + SourceLen = StrnLenS (Source, DestMax); + if (Length >= DestMax) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 5. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax, (VOID *)Source, (SourceLen + 1) * sizeof(CHAR16)), RETURN_ACCESS_DENIED); + + *DestinationLength = 0; + + // + // Convert string + // + while ((*Source != 0) && (SourceLen > 0)) { + // + // If any Unicode characters in Source contain non-zero value in the upper + // 8 bits, then ASSERT(). + // + ASSERT (*Source < 0x100); + *(Destination++) = (CHAR8) *(Source++); + SourceLen--; + (*DestinationLength)++; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Convert one Null-terminated ASCII string to a Null-terminated + Unicode string. + + This function is similar to StrCpyS. + + This function converts the contents of the ASCII string Source to the Unicode + string Destination. The function terminates the Unicode string Destination by + appending a Null-terminator character at the end. + + The caller is responsible to make sure Destination points to a buffer with size + equal or greater than ((AsciiStrLen (Source) + 1) * sizeof (CHAR16)) in bytes. + + If Destination is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then the Destination is unmodified. + + @param Source The pointer to a Null-terminated ASCII string. + @param Destination The pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode + char, including terminating null char. + + @retval RETURN_SUCCESS String is converted. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If PcdMaximumUnicodeStringLength is not zero, + and DestMax is greater than + PcdMaximumUnicodeStringLength. + If PcdMaximumAsciiStringLength is not zero, + and DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrToUnicodeStrS ( + IN CONST CHAR8 *Source, + OUT CHAR16 *Destination, + IN UINTN DestMax + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + + // + // 1. Neither Destination nor Source shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. DestMax shall not be greater than RSIZE_MAX or ASCII_RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. DestMax shall be greater than AsciiStrnLenS(Source, DestMax). + // + SourceLen = AsciiStrnLenS (Source, DestMax); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + + // + // 5. Copying shall not take place between objects that overlap. + // + SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax * sizeof(CHAR16), (VOID *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + // + // Convert string + // + while (*Source != '\0') { + *(Destination++) = (CHAR16)*(Source++); + } + *Destination = '\0'; + + return RETURN_SUCCESS; +} + +/** + Convert not more than Length successive characters from a Null-terminated + Ascii string to a Null-terminated Unicode string. If no null char is copied + from Source, then Destination[Length] is always set to null. + + This function converts not more than Length successive characters from the + Ascii string Source to the Unicode string Destination. The function + terminates the Unicode string Destination by appending a Null-terminator + character at the end. + + The caller is responsible to make sure Destination points to a buffer with + size not smaller than + ((MIN(AsciiStrLen(Source), Length) + 1) * sizeof (CHAR8)) in bytes. + + If Destination is not aligned on a 16-bit boundary, then ASSERT(). + If an error would be returned, then the function will also ASSERT(). + + If an error is returned, then Destination and DestinationLength are + unmodified. + + @param Source The pointer to a Null-terminated Ascii string. + @param Length The maximum number of Ascii characters to convert. + @param Destination The pointer to a Null-terminated Unicode string. + @param DestMax The maximum number of Destination Unicode char, + including terminating null char. + @param DestinationLength The number of Ascii characters converted. + + @retval RETURN_SUCCESS String is converted. + @retval RETURN_INVALID_PARAMETER If Destination is NULL. + If Source is NULL. + If DestinationLength is NULL. + If PcdMaximumUnicodeStringLength is not + zero, and Length or DestMax is greater than + PcdMaximumUnicodeStringLength. + If PcdMaximumAsciiStringLength is not zero, + and Length or DestMax is greater than + PcdMaximumAsciiStringLength. + If DestMax is 0. + @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than + MIN(AsciiStrLen(Source), Length). + @retval RETURN_ACCESS_DENIED If Source and Destination overlap. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrnToUnicodeStrS ( + IN CONST CHAR8 *Source, + IN UINTN Length, + OUT CHAR16 *Destination, + IN UINTN DestMax, + OUT UINTN *DestinationLength + ) +{ + UINTN SourceLen; + + ASSERT (((UINTN) Destination & BIT0) == 0); + + // + // 1. None of Destination, Source or DestinationLength shall be a null + // pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestinationLength != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Neither Length nor DestMax shall be greater than ASCII_RSIZE_MAX or + // RSIZE_MAX. + // + if (RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. DestMax shall not equal zero. + // + SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); + + // + // 4. If Length is not less than DestMax, then DestMax shall be greater than + // AsciiStrnLenS(Source, DestMax). + // + SourceLen = AsciiStrnLenS (Source, DestMax); + if (Length >= DestMax) { + SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); + } + + // + // 5. Copying shall not take place between objects that overlap. + // + if (SourceLen > Length) { + SourceLen = Length; + } + SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax * sizeof(CHAR16), (VOID *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); + + *DestinationLength = 0; + + // + // Convert string + // + while ((*Source != 0) && (SourceLen > 0)) { + *(Destination++) = (CHAR16)*(Source++); + SourceLen--; + (*DestinationLength)++; + } + *Destination = 0; + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated ASCII string to IPv6 address and prefix length. + + This function outputs a value of type IPv6_ADDRESS and may output a value + of type UINT8 by interpreting the contents of the ASCII string specified + by String. The format of the input ASCII string String is as follows: + + X:X:X:X:X:X:X:X[/P] + + X contains one to four hexadecimal digit characters in the range [0-9], [a-f] and + [A-F]. X is converted to a value of type UINT16, whose low byte is stored in low + memory address and high byte is stored in high memory address. P contains decimal + digit characters in the range [0-9]. The running zero in the beginning of P will + be ignored. /P is optional. + + When /P is not in the String, the function stops at the first character that is + not a valid hexadecimal digit character after eight X's are converted. + + When /P is in the String, the function stops at the first character that is not + a valid decimal digit character after P is converted. + + "::" can be used to compress one or more groups of X when X contains only 0. + The "::" can only appear once in the String. + + If String is NULL, then ASSERT(). + + If Address is NULL, then ASSERT(). + + If EndPointer is not NULL and Address is translated from String, a pointer + to the character that stopped the scan is stored at the location pointed to + by EndPointer. + + @param String Pointer to a Null-terminated ASCII string. + @param EndPointer Pointer to character that stops scan. + @param Address Pointer to the converted IPv6 address. + @param PrefixLength Pointer to the converted IPv6 address prefix + length. MAX_UINT8 is returned when /P is + not in the String. + + @retval RETURN_SUCCESS Address is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If X contains more than four hexadecimal + digit characters. + If String contains "::" and number of X + is not less than 8. + If P starts with character that is not a + valid decimal digit character. + If the decimal number converted from P + exceeds 128. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrToIpv6Address ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT IPv6_ADDRESS *Address, + OUT UINT8 *PrefixLength OPTIONAL + ) +{ + RETURN_STATUS Status; + UINTN AddressIndex; + UINTN Uintn; + IPv6_ADDRESS LocalAddress; + UINT8 LocalPrefixLength; + CONST CHAR8 *Pointer; + CHAR8 *End; + UINTN CompressStart; + BOOLEAN ExpectPrefix; + + LocalPrefixLength = MAX_UINT8; + CompressStart = ARRAY_SIZE (Address->Addr); + ExpectPrefix = FALSE; + + // + // None of String or Address shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); + + for (Pointer = String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { + if (!InternalAsciiIsHexaDecimalDigitCharacter (*Pointer)) { + if (*Pointer != ':') { + // + // ":" or "/" should be followed by digit characters. + // + return RETURN_UNSUPPORTED; + } + + // + // Meet second ":" after previous ":" or "/" + // or meet first ":" in the beginning of String. + // + if (ExpectPrefix) { + // + // ":" shall not be after "/" + // + return RETURN_UNSUPPORTED; + } + + if (CompressStart != ARRAY_SIZE (Address->Addr) || AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // "::" can only appear once. + // "::" can only appear when address is not full length. + // + return RETURN_UNSUPPORTED; + } else { + // + // Remember the start of zero compressing. + // + CompressStart = AddressIndex; + Pointer++; + + if (CompressStart == 0) { + if (*Pointer != ':') { + // + // Single ":" shall not be in the beginning of String. + // + return RETURN_UNSUPPORTED; + } + Pointer++; + } + } + } + + if (!InternalAsciiIsHexaDecimalDigitCharacter (*Pointer)) { + if (*Pointer == '/') { + // + // Might be optional "/P" after "::". + // + if (CompressStart != AddressIndex) { + return RETURN_UNSUPPORTED; + } + } else { + break; + } + } else { + if (!ExpectPrefix) { + // + // Get X. + // + Status = AsciiStrHexToUintnS (Pointer, &End, &Uintn); + if (RETURN_ERROR (Status) || End - Pointer > 4) { + // + // Number of hexadecimal digit characters is no more than 4. + // + return RETURN_UNSUPPORTED; + } + Pointer = End; + // + // Uintn won't exceed MAX_UINT16 if number of hexadecimal digit characters is no more than 4. + // + ASSERT (AddressIndex + 1 < ARRAY_SIZE (Address->Addr)); + LocalAddress.Addr[AddressIndex] = (UINT8) ((UINT16) Uintn >> 8); + LocalAddress.Addr[AddressIndex + 1] = (UINT8) Uintn; + AddressIndex += 2; + } else { + // + // Get P, then exit the loop. + // + Status = AsciiStrDecimalToUintnS (Pointer, &End, &Uintn); + if (RETURN_ERROR (Status) || End == Pointer || Uintn > 128) { + // + // Prefix length should not exceed 128. + // + return RETURN_UNSUPPORTED; + } + LocalPrefixLength = (UINT8) Uintn; + Pointer = End; + break; + } + } + + // + // Skip ':' or "/" + // + if (*Pointer == '/') { + ExpectPrefix = TRUE; + } else if (*Pointer == ':') { + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // Meet additional ":" after all 8 16-bit address + // + break; + } + } else { + // + // Meet other character that is not "/" or ":" after all 8 16-bit address + // + break; + } + Pointer++; + } + + if ((AddressIndex == ARRAY_SIZE (Address->Addr) && CompressStart != ARRAY_SIZE (Address->Addr)) || + (AddressIndex != ARRAY_SIZE (Address->Addr) && CompressStart == ARRAY_SIZE (Address->Addr)) + ) { + // + // Full length of address shall not have compressing zeros. + // Non-full length of address shall have compressing zeros. + // + return RETURN_UNSUPPORTED; + } + CopyMem (&Address->Addr[0], &LocalAddress.Addr[0], CompressStart); + ZeroMem (&Address->Addr[CompressStart], ARRAY_SIZE (Address->Addr) - AddressIndex); + if (AddressIndex > CompressStart) { + CopyMem ( + &Address->Addr[CompressStart + ARRAY_SIZE (Address->Addr) - AddressIndex], + &LocalAddress.Addr[CompressStart], + AddressIndex - CompressStart + ); + + } + + if (PrefixLength != NULL) { + *PrefixLength = LocalPrefixLength; + } + if (EndPointer != NULL) { + *EndPointer = (CHAR8 *) Pointer; + } + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated ASCII string to IPv4 address and prefix length. + + This function outputs a value of type IPv4_ADDRESS and may output a value + of type UINT8 by interpreting the contents of the ASCII string specified + by String. The format of the input ASCII string String is as follows: + + D.D.D.D[/P] + + D and P are decimal digit characters in the range [0-9]. The running zero in + the beginning of D and P will be ignored. /P is optional. + + When /P is not in the String, the function stops at the first character that is + not a valid decimal digit character after four D's are converted. + + When /P is in the String, the function stops at the first character that is not + a valid decimal digit character after P is converted. + + If String is NULL, then ASSERT(). + + If Address is NULL, then ASSERT(). + + If EndPointer is not NULL and Address is translated from String, a pointer + to the character that stopped the scan is stored at the location pointed to + by EndPointer. + + @param String Pointer to a Null-terminated ASCII string. + @param EndPointer Pointer to character that stops scan. + @param Address Pointer to the converted IPv4 address. + @param PrefixLength Pointer to the converted IPv4 address prefix + length. MAX_UINT8 is returned when /P is + not in the String. + + @retval RETURN_SUCCESS Address is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If String is not in the correct format. + If any decimal number converted from D + exceeds 255. + If the decimal number converted from P + exceeds 32. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrToIpv4Address ( + IN CONST CHAR8 *String, + OUT CHAR8 **EndPointer, OPTIONAL + OUT IPv4_ADDRESS *Address, + OUT UINT8 *PrefixLength OPTIONAL + ) +{ + RETURN_STATUS Status; + UINTN AddressIndex; + UINTN Uintn; + IPv4_ADDRESS LocalAddress; + UINT8 LocalPrefixLength; + CHAR8 *Pointer; + + LocalPrefixLength = MAX_UINT8; + + // + // None of String or Address shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); + + for (Pointer = (CHAR8 *) String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { + if (!InternalAsciiIsDecimalDigitCharacter (*Pointer)) { + // + // D or P contains invalid characters. + // + break; + } + + // + // Get D or P. + // + Status = AsciiStrDecimalToUintnS ((CONST CHAR8 *) Pointer, &Pointer, &Uintn); + if (RETURN_ERROR (Status)) { + return RETURN_UNSUPPORTED; + } + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + // + // It's P. + // + if (Uintn > 32) { + return RETURN_UNSUPPORTED; + } + LocalPrefixLength = (UINT8) Uintn; + } else { + // + // It's D. + // + if (Uintn > MAX_UINT8) { + return RETURN_UNSUPPORTED; + } + LocalAddress.Addr[AddressIndex] = (UINT8) Uintn; + AddressIndex++; + } + + // + // Check the '.' or '/', depending on the AddressIndex. + // + if (AddressIndex == ARRAY_SIZE (Address->Addr)) { + if (*Pointer == '/') { + // + // '/P' is in the String. + // Skip "/" and get P in next loop. + // + Pointer++; + } else { + // + // '/P' is not in the String. + // + break; + } + } else if (AddressIndex < ARRAY_SIZE (Address->Addr)) { + if (*Pointer == '.') { + // + // D should be followed by '.' + // + Pointer++; + } else { + return RETURN_UNSUPPORTED; + } + } + } + + if (AddressIndex < ARRAY_SIZE (Address->Addr)) { + return RETURN_UNSUPPORTED; + } + + CopyMem (Address, &LocalAddress, sizeof (*Address)); + if (PrefixLength != NULL) { + *PrefixLength = LocalPrefixLength; + } + if (EndPointer != NULL) { + *EndPointer = Pointer; + } + + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated ASCII GUID string to a value of type + EFI_GUID. + + This function outputs a GUID value by interpreting the contents of + the ASCII string specified by String. The format of the input + ASCII string String consists of 36 characters, as follows: + + aabbccdd-eeff-gghh-iijj-kkllmmnnoopp + + The pairs aa - pp are two characters in the range [0-9], [a-f] and + [A-F], with each pair representing a single byte hexadecimal value. + + The mapping between String and the EFI_GUID structure is as follows: + aa Data1[24:31] + bb Data1[16:23] + cc Data1[8:15] + dd Data1[0:7] + ee Data2[8:15] + ff Data2[0:7] + gg Data3[8:15] + hh Data3[0:7] + ii Data4[0:7] + jj Data4[8:15] + kk Data4[16:23] + ll Data4[24:31] + mm Data4[32:39] + nn Data4[40:47] + oo Data4[48:55] + pp Data4[56:63] + + If String is NULL, then ASSERT(). + If Guid is NULL, then ASSERT(). + + @param String Pointer to a Null-terminated ASCII string. + @param Guid Pointer to the converted GUID. + + @retval RETURN_SUCCESS Guid is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + @retval RETURN_UNSUPPORTED If String is not as the above format. + +**/ +RETURN_STATUS +EFIAPI +AsciiStrToGuid ( + IN CONST CHAR8 *String, + OUT GUID *Guid + ) +{ + RETURN_STATUS Status; + GUID LocalGuid; + + // + // None of String or Guid shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Guid != NULL), RETURN_INVALID_PARAMETER); + + // + // Get aabbccdd in big-endian. + // + Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data1), (UINT8 *) &LocalGuid.Data1, sizeof (LocalGuid.Data1)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data1)] != '-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data1 = SwapBytes32 (LocalGuid.Data1); + String += 2 * sizeof (LocalGuid.Data1) + 1; + + // + // Get eeff in big-endian. + // + Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data2), (UINT8 *) &LocalGuid.Data2, sizeof (LocalGuid.Data2)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data2)] != '-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data2 = SwapBytes16 (LocalGuid.Data2); + String += 2 * sizeof (LocalGuid.Data2) + 1; + + // + // Get gghh in big-endian. + // + Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data3), (UINT8 *) &LocalGuid.Data3, sizeof (LocalGuid.Data3)); + if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data3)] != '-') { + return RETURN_UNSUPPORTED; + } + // + // Convert big-endian to little-endian. + // + LocalGuid.Data3 = SwapBytes16 (LocalGuid.Data3); + String += 2 * sizeof (LocalGuid.Data3) + 1; + + // + // Get iijj. + // + Status = AsciiStrHexToBytes (String, 2 * 2, &LocalGuid.Data4[0], 2); + if (RETURN_ERROR (Status) || String[2 * 2] != '-') { + return RETURN_UNSUPPORTED; + } + String += 2 * 2 + 1; + + // + // Get kkllmmnnoopp. + // + Status = AsciiStrHexToBytes (String, 2 * 6, &LocalGuid.Data4[2], 6); + if (RETURN_ERROR (Status)) { + return RETURN_UNSUPPORTED; + } + + CopyGuid (Guid, &LocalGuid); + return RETURN_SUCCESS; +} + +/** + Convert a Null-terminated ASCII hexadecimal string to a byte array. + + This function outputs a byte array by interpreting the contents of + the ASCII string specified by String in hexadecimal format. The format of + the input ASCII string String is: + + [XX]* + + X is a hexadecimal digit character in the range [0-9], [a-f] and [A-F]. + The function decodes every two hexadecimal digit characters as one byte. The + decoding stops after Length of characters and outputs Buffer containing + (Length / 2) bytes. + + If String is NULL, then ASSERT(). + + If Buffer is NULL, then ASSERT(). + + If Length is not multiple of 2, then ASSERT(). + + If PcdMaximumAsciiStringLength is not zero and Length is greater than + PcdMaximumAsciiStringLength, then ASSERT(). + + If MaxBufferSize is less than (Length / 2), then ASSERT(). + + @param String Pointer to a Null-terminated ASCII string. + @param Length The number of ASCII characters to decode. + @param Buffer Pointer to the converted bytes array. + @param MaxBufferSize The maximum size of Buffer. + + @retval RETURN_SUCCESS Buffer is translated from String. + @retval RETURN_INVALID_PARAMETER If String is NULL. + If Data is NULL. + If Length is not multiple of 2. + If PcdMaximumAsciiStringLength is not zero, + and Length is greater than + PcdMaximumAsciiStringLength. + @retval RETURN_UNSUPPORTED If Length of characters from String contain + a character that is not valid hexadecimal + digit characters, or a Null-terminator. + @retval RETURN_BUFFER_TOO_SMALL If MaxBufferSize is less than (Length / 2). +**/ +RETURN_STATUS +EFIAPI +AsciiStrHexToBytes ( + IN CONST CHAR8 *String, + IN UINTN Length, + OUT UINT8 *Buffer, + IN UINTN MaxBufferSize + ) +{ + UINTN Index; + + // + // 1. None of String or Buffer shall be a null pointer. + // + SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); + SAFE_STRING_CONSTRAINT_CHECK ((Buffer != NULL), RETURN_INVALID_PARAMETER); + + // + // 2. Length shall not be greater than ASCII_RSIZE_MAX. + // + if (ASCII_RSIZE_MAX != 0) { + SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); + } + + // + // 3. Length shall not be odd. + // + SAFE_STRING_CONSTRAINT_CHECK (((Length & BIT0) == 0), RETURN_INVALID_PARAMETER); + + // + // 4. MaxBufferSize shall equal to or greater than Length / 2. + // + SAFE_STRING_CONSTRAINT_CHECK ((MaxBufferSize >= Length / 2), RETURN_BUFFER_TOO_SMALL); + + // + // 5. String shall not contains invalid hexadecimal digits. + // + for (Index = 0; Index < Length; Index++) { + if (!InternalAsciiIsHexaDecimalDigitCharacter (String[Index])) { + break; + } + } + if (Index != Length) { + return RETURN_UNSUPPORTED; + } + + // + // Convert the hex string to bytes. + // + for(Index = 0; Index < Length; Index++) { + + // + // For even characters, write the upper nibble for each buffer byte, + // and for even characters, the lower nibble. + // + if ((Index & BIT0) == 0) { + Buffer[Index / 2] = (UINT8) InternalAsciiHexCharToUintn (String[Index]) << 4; + } else { + Buffer[Index / 2] |= (UINT8) InternalAsciiHexCharToUintn (String[Index]); + } + } + return RETURN_SUCCESS; +} + diff --git a/MdePkg/HostLibrary/BaseLibHost/SetJump.c b/MdePkg/HostLibrary/BaseLibHost/SetJump.c new file mode 100644 index 00000000000..6d61e93adc5 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SetJump.c @@ -0,0 +1,54 @@ +/** @file + Internal ASSERT () functions for SetJump. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + +#include +#include +#include +#include +#include + +/** + Saves the current CPU context that can be restored with a call to LongJump() + and returns 0. + + Saves the current CPU context in the buffer specified by JumpBuffer and + returns 0. The initial call to SetJump() must always return 0. Subsequent + calls to LongJump() cause a non-zero value to be returned by SetJump(). + + If JumpBuffer is NULL, then ASSERT(). + For Itanium processors, if JumpBuffer is not aligned on a 16-byte boundary, then ASSERT(). + + NOTE: The structure BASE_LIBRARY_JUMP_BUFFER is CPU architecture specific. + The same structure must never be used for more than one CPU architecture context. + For example, a BASE_LIBRARY_JUMP_BUFFER allocated by an IA-32 module must never be used from an x64 module. + SetJump()/LongJump() is not currently supported for the EBC processor type. + + @param JumpBuffer A pointer to CPU context buffer. + + @retval 0 Indicates a return from SetJump(). + +**/ +UINTN +EFIAPI +SetJump ( + OUT BASE_LIBRARY_JUMP_BUFFER *JumpBuffer + ) +{ + jmp_buf local_buf; + jmp_buf *buf; + UINTN Value; + + buf = malloc (sizeof(jmp_buf)); + *(VOID **)JumpBuffer = buf; + Value = setjmp (local_buf); + if (Value == 0) { + memcpy (buf, &local_buf, sizeof(jmp_buf)); + } + return Value; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/String.c b/MdePkg/HostLibrary/BaseLibHost/String.c new file mode 100644 index 00000000000..4f5fa470b33 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/String.c @@ -0,0 +1,1163 @@ +/** @file + Unicode and ASCII string primitives. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Returns the length of a Null-terminated Unicode string. + + This function returns the number of Unicode characters in the Null-terminated + Unicode string specified by String. + + If String is NULL, then ASSERT(). + If String is not aligned on a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @return The length of String. + +**/ +UINTN +EFIAPI +StrLen ( + IN CONST CHAR16 *String + ) +{ + UINTN Length; + + ASSERT (String != NULL); + ASSERT (((UINTN) String & BIT0) == 0); + + for (Length = 0; *String != L'\0'; String++, Length++) { + // + // If PcdMaximumUnicodeStringLength is not zero, + // length should not more than PcdMaximumUnicodeStringLength + // + } + return Length; +} + +/** + Returns the size of a Null-terminated Unicode string in bytes, including the + Null terminator. + + This function returns the size, in bytes, of the Null-terminated Unicode string + specified by String. + + If String is NULL, then ASSERT(). + If String is not aligned on a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @return The size of String. + +**/ +UINTN +EFIAPI +StrSize ( + IN CONST CHAR16 *String + ) +{ + return (StrLen (String) + 1) * sizeof (*String); +} + +/** + Compares two Null-terminated Unicode strings, and returns the difference + between the first mismatched Unicode characters. + + This function compares the Null-terminated Unicode string FirstString to the + Null-terminated Unicode string SecondString. If FirstString is identical to + SecondString, then 0 is returned. Otherwise, the value returned is the first + mismatched Unicode character in SecondString subtracted from the first + mismatched Unicode character in FirstString. + + If FirstString is NULL, then ASSERT(). + If FirstString is not aligned on a 16-bit boundary, then ASSERT(). + If SecondString is NULL, then ASSERT(). + If SecondString is not aligned on a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and FirstString contains more + than PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and SecondString contains more + than PcdMaximumUnicodeStringLength Unicode characters, not including the + Null-terminator, then ASSERT(). + + @param FirstString A pointer to a Null-terminated Unicode string. + @param SecondString A pointer to a Null-terminated Unicode string. + + @retval 0 FirstString is identical to SecondString. + @return others FirstString is not identical to SecondString. + +**/ +INTN +EFIAPI +StrCmp ( + IN CONST CHAR16 *FirstString, + IN CONST CHAR16 *SecondString + ) +{ + // + // ASSERT both strings are less long than PcdMaximumUnicodeStringLength + // + ASSERT (StrSize (FirstString) != 0); + ASSERT (StrSize (SecondString) != 0); + + while ((*FirstString != L'\0') && (*FirstString == *SecondString)) { + FirstString++; + SecondString++; + } + return *FirstString - *SecondString; +} + +/** + Compares up to a specified length the contents of two Null-terminated Unicode strings, + and returns the difference between the first mismatched Unicode characters. + + This function compares the Null-terminated Unicode string FirstString to the + Null-terminated Unicode string SecondString. At most, Length Unicode + characters will be compared. If Length is 0, then 0 is returned. If + FirstString is identical to SecondString, then 0 is returned. Otherwise, the + value returned is the first mismatched Unicode character in SecondString + subtracted from the first mismatched Unicode character in FirstString. + + If Length > 0 and FirstString is NULL, then ASSERT(). + If Length > 0 and FirstString is not aligned on a 16-bit boundary, then ASSERT(). + If Length > 0 and SecondString is NULL, then ASSERT(). + If Length > 0 and SecondString is not aligned on a 16-bit boundary, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and Length is greater than + PcdMaximumUnicodeStringLength, then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and FirstString contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, + then ASSERT(). + If PcdMaximumUnicodeStringLength is not zero, and SecondString contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, + then ASSERT(). + + @param FirstString A pointer to a Null-terminated Unicode string. + @param SecondString A pointer to a Null-terminated Unicode string. + @param Length The maximum number of Unicode characters to compare. + + @retval 0 FirstString is identical to SecondString. + @return others FirstString is not identical to SecondString. + +**/ +INTN +EFIAPI +StrnCmp ( + IN CONST CHAR16 *FirstString, + IN CONST CHAR16 *SecondString, + IN UINTN Length + ) +{ + if (Length == 0) { + return 0; + } + + // + // ASSERT both strings are less long than PcdMaximumUnicodeStringLength. + // Length tests are performed inside StrLen(). + // + ASSERT (StrSize (FirstString) != 0); + ASSERT (StrSize (SecondString) != 0); + + while ((*FirstString != L'\0') && + (*SecondString != L'\0') && + (*FirstString == *SecondString) && + (Length > 1)) { + FirstString++; + SecondString++; + Length--; + } + + return *FirstString - *SecondString; +} + +/** + Returns the first occurrence of a Null-terminated Unicode sub-string + in a Null-terminated Unicode string. + + This function scans the contents of the Null-terminated Unicode string + specified by String and returns the first occurrence of SearchString. + If SearchString is not found in String, then NULL is returned. If + the length of SearchString is zero, then String is + returned. + + If String is NULL, then ASSERT(). + If String is not aligned on a 16-bit boundary, then ASSERT(). + If SearchString is NULL, then ASSERT(). + If SearchString is not aligned on a 16-bit boundary, then ASSERT(). + + If PcdMaximumUnicodeStringLength is not zero, and SearchString + or String contains more than PcdMaximumUnicodeStringLength Unicode + characters, not including the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + @param SearchString A pointer to a Null-terminated Unicode string to search for. + + @retval NULL If the SearchString does not appear in String. + @return others If there is a match. + +**/ +CHAR16 * +EFIAPI +StrStr ( + IN CONST CHAR16 *String, + IN CONST CHAR16 *SearchString + ) +{ + CONST CHAR16 *FirstMatch; + CONST CHAR16 *SearchStringTmp; + + // + // ASSERT both strings are less long than PcdMaximumUnicodeStringLength. + // Length tests are performed inside StrLen(). + // + ASSERT (StrSize (String) != 0); + ASSERT (StrSize (SearchString) != 0); + + if (*SearchString == L'\0') { + return (CHAR16 *) String; + } + + while (*String != L'\0') { + SearchStringTmp = SearchString; + FirstMatch = String; + + while ((*String == *SearchStringTmp) + && (*String != L'\0')) { + String++; + SearchStringTmp++; + } + + if (*SearchStringTmp == L'\0') { + return (CHAR16 *) FirstMatch; + } + + if (*String == L'\0') { + return NULL; + } + + String = FirstMatch + 1; + } + + return NULL; +} + +/** + Check if a Unicode character is a decimal character. + + This internal function checks if a Unicode character is a + decimal character. The valid decimal character is from + L'0' to L'9'. + + @param Char The character to check against. + + @retval TRUE If the Char is a decmial character. + @retval FALSE If the Char is not a decmial character. + +**/ +BOOLEAN +EFIAPI +InternalIsDecimalDigitCharacter ( + IN CHAR16 Char + ) +{ + return (BOOLEAN) (Char >= L'0' && Char <= L'9'); +} + +/** + Convert a Unicode character to upper case only if + it maps to a valid small-case ASCII character. + + This internal function only deal with Unicode character + which maps to a valid small-case ASCII character, i.e. + L'a' to L'z'. For other Unicode character, the input character + is returned directly. + + @param Char The character to convert. + + @retval LowerCharacter If the Char is with range L'a' to L'z'. + @retval Unchanged Otherwise. + +**/ +CHAR16 +EFIAPI +InternalCharToUpper ( + IN CHAR16 Char + ) +{ + if (Char >= L'a' && Char <= L'z') { + return (CHAR16) (Char - (L'a' - L'A')); + } + + return Char; +} + +/** + Convert a Unicode character to numerical value. + + This internal function only deal with Unicode character + which maps to a valid hexadecimal ASII character, i.e. + L'0' to L'9', L'a' to L'f' or L'A' to L'F'. For other + Unicode character, the value returned does not make sense. + + @param Char The character to convert. + + @return The numerical value converted. + +**/ +UINTN +EFIAPI +InternalHexCharToUintn ( + IN CHAR16 Char + ) +{ + if (InternalIsDecimalDigitCharacter (Char)) { + return Char - L'0'; + } + + return (10 + InternalCharToUpper (Char) - L'A'); +} + +/** + Check if a Unicode character is a hexadecimal character. + + This internal function checks if a Unicode character is a + decimal character. The valid hexadecimal character is + L'0' to L'9', L'a' to L'f', or L'A' to L'F'. + + + @param Char The character to check against. + + @retval TRUE If the Char is a hexadecmial character. + @retval FALSE If the Char is not a hexadecmial character. + +**/ +BOOLEAN +EFIAPI +InternalIsHexaDecimalDigitCharacter ( + IN CHAR16 Char + ) +{ + + return (BOOLEAN) (InternalIsDecimalDigitCharacter (Char) || + (Char >= L'A' && Char <= L'F') || + (Char >= L'a' && Char <= L'f')); +} + +/** + Convert a Null-terminated Unicode decimal string to a value of + type UINTN. + + This function returns a value of type UINTN by interpreting the contents + of the Unicode string specified by String as a decimal number. The format + of the input Unicode string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The + function will ignore the pad space, which includes spaces or + tab characters, before [decimal digits]. The running zero in the + beginning of [decimal digits] will be ignored. Then, the function + stops at the first character that is a not a valid decimal character + or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If String has only pad spaces, then 0 is returned. + If String has no pad spaces or valid decimal digits, + then 0 is returned. + If the number represented by String overflows according + to the range defined by UINTN, then MAX_UINTN is returned. + + If PcdMaximumUnicodeStringLength is not zero, and String contains + more than PcdMaximumUnicodeStringLength Unicode characters, not including + the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @retval Value translated from String. + +**/ +UINTN +EFIAPI +StrDecimalToUintn ( + IN CONST CHAR16 *String + ) +{ + UINTN Result; + + StrDecimalToUintnS (String, (CHAR16 **) NULL, &Result); + return Result; +} + + +/** + Convert a Null-terminated Unicode decimal string to a value of + type UINT64. + + This function returns a value of type UINT64 by interpreting the contents + of the Unicode string specified by String as a decimal number. The format + of the input Unicode string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The + function will ignore the pad space, which includes spaces or + tab characters, before [decimal digits]. The running zero in the + beginning of [decimal digits] will be ignored. Then, the function + stops at the first character that is a not a valid decimal character + or a Null-terminator, whichever one comes first. + + If String is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If String has only pad spaces, then 0 is returned. + If String has no pad spaces or valid decimal digits, + then 0 is returned. + If the number represented by String overflows according + to the range defined by UINT64, then MAX_UINT64 is returned. + + If PcdMaximumUnicodeStringLength is not zero, and String contains + more than PcdMaximumUnicodeStringLength Unicode characters, not including + the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @retval Value translated from String. + +**/ +UINT64 +EFIAPI +StrDecimalToUint64 ( + IN CONST CHAR16 *String + ) +{ + UINT64 Result; + + StrDecimalToUint64S (String, (CHAR16 **) NULL, &Result); + return Result; +} + +/** + Convert a Null-terminated Unicode hexadecimal string to a value of type UINTN. + + This function returns a value of type UINTN by interpreting the contents + of the Unicode string specified by String as a hexadecimal number. + The format of the input Unicode string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. + If "x" appears in the input string, it must be prefixed with at least one 0. + The function will ignore the pad space, which includes spaces or tab characters, + before [zeros], [x] or [hexadecimal digit]. The running zero before [x] or + [hexadecimal digit] will be ignored. Then, the decoding starts after [x] or the + first valid hexadecimal digit. Then, the function stops at the first character that is + a not a valid hexadecimal character or NULL, whichever one comes first. + + If String is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If String has only pad spaces, then zero is returned. + If String has no leading pad spaces, leading zeros or valid hexadecimal digits, + then zero is returned. + If the number represented by String overflows according to the range defined by + UINTN, then MAX_UINTN is returned. + + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @retval Value translated from String. + +**/ +UINTN +EFIAPI +StrHexToUintn ( + IN CONST CHAR16 *String + ) +{ + UINTN Result; + + StrHexToUintnS (String, (CHAR16 **) NULL, &Result); + return Result; +} + + +/** + Convert a Null-terminated Unicode hexadecimal string to a value of type UINT64. + + This function returns a value of type UINT64 by interpreting the contents + of the Unicode string specified by String as a hexadecimal number. + The format of the input Unicode string String is + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. + If "x" appears in the input string, it must be prefixed with at least one 0. + The function will ignore the pad space, which includes spaces or tab characters, + before [zeros], [x] or [hexadecimal digit]. The running zero before [x] or + [hexadecimal digit] will be ignored. Then, the decoding starts after [x] or the + first valid hexadecimal digit. Then, the function stops at the first character that is + a not a valid hexadecimal character or NULL, whichever one comes first. + + If String is NULL, then ASSERT(). + If String is not aligned in a 16-bit boundary, then ASSERT(). + If String has only pad spaces, then zero is returned. + If String has no leading pad spaces, leading zeros or valid hexadecimal digits, + then zero is returned. + If the number represented by String overflows according to the range defined by + UINT64, then MAX_UINT64 is returned. + + If PcdMaximumUnicodeStringLength is not zero, and String contains more than + PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated Unicode string. + + @retval Value translated from String. + +**/ +UINT64 +EFIAPI +StrHexToUint64 ( + IN CONST CHAR16 *String + ) +{ + UINT64 Result; + + StrHexToUint64S (String, (CHAR16 **) NULL, &Result); + return Result; +} + +/** + Check if a ASCII character is a decimal character. + + This internal function checks if a Unicode character is a + decimal character. The valid decimal character is from + '0' to '9'. + + @param Char The character to check against. + + @retval TRUE If the Char is a decmial character. + @retval FALSE If the Char is not a decmial character. + +**/ +BOOLEAN +EFIAPI +InternalAsciiIsDecimalDigitCharacter ( + IN CHAR8 Char + ) +{ + return (BOOLEAN) (Char >= '0' && Char <= '9'); +} + +/** + Check if a ASCII character is a hexadecimal character. + + This internal function checks if a ASCII character is a + decimal character. The valid hexadecimal character is + L'0' to L'9', L'a' to L'f', or L'A' to L'F'. + + + @param Char The character to check against. + + @retval TRUE If the Char is a hexadecmial character. + @retval FALSE If the Char is not a hexadecmial character. + +**/ +BOOLEAN +EFIAPI +InternalAsciiIsHexaDecimalDigitCharacter ( + IN CHAR8 Char + ) +{ + + return (BOOLEAN) (InternalAsciiIsDecimalDigitCharacter (Char) || + (Char >= 'A' && Char <= 'F') || + (Char >= 'a' && Char <= 'f')); +} + +/** + Returns the length of a Null-terminated ASCII string. + + This function returns the number of ASCII characters in the Null-terminated + ASCII string specified by String. + + If Length > 0 and Destination is NULL, then ASSERT(). + If Length > 0 and Source is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and String contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @return The length of String. + +**/ +UINTN +EFIAPI +AsciiStrLen ( + IN CONST CHAR8 *String + ) +{ + UINTN Length; + + ASSERT (String != NULL); + + for (Length = 0; *String != '\0'; String++, Length++) { + // + // If PcdMaximumUnicodeStringLength is not zero, + // length should not more than PcdMaximumUnicodeStringLength + // + } + return Length; +} + +/** + Returns the size of a Null-terminated ASCII string in bytes, including the + Null terminator. + + This function returns the size, in bytes, of the Null-terminated ASCII string + specified by String. + + If String is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and String contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @return The size of String. + +**/ +UINTN +EFIAPI +AsciiStrSize ( + IN CONST CHAR8 *String + ) +{ + return (AsciiStrLen (String) + 1) * sizeof (*String); +} + +/** + Compares two Null-terminated ASCII strings, and returns the difference + between the first mismatched ASCII characters. + + This function compares the Null-terminated ASCII string FirstString to the + Null-terminated ASCII string SecondString. If FirstString is identical to + SecondString, then 0 is returned. Otherwise, the value returned is the first + mismatched ASCII character in SecondString subtracted from the first + mismatched ASCII character in FirstString. + + If FirstString is NULL, then ASSERT(). + If SecondString is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and FirstString contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and SecondString contains more + than PcdMaximumAsciiStringLength ASCII characters, not including the + Null-terminator, then ASSERT(). + + @param FirstString A pointer to a Null-terminated ASCII string. + @param SecondString A pointer to a Null-terminated ASCII string. + + @retval ==0 FirstString is identical to SecondString. + @retval !=0 FirstString is not identical to SecondString. + +**/ +INTN +EFIAPI +AsciiStrCmp ( + IN CONST CHAR8 *FirstString, + IN CONST CHAR8 *SecondString + ) +{ + // + // ASSERT both strings are less long than PcdMaximumAsciiStringLength + // + ASSERT (AsciiStrSize (FirstString)); + ASSERT (AsciiStrSize (SecondString)); + + while ((*FirstString != '\0') && (*FirstString == *SecondString)) { + FirstString++; + SecondString++; + } + + return *FirstString - *SecondString; +} + +/** + Converts a lowercase Ascii character to upper one. + + If Chr is lowercase Ascii character, then converts it to upper one. + + If Value >= 0xA0, then ASSERT(). + If (Value & 0x0F) >= 0x0A, then ASSERT(). + + @param Chr one Ascii character + + @return The uppercase value of Ascii character + +**/ +CHAR8 +EFIAPI +InternalBaseLibAsciiToUpper ( + IN CHAR8 Chr + ) +{ + return (UINT8) ((Chr >= 'a' && Chr <= 'z') ? Chr - ('a' - 'A') : Chr); +} + +/** + Convert a ASCII character to numerical value. + + This internal function only deal with Unicode character + which maps to a valid hexadecimal ASII character, i.e. + '0' to '9', 'a' to 'f' or 'A' to 'F'. For other + ASCII character, the value returned does not make sense. + + @param Char The character to convert. + + @return The numerical value converted. + +**/ +UINTN +EFIAPI +InternalAsciiHexCharToUintn ( + IN CHAR8 Char + ) +{ + if (InternalIsDecimalDigitCharacter (Char)) { + return Char - '0'; + } + + return (10 + InternalBaseLibAsciiToUpper (Char) - 'A'); +} + + +/** + Performs a case insensitive comparison of two Null-terminated ASCII strings, + and returns the difference between the first mismatched ASCII characters. + + This function performs a case insensitive comparison of the Null-terminated + ASCII string FirstString to the Null-terminated ASCII string SecondString. If + FirstString is identical to SecondString, then 0 is returned. Otherwise, the + value returned is the first mismatched lower case ASCII character in + SecondString subtracted from the first mismatched lower case ASCII character + in FirstString. + + If FirstString is NULL, then ASSERT(). + If SecondString is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and FirstString contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + If PcdMaximumAsciiStringLength is not zero and SecondString contains more + than PcdMaximumAsciiStringLength ASCII characters, not including the + Null-terminator, then ASSERT(). + + @param FirstString A pointer to a Null-terminated ASCII string. + @param SecondString A pointer to a Null-terminated ASCII string. + + @retval ==0 FirstString is identical to SecondString using case insensitive + comparisons. + @retval !=0 FirstString is not identical to SecondString using case + insensitive comparisons. + +**/ +INTN +EFIAPI +AsciiStriCmp ( + IN CONST CHAR8 *FirstString, + IN CONST CHAR8 *SecondString + ) +{ + CHAR8 UpperFirstString; + CHAR8 UpperSecondString; + + // + // ASSERT both strings are less long than PcdMaximumAsciiStringLength + // + ASSERT (AsciiStrSize (FirstString)); + ASSERT (AsciiStrSize (SecondString)); + + UpperFirstString = InternalBaseLibAsciiToUpper (*FirstString); + UpperSecondString = InternalBaseLibAsciiToUpper (*SecondString); + while ((*FirstString != '\0') && (*SecondString != '\0') && (UpperFirstString == UpperSecondString)) { + FirstString++; + SecondString++; + UpperFirstString = InternalBaseLibAsciiToUpper (*FirstString); + UpperSecondString = InternalBaseLibAsciiToUpper (*SecondString); + } + + return UpperFirstString - UpperSecondString; +} + +/** + Compares two Null-terminated ASCII strings with maximum lengths, and returns + the difference between the first mismatched ASCII characters. + + This function compares the Null-terminated ASCII string FirstString to the + Null-terminated ASCII string SecondString. At most, Length ASCII characters + will be compared. If Length is 0, then 0 is returned. If FirstString is + identical to SecondString, then 0 is returned. Otherwise, the value returned + is the first mismatched ASCII character in SecondString subtracted from the + first mismatched ASCII character in FirstString. + + If Length > 0 and FirstString is NULL, then ASSERT(). + If Length > 0 and SecondString is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and Length is greater than + PcdMaximumAsciiStringLength, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and FirstString contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and SecondString contains more than + PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, + then ASSERT(). + + @param FirstString A pointer to a Null-terminated ASCII string. + @param SecondString A pointer to a Null-terminated ASCII string. + @param Length The maximum number of ASCII characters for compare. + + @retval ==0 FirstString is identical to SecondString. + @retval !=0 FirstString is not identical to SecondString. + +**/ +INTN +EFIAPI +AsciiStrnCmp ( + IN CONST CHAR8 *FirstString, + IN CONST CHAR8 *SecondString, + IN UINTN Length + ) +{ + if (Length == 0) { + return 0; + } + + // + // ASSERT both strings are less long than PcdMaximumAsciiStringLength + // + ASSERT (AsciiStrSize (FirstString)); + ASSERT (AsciiStrSize (SecondString)); + + while ((*FirstString != '\0') && + (*SecondString != '\0') && + (*FirstString == *SecondString) && + (Length > 1)) { + FirstString++; + SecondString++; + Length--; + } + return *FirstString - *SecondString; +} + +/** + Returns the first occurrence of a Null-terminated ASCII sub-string + in a Null-terminated ASCII string. + + This function scans the contents of the ASCII string specified by String + and returns the first occurrence of SearchString. If SearchString is not + found in String, then NULL is returned. If the length of SearchString is zero, + then String is returned. + + If String is NULL, then ASSERT(). + If SearchString is NULL, then ASSERT(). + + If PcdMaximumAsciiStringLength is not zero, and SearchString or + String contains more than PcdMaximumAsciiStringLength Unicode characters + not including the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + @param SearchString A pointer to a Null-terminated ASCII string to search for. + + @retval NULL If the SearchString does not appear in String. + @retval others If there is a match return the first occurrence of SearchingString. + If the length of SearchString is zero,return String. + +**/ +CHAR8 * +EFIAPI +AsciiStrStr ( + IN CONST CHAR8 *String, + IN CONST CHAR8 *SearchString + ) +{ + CONST CHAR8 *FirstMatch; + CONST CHAR8 *SearchStringTmp; + + // + // ASSERT both strings are less long than PcdMaximumAsciiStringLength + // + ASSERT (AsciiStrSize (String) != 0); + ASSERT (AsciiStrSize (SearchString) != 0); + + if (*SearchString == '\0') { + return (CHAR8 *) String; + } + + while (*String != '\0') { + SearchStringTmp = SearchString; + FirstMatch = String; + + while ((*String == *SearchStringTmp) + && (*String != '\0')) { + String++; + SearchStringTmp++; + } + + if (*SearchStringTmp == '\0') { + return (CHAR8 *) FirstMatch; + } + + if (*String == '\0') { + return NULL; + } + + String = FirstMatch + 1; + } + + return NULL; +} + +/** + Convert a Null-terminated ASCII decimal string to a value of type + UINTN. + + This function returns a value of type UINTN by interpreting the contents + of the ASCII string String as a decimal number. The format of the input + ASCII string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before the digits. + The running zero in the beginning of [decimal digits] will be ignored. Then, the + function stops at the first character that is a not a valid decimal character or + Null-terminator, whichever on comes first. + + If String has only pad spaces, then 0 is returned. + If String has no pad spaces or valid decimal digits, then 0 is returned. + If the number represented by String overflows according to the range defined by + UINTN, then MAX_UINTN is returned. + If String is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength ASCII characters not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @retval Value translated from String. + +**/ +UINTN +EFIAPI +AsciiStrDecimalToUintn ( + IN CONST CHAR8 *String + ) +{ + UINTN Result; + + AsciiStrDecimalToUintnS (String, (CHAR8 **) NULL, &Result); + return Result; +} + + +/** + Convert a Null-terminated ASCII decimal string to a value of type + UINT64. + + This function returns a value of type UINT64 by interpreting the contents + of the ASCII string String as a decimal number. The format of the input + ASCII string String is: + + [spaces] [decimal digits]. + + The valid decimal digit character is in the range [0-9]. The function will + ignore the pad space, which includes spaces or tab characters, before the digits. + The running zero in the beginning of [decimal digits] will be ignored. Then, the + function stops at the first character that is a not a valid decimal character or + Null-terminator, whichever on comes first. + + If String has only pad spaces, then 0 is returned. + If String has no pad spaces or valid decimal digits, then 0 is returned. + If the number represented by String overflows according to the range defined by + UINT64, then MAX_UINT64 is returned. + If String is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, and String contains more than + PcdMaximumAsciiStringLength ASCII characters not including the Null-terminator, + then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @retval Value translated from String. + +**/ +UINT64 +EFIAPI +AsciiStrDecimalToUint64 ( + IN CONST CHAR8 *String + ) +{ + UINT64 Result; + + AsciiStrDecimalToUint64S (String, (CHAR8 **) NULL, &Result); + return Result; +} + +/** + Convert a Null-terminated ASCII hexadecimal string to a value of type UINTN. + + This function returns a value of type UINTN by interpreting the contents of + the ASCII string String as a hexadecimal number. The format of the input ASCII + string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If "x" + appears in the input string, it must be prefixed with at least one 0. The function + will ignore the pad space, which includes spaces or tab characters, before [zeros], + [x] or [hexadecimal digits]. The running zero before [x] or [hexadecimal digits] + will be ignored. Then, the decoding starts after [x] or the first valid hexadecimal + digit. Then, the function stops at the first character that is a not a valid + hexadecimal character or Null-terminator, whichever on comes first. + + If String has only pad spaces, then 0 is returned. + If String has no leading pad spaces, leading zeros or valid hexadecimal digits, then + 0 is returned. + + If the number represented by String overflows according to the range defined by UINTN, + then MAX_UINTN is returned. + If String is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, + and String contains more than PcdMaximumAsciiStringLength ASCII characters not including + the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @retval Value translated from String. + +**/ +UINTN +EFIAPI +AsciiStrHexToUintn ( + IN CONST CHAR8 *String + ) +{ + UINTN Result; + + AsciiStrHexToUintnS (String, (CHAR8 **) NULL, &Result); + return Result; +} + + +/** + Convert a Null-terminated ASCII hexadecimal string to a value of type UINT64. + + This function returns a value of type UINT64 by interpreting the contents of + the ASCII string String as a hexadecimal number. The format of the input ASCII + string String is: + + [spaces][zeros][x][hexadecimal digits]. + + The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. + The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If "x" + appears in the input string, it must be prefixed with at least one 0. The function + will ignore the pad space, which includes spaces or tab characters, before [zeros], + [x] or [hexadecimal digits]. The running zero before [x] or [hexadecimal digits] + will be ignored. Then, the decoding starts after [x] or the first valid hexadecimal + digit. Then, the function stops at the first character that is a not a valid + hexadecimal character or Null-terminator, whichever on comes first. + + If String has only pad spaces, then 0 is returned. + If String has no leading pad spaces, leading zeros or valid hexadecimal digits, then + 0 is returned. + + If the number represented by String overflows according to the range defined by UINT64, + then MAX_UINT64 is returned. + If String is NULL, then ASSERT(). + If PcdMaximumAsciiStringLength is not zero, + and String contains more than PcdMaximumAsciiStringLength ASCII characters not including + the Null-terminator, then ASSERT(). + + @param String A pointer to a Null-terminated ASCII string. + + @retval Value translated from String. + +**/ +UINT64 +EFIAPI +AsciiStrHexToUint64 ( + IN CONST CHAR8 *String + ) +{ + UINT64 Result; + + AsciiStrHexToUint64S (String, (CHAR8 **) NULL, &Result); + return Result; +} + +/** + Converts an 8-bit value to an 8-bit BCD value. + + Converts the 8-bit value specified by Value to BCD. The BCD value is + returned. + + If Value >= 100, then ASSERT(). + + @param Value The 8-bit value to convert to BCD. Range 0..99. + + @return The BCD value. + +**/ +UINT8 +EFIAPI +DecimalToBcd8 ( + IN UINT8 Value + ) +{ + ASSERT (Value < 100); + return (UINT8) (((Value / 10) << 4) | (Value % 10)); +} + +/** + Converts an 8-bit BCD value to an 8-bit value. + + Converts the 8-bit BCD value specified by Value to an 8-bit value. The 8-bit + value is returned. + + If Value >= 0xA0, then ASSERT(). + If (Value & 0x0F) >= 0x0A, then ASSERT(). + + @param Value The 8-bit BCD value to convert to an 8-bit value. + + @return The 8-bit value is returned. + +**/ +UINT8 +EFIAPI +BcdToDecimal8 ( + IN UINT8 Value + ) +{ + ASSERT (Value < 0xa0); + ASSERT ((Value & 0xf) < 0xa); + return (UINT8) ((Value >> 4) * 10 + (Value & 0xf)); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c b/MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c new file mode 100644 index 00000000000..c04444750f3 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c @@ -0,0 +1,31 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Switches the endianess of a 16-bit integer. + + This function swaps the bytes in a 16-bit unsigned value to switch the value + from little endian to big endian or vice versa. The byte swapped value is + returned. + + @param Value A 16-bit unsigned value. + + @return The byte swapped Value. + +**/ +UINT16 +EFIAPI +SwapBytes16 ( + IN UINT16 Value + ) +{ + return (UINT16) ((Value<< 8) | (Value>> 8)); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c b/MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c new file mode 100644 index 00000000000..5e2d0edffd0 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c @@ -0,0 +1,37 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Switches the endianess of a 32-bit integer. + + This function swaps the bytes in a 32-bit unsigned value to switch the value + from little endian to big endian or vice versa. The byte swapped value is + returned. + + @param Value A 32-bit unsigned value. + + @return The byte swapped Value. + +**/ +UINT32 +EFIAPI +SwapBytes32 ( + IN UINT32 Value + ) +{ + UINT32 LowerBytes; + UINT32 HigherBytes; + + LowerBytes = (UINT32) SwapBytes16 ((UINT16) Value); + HigherBytes = (UINT32) SwapBytes16 ((UINT16) (Value >> 16)); + + return (LowerBytes << 16 | HigherBytes); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c b/MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c new file mode 100644 index 00000000000..f56580168ea --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c @@ -0,0 +1,37 @@ +/** @file + Math worker functions. + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +UINT64 +EFIAPI +InternalMathSwapBytes64 ( + IN UINT64 Operand + ); + +/** + Switches the endianess of a 64-bit integer. + + This function swaps the bytes in a 64-bit unsigned value to switch the value + from little endian to big endian or vice versa. The byte swapped value is + returned. + + @param Value A 64-bit unsigned value. + + @return The byte swapped Value. + +**/ +UINT64 +EFIAPI +SwapBytes64 ( + IN UINT64 Value + ) +{ + return InternalMathSwapBytes64 (Value); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c b/MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c new file mode 100644 index 00000000000..b011c147125 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c @@ -0,0 +1,52 @@ +/** @file + Switch Stack functions. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Transfers control to a function starting with a new stack. + + Transfers control to the function specified by EntryPoint using the + new stack specified by NewStack and passing in the parameters specified + by Context1 and Context2. Context1 and Context2 are optional and may + be NULL. The function EntryPoint must never return. This function + supports a variable number of arguments following the NewStack parameter. + These additional arguments are ignored on IA-32, x64, and EBC. + IPF CPUs expect one additional parameter of type VOID * that specifies + the new backing store pointer. + + If EntryPoint is NULL, then ASSERT(). + If NewStack is NULL, then ASSERT(). + + @param EntryPoint A pointer to function to call with the new stack. + @param Context1 A pointer to the context to pass into the EntryPoint + function. + @param Context2 A pointer to the context to pass into the EntryPoint + function. + @param NewStack A pointer to the new stack to use for the EntryPoint + function. + @param ... This variable argument list is ignored for IA32, x64, and EBC. + For IPF, this variable argument list is expected to contain + a single parameter of type VOID * that specifies the new backing + store pointer. + + +**/ +VOID +EFIAPI +SwitchStack ( + IN SWITCH_STACK_ENTRY_POINT EntryPoint, + IN VOID *Context1, OPTIONAL + IN VOID *Context2, OPTIONAL + IN VOID *NewStack, + ... + ) +{ + ASSERT (FALSE); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/Unaligned.c b/MdePkg/HostLibrary/BaseLibHost/Unaligned.c new file mode 100644 index 00000000000..fda732b6626 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/Unaligned.c @@ -0,0 +1,216 @@ +/** @file + Unaligned access functions of BaseLib. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Reads a 16-bit value from memory that may be unaligned. + + This function returns the 16-bit value pointed to by Buffer. The function + guarantees that the read operation does not produce an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 16-bit value that may be unaligned. + + @return The 16-bit value read from Buffer. + +**/ +UINT16 +EFIAPI +ReadUnaligned16 ( + IN CONST UINT16 *Buffer + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer; +} + +/** + Writes a 16-bit value to memory that may be unaligned. + + This function writes the 16-bit value specified by Value to Buffer. Value is + returned. The function guarantees that the write operation does not produce + an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 16-bit value that may be unaligned. + @param Value 16-bit value to write to Buffer. + + @return The 16-bit value to write to Buffer. + +**/ +UINT16 +EFIAPI +WriteUnaligned16 ( + OUT UINT16 *Buffer, + IN UINT16 Value + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer = Value; +} + +/** + Reads a 24-bit value from memory that may be unaligned. + + This function returns the 24-bit value pointed to by Buffer. The function + guarantees that the read operation does not produce an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 24-bit value that may be unaligned. + + @return The 24-bit value read from Buffer. + +**/ +UINT32 +EFIAPI +ReadUnaligned24 ( + IN CONST UINT32 *Buffer + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer & 0xffffff; +} + +/** + Writes a 24-bit value to memory that may be unaligned. + + This function writes the 24-bit value specified by Value to Buffer. Value is + returned. The function guarantees that the write operation does not produce + an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 24-bit value that may be unaligned. + @param Value 24-bit value to write to Buffer. + + @return The 24-bit value to write to Buffer. + +**/ +UINT32 +EFIAPI +WriteUnaligned24 ( + OUT UINT32 *Buffer, + IN UINT32 Value + ) +{ + ASSERT (Buffer != NULL); + + *Buffer = BitFieldWrite32 (*Buffer, 0, 23, Value); + return Value; +} + +/** + Reads a 32-bit value from memory that may be unaligned. + + This function returns the 32-bit value pointed to by Buffer. The function + guarantees that the read operation does not produce an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 32-bit value that may be unaligned. + + @return The 32-bit value read from Buffer. + +**/ +UINT32 +EFIAPI +ReadUnaligned32 ( + IN CONST UINT32 *Buffer + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer; +} + +/** + Writes a 32-bit value to memory that may be unaligned. + + This function writes the 32-bit value specified by Value to Buffer. Value is + returned. The function guarantees that the write operation does not produce + an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 32-bit value that may be unaligned. + @param Value The 32-bit value to write to Buffer. + + @return The 32-bit value to write to Buffer. + +**/ +UINT32 +EFIAPI +WriteUnaligned32 ( + OUT UINT32 *Buffer, + IN UINT32 Value + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer = Value; +} + +/** + Reads a 64-bit value from memory that may be unaligned. + + This function returns the 64-bit value pointed to by Buffer. The function + guarantees that the read operation does not produce an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 64-bit value that may be unaligned. + + @return The 64-bit value read from Buffer. + +**/ +UINT64 +EFIAPI +ReadUnaligned64 ( + IN CONST UINT64 *Buffer + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer; +} + +/** + Writes a 64-bit value to memory that may be unaligned. + + This function writes the 64-bit value specified by Value to Buffer. Value is + returned. The function guarantees that the write operation does not produce + an alignment fault. + + If the Buffer is NULL, then ASSERT(). + + @param Buffer A pointer to a 64-bit value that may be unaligned. + @param Value The 64-bit value to write to Buffer. + + @return The 64-bit value to write to Buffer. + +**/ +UINT64 +EFIAPI +WriteUnaligned64 ( + OUT UINT64 *Buffer, + IN UINT64 Value + ) +{ + ASSERT (Buffer != NULL); + + return *Buffer = Value; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm b/MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm new file mode 100644 index 00000000000..7e7fe99670f --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm @@ -0,0 +1,77 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; RdRand.nasm +; +; Abstract: +; +; Generates random number through CPU RdRand instruction under 64-bit platform. +; +; Notes: +; +;------------------------------------------------------------------------------ + + DEFAULT REL + SECTION .text + +;------------------------------------------------------------------------------ +; Generates a 16 bit random number through RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand16 (UINT16 *Rand); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand16) +ASM_PFX(InternalX86RdRand16): + ; rdrand ax ; generate a 16 bit RN into eax, + ; CF=1 if RN generated ok, otherwise CF=0 + db 0xf, 0xc7, 0xf0 ; rdrand r16: "0f c7 /6 ModRM:r/m(w)" + jc rn16_ok ; jmp if CF=1 + xor rax, rax ; reg=0 if CF=0 + ret ; return with failure status +rn16_ok: + mov [rcx], ax + mov rax, 1 + ret + +;------------------------------------------------------------------------------ +; Generates a 32 bit random number through RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand32 (UINT32 *Rand); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand32) +ASM_PFX(InternalX86RdRand32): + ; rdrand eax ; generate a 32 bit RN into eax, + ; CF=1 if RN generated ok, otherwise CF=0 + db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" + jc rn32_ok ; jmp if CF=1 + xor rax, rax ; reg=0 if CF=0 + ret ; return with failure status +rn32_ok: + mov [rcx], eax + mov rax, 1 + ret + +;------------------------------------------------------------------------------ +; Generates a 64 bit random number through one RDRAND instruction. +; Return TRUE if Rand generated successfully, or FALSE if not. +; +; BOOLEAN EFIAPI InternalX86RdRand64 (UINT64 *Random); +;------------------------------------------------------------------------------ +global ASM_PFX(InternalX86RdRand64) +ASM_PFX(InternalX86RdRand64): + ; rdrand rax ; generate a 64 bit RN into rax, + ; CF=1 if RN generated ok, otherwise CF=0 + db 0x48, 0xf, 0xc7, 0xf0 ; rdrand r64: "REX.W + 0f c7 /6 ModRM:r/m(w)" + jc rn64_ok ; jmp if CF=1 + xor rax, rax ; reg=0 if CF=0 + ret ; return with failure status +rn64_ok: + mov [rcx], rax + mov rax, 1 + ret + diff --git a/MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm b/MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm new file mode 100644 index 00000000000..45672d680e6 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm @@ -0,0 +1,34 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2006, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +; Module Name: +; +; ReadTsc.Asm +; +; Abstract: +; +; AsmReadTsc function +; +; Notes: +; +;------------------------------------------------------------------------------ + + DEFAULT REL + SECTION .text + +;------------------------------------------------------------------------------ +; UINT64 +; EFIAPI +; AsmReadTsc ( +; VOID +; ); +;------------------------------------------------------------------------------ +global ASM_PFX(AsmReadTsc) +ASM_PFX(AsmReadTsc): + rdtsc + shl rdx, 0x20 + or rax, rdx + ret + diff --git a/MdePkg/HostLibrary/BaseLibHost/X86Cr.c b/MdePkg/HostLibrary/BaseLibHost/X86Cr.c new file mode 100644 index 00000000000..ab16ca6e286 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86Cr.c @@ -0,0 +1,180 @@ +/** @file + Base Library CPU Functions for all architectures. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +UINTN gCr0; +UINTN gCr2; +UINTN gCr3; +UINTN gCr4; + +/** + Reads the current value of the Control Register 0 (CR0). + + Reads and returns the current value of CR0. This function is only available + on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on + x64. + + @return The value of the Control Register 0 (CR0). + +**/ +UINTN +EFIAPI +AsmReadCr0 ( + VOID + ) +{ + return gCr0; +} + + +/** + Reads the current value of the Control Register 2 (CR2). + + Reads and returns the current value of CR2. This function is only available + on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on + x64. + + @return The value of the Control Register 2 (CR2). + +**/ +UINTN +EFIAPI +AsmReadCr2 ( + VOID + ) +{ + return gCr2; +} + + +/** + Reads the current value of the Control Register 3 (CR3). + + Reads and returns the current value of CR3. This function is only available + on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on + x64. + + @return The value of the Control Register 3 (CR3). + +**/ +UINTN +EFIAPI +AsmReadCr3 ( + VOID + ) +{ + return gCr3; +} + + +/** + Reads the current value of the Control Register 4 (CR4). + + Reads and returns the current value of CR4. This function is only available + on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on + x64. + + @return The value of the Control Register 4 (CR4). + +**/ +UINTN +EFIAPI +AsmReadCr4 ( + VOID + ) +{ + return gCr4; +} + + +/** + Writes a value to Control Register 0 (CR0). + + Writes and returns a new value to CR0. This function is only available on + IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. + + @param Cr0 The value to write to CR0. + + @return The value written to CR0. + +**/ +UINTN +EFIAPI +AsmWriteCr0 ( + UINTN Cr0 + ) +{ + gCr0 = Cr0; + return Cr0; +} + +/** + Writes a value to Control Register 2 (CR2). + + Writes and returns a new value to CR2. This function is only available on + IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. + + @param Cr2 The value to write to CR2. + + @return The value written to CR2. + +**/ +UINTN +EFIAPI +AsmWriteCr2 ( + UINTN Cr2 + ) +{ + gCr2 = Cr2; + return Cr2; +} + + +/** + Writes a value to Control Register 3 (CR3). + + Writes and returns a new value to CR3. This function is only available on + IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. + + @param Cr3 The value to write to CR3. + + @return The value written to CR3. + +**/ +UINTN +EFIAPI +AsmWriteCr3 ( + UINTN Cr3 + ) +{ + gCr3 = Cr3; + return Cr3; +} + + +/** + Writes a value to Control Register 4 (CR4). + + Writes and returns a new value to CR4. This function is only available on + IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. + + @param Cr4 The value to write to CR4. + + @return The value written to CR4. + +**/ +UINTN +EFIAPI +AsmWriteCr4 ( + UINTN Cr4 + ) +{ + gCr4 = Cr4; + return Cr4; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c b/MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c new file mode 100644 index 00000000000..255264fd71b --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c @@ -0,0 +1,53 @@ +/** @file + IA-32/x64 AsmDisablePaging64() + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Disables the 64-bit paging mode on the CPU. + + Disables the 64-bit paging mode on the CPU and returns to 32-bit protected + mode. This function assumes the current execution mode is 64-paging mode. + This function is only available on x64. After the 64-bit paging mode is + disabled, control is transferred to the function specified by EntryPoint + using the new stack specified by NewStack and passing in the parameters + specified by Context1 and Context2. Context1 and Context2 are optional and + may be 0. The function EntryPoint must never return. + + If the current execution mode is not 64-bit paged mode, then ASSERT(). + If EntryPoint is 0, then ASSERT(). + If NewStack is 0, then ASSERT(). + + @param Cs The 16-bit selector to load in the CS before EntryPoint + is called. The descriptor in the GDT that this selector + references must be setup for 32-bit protected mode. + @param EntryPoint The 64-bit virtual address of the function to call with + the new stack after paging is disabled. + @param Context1 The 64-bit virtual address of the context to pass into + the EntryPoint function as the first parameter after + paging is disabled. + @param Context2 The 64-bit virtual address of the context to pass into + the EntryPoint function as the second parameter after + paging is disabled. + @param NewStack The 64-bit virtual address of the new stack to use for + the EntryPoint function after paging is disabled. + +**/ +VOID +EFIAPI +AsmDisablePaging64 ( + IN UINT16 Cs, + IN UINT32 EntryPoint, + IN UINT32 Context1, OPTIONAL + IN UINT32 Context2, OPTIONAL + IN UINT32 NewStack + ) +{ + ASSERT (FALSE); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86Dr.c b/MdePkg/HostLibrary/BaseLibHost/X86Dr.c new file mode 100644 index 00000000000..057ec9781f9 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86Dr.c @@ -0,0 +1,170 @@ +/** @file + Base Library CPU Functions for all architectures. + + Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +UINTN gDr0; +UINTN gDr1; +UINTN gDr2; +UINTN gDr3; +UINTN gDr4; +UINTN gDr5; +UINTN gDr6; +UINTN gDr7; + +UINTN +EFIAPI +AsmReadDr0 ( + VOID + ) +{ + return gDr0; +} + +UINTN +EFIAPI +AsmReadDr1 ( + VOID + ) +{ + return gDr1; +} + +UINTN +EFIAPI +AsmReadDr2 ( + VOID + ) +{ + return gDr2; +} + +UINTN +EFIAPI +AsmReadDr3 ( + VOID + ) +{ + return gDr3; +} + +UINTN +EFIAPI +AsmReadDr4 ( + VOID + ) +{ + return gDr4; +} + +UINTN +EFIAPI +AsmReadDr5 ( + VOID + ) +{ + return gDr5; +} + +UINTN +EFIAPI +AsmReadDr6 ( + VOID + ) +{ + return gDr6; +} + +UINTN +EFIAPI +AsmReadDr7 ( + VOID + ) +{ + return gDr7; +} + +UINTN +EFIAPI +AsmWriteDr0 ( + UINTN Dr0 + ) +{ + gDr0 = Dr0; + return Dr0; +} + +UINTN +EFIAPI +AsmWriteDr1 ( + UINTN Dr1 + ) +{ + gDr1 = Dr1; + return Dr1; +} + +UINTN +EFIAPI +AsmWriteDr2 ( + UINTN Dr2 + ) +{ + gDr2 = Dr2; + return Dr2; +} + +UINTN +EFIAPI +AsmWriteDr3 ( + UINTN Dr3 + ) +{ + gDr3 = Dr3; + return Dr3; +} + +UINTN +EFIAPI +AsmWriteDr4 ( + UINTN Dr4 + ) +{ + gDr4 = Dr4; + return Dr4; +} + +UINTN +EFIAPI +AsmWriteDr5 ( + UINTN Dr5 + ) +{ + gDr5 = Dr5; + return Dr5; +} + +UINTN +EFIAPI +AsmWriteDr6 ( + UINTN Dr6 + ) +{ + gDr6 = Dr6; + return Dr6; +} + +UINTN +EFIAPI +AsmWriteDr7 ( + UINTN Dr7 + ) +{ + gDr7 = Dr7; + return Dr7; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c b/MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c new file mode 100644 index 00000000000..9a7a7dad4da --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c @@ -0,0 +1,50 @@ +/** @file + IA-32/x64 AsmReadGdtr() + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Reads the current Global Descriptor Table Register(GDTR) descriptor. + + Reads and returns the current GDTR descriptor and returns it in Gdtr. This + function is only available on IA-32 and x64. + + If Gdtr is NULL, then ASSERT(). + + @param Gdtr The pointer to a GDTR descriptor. + +**/ +VOID +EFIAPI +AsmReadGdtr ( + OUT IA32_DESCRIPTOR *Gdtr + ) +{ + ASSERT (FALSE); +} + +/** + Writes the current Global Descriptor Table Register (GDTR) descriptor. + + Writes and the current GDTR descriptor specified by Gdtr. This function is + only available on IA-32 and x64. + + If Gdtr is NULL, then ASSERT(). + + @param Gdtr The pointer to a GDTR descriptor. + +**/ +VOID +EFIAPI +AsmWriteGdtr ( + IN CONST IA32_DESCRIPTOR *Gdtr + ) +{ + ASSERT (FALSE); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c b/MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c new file mode 100644 index 00000000000..3fb1aa835a1 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c @@ -0,0 +1,50 @@ +/** @file + IA-32/x64 AsmReadIdtr() + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Reads the current Interrupt Descriptor Table Register(IDTR) descriptor. + + Reads and returns the current IDTR descriptor and returns it in Idtr. This + function is only available on IA-32 and x64. + + If Idtr is NULL, then ASSERT(). + + @param Idtr The pointer to a IDTR descriptor. + +**/ +VOID +EFIAPI +AsmReadIdtr ( + OUT IA32_DESCRIPTOR *Idtr + ) +{ + ASSERT (FALSE); +} + +/** + Writes the current Interrupt Descriptor Table Register(IDTR) descriptor. + + Writes the current IDTR descriptor and returns it in Idtr. This function is + only available on IA-32 and x64. + + If Idtr is NULL, then ASSERT(). + + @param Idtr The pointer to a IDTR descriptor. + +**/ +VOID +EFIAPI +AsmWriteIdtr ( + IN CONST IA32_DESCRIPTOR *Idtr + ) +{ + ASSERT (FALSE); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c b/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c new file mode 100644 index 00000000000..da85c1bd451 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c @@ -0,0 +1,29 @@ +/** @file + GCC inline implementation of BaseLib processor specific functions. + + Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + + +/** + Used to serialize load and store operations. + + All loads and stores that proceed calls to this function are guaranteed to be + globally visible when this function returns. + +**/ +VOID +EFIAPI +MemoryFence ( + VOID + ) +{ + // This is a little bit of overkill and it is more about the compiler that it is + // actually processor synchronization. This is like the _ReadWriteBarrier + // Microsoft specific intrinsic + __asm__ __volatile__ ("":::"memory"); +} + diff --git a/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c b/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c new file mode 100644 index 00000000000..5e61a4a782b --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c @@ -0,0 +1,27 @@ +/** @file + IA-32/x64 MemoryFence(). + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +void _ReadWriteBarrier (void); +#pragma intrinsic(_ReadWriteBarrier) + +/** + Used to serialize load and store operations. + + All loads and stores that proceed calls to this function are guaranteed to be + globally visible when this function returns. + +**/ +VOID +EFIAPI +MemoryFence ( + VOID + ) +{ + _ReadWriteBarrier (); + return; +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c b/MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c new file mode 100644 index 00000000000..e833afb955f --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c @@ -0,0 +1,84 @@ +/** @file + IA-32/x64 PatchInstructionX86() + + Copyright (C) 2018, Intel Corporation. All rights reserved.
+ Copyright (C) 2018, Red Hat, Inc. + + SPDX-License-Identifier: BSD-2-Clause-Patent +**/ + +#include +#include + +/** + Patch the immediate operand of an IA32 or X64 instruction such that the byte, + word, dword or qword operand is encoded at the end of the instruction's + binary representation. + + This function should be used to update object code that was compiled with + NASM from assembly source code. Example: + + NASM source code: + + mov eax, strict dword 0 ; the imm32 zero operand will be patched + ASM_PFX(gPatchCr3): + mov cr3, eax + + C source code: + + X86_ASSEMBLY_PATCH_LABEL gPatchCr3; + PatchInstructionX86 (gPatchCr3, AsmReadCr3 (), 4); + + @param[out] InstructionEnd Pointer right past the instruction to patch. The + immediate operand to patch is expected to + comprise the trailing bytes of the instruction. + If InstructionEnd is closer to address 0 than + ValueSize permits, then ASSERT(). + + @param[in] PatchValue The constant to write to the immediate operand. + The caller is responsible for ensuring that + PatchValue can be represented in the byte, word, + dword or qword operand (as indicated through + ValueSize); otherwise ASSERT(). + + @param[in] ValueSize The size of the operand in bytes; must be 1, 2, + 4, or 8. ASSERT() otherwise. +**/ +VOID +EFIAPI +PatchInstructionX86 ( + OUT X86_ASSEMBLY_PATCH_LABEL *InstructionEnd, + IN UINT64 PatchValue, + IN UINTN ValueSize + ) +{ + // + // The equality ((UINTN)InstructionEnd == ValueSize) would assume a zero-size + // instruction at address 0; forbid it. + // + ASSERT ((UINTN)InstructionEnd > ValueSize); + + switch (ValueSize) { + case 1: + ASSERT (PatchValue <= MAX_UINT8); + *((UINT8 *)(UINTN)InstructionEnd - 1) = (UINT8)PatchValue; + break; + + case 2: + ASSERT (PatchValue <= MAX_UINT16); + WriteUnaligned16 ((UINT16 *)(UINTN)InstructionEnd - 1, (UINT16)PatchValue); + break; + + case 4: + ASSERT (PatchValue <= MAX_UINT32); + WriteUnaligned32 ((UINT32 *)(UINTN)InstructionEnd - 1, (UINT32)PatchValue); + break; + + case 8: + WriteUnaligned64 ((UINT64 *)(UINTN)InstructionEnd - 1, PatchValue); + break; + + default: + ASSERT (FALSE); + } +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86RdRand.c b/MdePkg/HostLibrary/BaseLibHost/X86RdRand.c new file mode 100644 index 00000000000..5f5fa85e413 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86RdRand.c @@ -0,0 +1,121 @@ +/** @file + IA-32/x64 AsmRdRandxx() + Generates random number through CPU RdRand instruction. + + Copyright (c) 2016, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + +/** + Generates a 16-bit random number through RDRAND instruction. + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + + **/ +BOOLEAN +EFIAPI +InternalX86RdRand16 ( + OUT UINT16 *Rand + ); + +/** + Generates a 32-bit random number through RDRAND instruction. + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +InternalX86RdRand32 ( + OUT UINT32 *Rand + ); + +/** + Generates a 64-bit random number through RDRAND instruction. + + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +InternalX86RdRand64 ( + OUT UINT64 *Rand + ); + +/** + Generates a 16-bit random number through RDRAND instruction. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + + **/ +BOOLEAN +EFIAPI +AsmRdRand16 ( + OUT UINT16 *Rand + ) +{ + ASSERT (Rand != NULL); + return InternalX86RdRand16 (Rand); +} + +/** + Generates a 32-bit random number through RDRAND instruction. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +AsmRdRand32 ( + OUT UINT32 *Rand + ) +{ + ASSERT (Rand != NULL); + return InternalX86RdRand32 (Rand); +} + +/** + Generates a 64-bit random number through RDRAND instruction. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the random result. + + @retval TRUE RDRAND call was successful. + @retval FALSE Failed attempts to call RDRAND. + +**/ +BOOLEAN +EFIAPI +AsmRdRand64 ( + OUT UINT64 *Rand + ) +{ + ASSERT (Rand != NULL); + return InternalX86RdRand64 (Rand); +} diff --git a/MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c b/MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c new file mode 100644 index 00000000000..b3690956373 --- /dev/null +++ b/MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c @@ -0,0 +1,163 @@ +/** @file + IA-32/x64 AsmReadGdtr() + + Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Reads the current value of Code Segment Register (CS). + + Reads and returns the current value of CS. This function is only available on + IA-32 and x64. + + @return The current value of CS. + +**/ +UINT16 +EFIAPI +AsmReadCs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of Data Segment Register (DS). + + Reads and returns the current value of DS. This function is only available on + IA-32 and x64. + + @return The current value of DS. + +**/ +UINT16 +EFIAPI +AsmReadDs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of Extra Segment Register (ES). + + Reads and returns the current value of ES. This function is only available on + IA-32 and x64. + + @return The current value of ES. + +**/ +UINT16 +EFIAPI +AsmReadEs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of FS Data Segment Register (FS). + + Reads and returns the current value of FS. This function is only available on + IA-32 and x64. + + @return The current value of FS. + +**/ +UINT16 +EFIAPI +AsmReadFs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of GS Data Segment Register (GS). + + Reads and returns the current value of GS. This function is only available on + IA-32 and x64. + + @return The current value of GS. + +**/ +UINT16 +EFIAPI +AsmReadGs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of Stack Segment Register (SS). + + Reads and returns the current value of SS. This function is only available on + IA-32 and x64. + + @return The current value of SS. + +**/ +UINT16 +EFIAPI +AsmReadSs ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + + +/** + Reads the current value of Task Register (TR). + + Reads and returns the current value of TR. This function is only available on + IA-32 and x64. + + @return The current value of TR. + +**/ +UINT16 +EFIAPI +AsmReadTr ( + VOID + ) +{ + ASSERT (FALSE); + return 0; +} + +/** + Load given selector into TR register. + + @param[in] Selector Task segment selector +**/ +VOID +EFIAPI +AsmWriteTr ( + IN UINT16 Selector + ) +{ + ASSERT (FALSE); +} \ No newline at end of file diff --git a/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c b/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c new file mode 100644 index 00000000000..712fe1500ee --- /dev/null +++ b/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c @@ -0,0 +1,160 @@ +/** @file + +Copyright (c) 2018, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include + +#include + +VOID * +EFIAPI +SetMem ( + OUT VOID *Buffer, + IN UINTN Length, + IN UINT8 Value + ) +{ + memset (Buffer, Value, Length); + return Buffer; +} + +VOID * +EFIAPI +SetMem16 ( + OUT VOID *Buffer, + IN UINTN Length, + IN UINT16 Value + ) +{ + for (; Length != 0; Length--) { + ((UINT16*)Buffer)[Length - 1] = Value; + } + return Buffer; +} + +VOID * +EFIAPI +SetMem32 ( + OUT VOID *Buffer, + IN UINTN Length, + IN UINT32 Value + ) +{ + for (; Length != 0; Length--) { + ((UINT32*)Buffer)[Length - 1] = Value; + } + return Buffer; +} + +VOID * +EFIAPI +SetMem64 ( + OUT VOID *Buffer, + IN UINTN Length, + IN UINT64 Value + ) +{ + for (; Length != 0; Length--) { + ((UINT64*)Buffer)[Length - 1] = Value; + } + return Buffer; +} + +VOID * +EFIAPI +SetMemN ( + OUT VOID *Buffer, + IN UINTN Length, + IN UINTN Value + ) +{ + if (sizeof (UINTN) == sizeof (UINT64)) { + return SetMem64 (Buffer, Length, (UINT64)Value); + } else { + return SetMem32 (Buffer, Length, (UINT32)Value); + } +} + +VOID * +EFIAPI +ZeroMem ( + OUT VOID *Buffer, + IN UINTN Length + ) +{ + memset (Buffer, 0, Length); + return Buffer; +} + +VOID * +EFIAPI +CopyMem ( + OUT VOID *DestinationBuffer, + IN CONST VOID *SourceBuffer, + IN UINTN Length + ) +{ + memmove (DestinationBuffer, SourceBuffer, Length); + return DestinationBuffer; +} + +INTN +EFIAPI +CompareMem ( + IN CONST VOID *DestinationBuffer, + IN CONST VOID *SourceBuffer, + IN UINTN Length + ) +{ + return memcmp (DestinationBuffer, SourceBuffer, Length); +} + +BOOLEAN +EFIAPI +CompareGuid ( + IN CONST GUID *Guid1, + IN CONST GUID *Guid2 + ) +{ + return ((BOOLEAN)(memcmp (Guid1, Guid2, sizeof (GUID)) == 0)); +} + +GUID * +EFIAPI +CopyGuid ( + OUT GUID *DestinationGuid, + IN CONST GUID *SourceGuid + ) +{ + memmove (DestinationGuid, SourceGuid, sizeof(GUID)); + return DestinationGuid; +} + +UINT8 mZeroGuid[sizeof(GUID)] = {0}; + +BOOLEAN +EFIAPI +IsZeroGuid ( + IN CONST GUID *Guid + ) +{ + return ((BOOLEAN)(memcmp (Guid, mZeroGuid, sizeof (GUID)) == 0)); +} + +VOID * +EFIAPI +ScanMem8 ( + IN CONST VOID *Buffer, + IN UINTN Length, + IN UINT8 Value + ) +{ + return memchr (Buffer, Value, Length); +} + diff --git a/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf b/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf new file mode 100644 index 00000000000..35c7234aa55 --- /dev/null +++ b/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf @@ -0,0 +1,24 @@ +## @file +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = BaseMemoryLibHost + FILE_GUID = 90B7948B-DFED-46FB-BABE-770A5A464BA5 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = BaseMemoryLib | HOST_APPLICATION + +[Sources] + BaseMemoryLibHost.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + diff --git a/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c b/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c new file mode 100644 index 00000000000..1bc306ca262 --- /dev/null +++ b/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c @@ -0,0 +1,182 @@ +/** @file + +Copyright (c) 2018, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +#include +#include +#include + +#ifndef HOST_DEBUG_MESSAGE +#define HOST_DEBUG_MESSAGE 0 +#endif + +// +// Define the maximum debug and assert message length that this library supports +// +#define MAX_DEBUG_MESSAGE_LENGTH 0x100 + +VOID +EFIAPI +DebugAssert ( + IN CONST CHAR8 *FileName, + IN UINTN LineNumber, + IN CONST CHAR8 *Description + ) +{ +#ifndef TEST_WITH_KLEE + printf ("ASSERT: %s(%d): %s\n", FileName, (INT32)(UINT32)LineNumber, Description); + CpuBreakpoint (); +#endif +} + +BOOLEAN +EFIAPI +DebugAssertEnabled ( + VOID + ) +{ + return TRUE; +} + +VOID +PatchFormat ( + IN CONST CHAR8 *Format, + IN CHAR8 *MyFormat + ) +{ + UINTN Index; + UINTN MyIndex; + + Index = 0; + MyIndex = 0; + while (Format[Index] != 0) { + MyFormat[MyIndex] = Format[Index]; + if (Format[Index] == '%') { + Index++; + MyIndex++; + switch (Format[Index]) { + case 'a': + MyFormat[MyIndex] = 's'; + break; + case 's': + MyFormat[MyIndex] = 'w'; + MyIndex++; + MyFormat[MyIndex] = 's'; + break; + case 'g': + case 't': + MyFormat[MyIndex] = 'p'; + break; + case 'r': + MyFormat[MyIndex] = 'x'; + break; + case 'L': + case 'l': + MyFormat[MyIndex] = 'I'; + MyIndex++; + MyFormat[MyIndex] = '6'; + MyIndex++; + MyFormat[MyIndex] = '4'; + break; + case '0': + MyFormat[MyIndex] = Format[Index]; + if (Format[Index + 1] == '1') { + Index++; + MyIndex++; + MyFormat[MyIndex] = Format[Index]; + } + case '1': + MyFormat[MyIndex] = Format[Index]; + if (Format[Index + 1] == '6') { + Index++; + MyIndex++; + MyFormat[MyIndex] = Format[Index]; + } + if (Format[Index + 1] == 'l') { + Index++; + MyIndex++; + MyFormat[MyIndex] = 'I'; + MyIndex++; + MyFormat[MyIndex] = '6'; + MyIndex++; + MyFormat[MyIndex] = '4'; + } + if (Format[Index + 1] == 'l') { + Index++; + } + break; + default: + MyFormat[MyIndex] = Format[Index]; + break; + } + } + Index++; + MyIndex++; + } + MyFormat[MyIndex] = 0; +} + +VOID +EFIAPI +DebugPrint ( + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ) +{ +#ifndef TEST_WITH_KLEE +#if HOST_DEBUG_MESSAGE + CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; + CHAR8 MyFormat[MAX_DEBUG_MESSAGE_LENGTH]; + VA_LIST Marker; + + VA_START (Marker, Format); + + if (0) { + PatchFormat (Format, MyFormat); + vsprintf (Buffer, MyFormat, Marker); + } else { + AsciiVSPrint (Buffer, sizeof (Buffer), Format, Marker); + } + VA_END (Marker); + + printf ("%s", Buffer); +#endif +#endif +} + +BOOLEAN +EFIAPI +DebugPrintEnabled ( + VOID + ) +{ + return TRUE; +} + +BOOLEAN +EFIAPI +DebugPrintLevelEnabled ( + IN CONST UINTN ErrorLevel + ) +{ + return TRUE; +} + +BOOLEAN +EFIAPI +DebugCodeEnabled ( + VOID + ) +{ + return TRUE; +} diff --git a/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf b/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf new file mode 100644 index 00000000000..78f062ff5ff --- /dev/null +++ b/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf @@ -0,0 +1,30 @@ +## @file +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = DebugLibHost + FILE_GUID = 6A77CE89-C1B6-4A6B-9561-07D7127514A7 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = DebugLib | HOST_APPLICATION + +[Sources] + DebugLibHost.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + PrintLib + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = /D _CRT_SECURE_NO_WARNINGS + GCC:*_KLEE_*_CC_FLAGS = "-DTEST_WITH_KLEE=TRUE" + + diff --git a/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c b/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c new file mode 100644 index 00000000000..8a92a888065 --- /dev/null +++ b/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c @@ -0,0 +1,302 @@ +/** @file + +Copyright (c) 2018, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include + +#include + +#define PAGE_HEAD_PRIVATE_SIGNATURE SIGNATURE_32 ('P', 'H', 'D', 'R') + +typedef struct { + UINT32 Signature; + VOID *AllocatedBufffer; + UINTN TotalPages; + VOID *AlignedBuffer; + UINTN AlignedPages; +} PAGE_HEAD; + +VOID * +EFIAPI +AllocateAlignedPages ( + IN UINTN Pages, + IN UINTN Alignment + ); + +VOID +EFIAPI +FreeAlignedPages ( + IN VOID *Buffer, + IN UINTN Pages + ); + +VOID * +EFIAPI +AllocatePages ( + IN UINTN Pages + ) +{ + return AllocateAlignedPages (Pages, SIZE_4KB); +} + +VOID * +EFIAPI +AllocateRuntimePages ( + IN UINTN Pages + ) +{ + return AllocatePages (Pages); +} + +VOID * +EFIAPI +AllocateReservedPages ( + IN UINTN Pages + ) +{ + return AllocatePages (Pages); +} + +VOID +EFIAPI +FreePages ( + IN VOID *Buffer, + IN UINTN Pages + ) +{ + FreeAlignedPages (Buffer, Pages); +} + +VOID * +EFIAPI +AllocateAlignedPages ( + IN UINTN Pages, + IN UINTN Alignment + ) +{ + PAGE_HEAD PageHead; + PAGE_HEAD *PageHeadPtr; + UINTN AlignmentMask; + + assert ((Alignment & (Alignment - 1)) == 0); + + if (Alignment < SIZE_4KB) { + Alignment = SIZE_4KB; + } + AlignmentMask = Alignment - 1; + + // + // We need reserve Alignment pages for PAGE_HEAD, as meta data. + // + + PageHead.Signature = PAGE_HEAD_PRIVATE_SIGNATURE; + PageHead.TotalPages = Pages + EFI_SIZE_TO_PAGES(Alignment) * 2; + PageHead.AlignedPages = Pages; + PageHead.AllocatedBufffer = malloc (EFI_PAGES_TO_SIZE(PageHead.TotalPages)); + if (PageHead.AllocatedBufffer == NULL) { + return NULL; + } + PageHead.AlignedBuffer = (VOID *)(((UINTN) PageHead.AllocatedBufffer + AlignmentMask) & ~AlignmentMask); + if ((UINTN)PageHead.AlignedBuffer - (UINTN)PageHead.AllocatedBufffer < sizeof(PAGE_HEAD)) { + PageHead.AlignedBuffer = (VOID *)((UINTN)PageHead.AlignedBuffer + Alignment); + } + + PageHeadPtr = (VOID *)((UINTN)PageHead.AlignedBuffer - sizeof(PAGE_HEAD)); + memcpy (PageHeadPtr, &PageHead, sizeof(PAGE_HEAD)); + + return PageHead.AlignedBuffer; +} + +VOID * +EFIAPI +AllocateAlignedRuntimePages ( + IN UINTN Pages, + IN UINTN Alignment + ) +{ + return AllocateAlignedPages (Pages, Alignment); +} + +VOID * +EFIAPI +AllocateAlignedReservedPages ( + IN UINTN Pages, + IN UINTN Alignment + ) +{ + return AllocateAlignedPages (Pages, Alignment); +} + +VOID +EFIAPI +FreeAlignedPages ( + IN VOID *Buffer, + IN UINTN Pages + ) +{ + PAGE_HEAD *PageHeadPtr; + + // + // NOTE: Partial free is not supported. Just keep it. + // + + PageHeadPtr = (VOID *)((UINTN)Buffer - sizeof(PAGE_HEAD)); + if (PageHeadPtr->Signature != PAGE_HEAD_PRIVATE_SIGNATURE) { + return ; + } + if (PageHeadPtr->AlignedPages != Pages) { + return ; + } + + PageHeadPtr->Signature = 0; + free (PageHeadPtr->AllocatedBufffer); +} + +VOID * +EFIAPI +AllocatePool ( + IN UINTN AllocationSize + ) +{ + return malloc (AllocationSize); +} + +VOID * +EFIAPI +AllocateRuntimePool ( + IN UINTN AllocationSize + ) +{ + return AllocatePool (AllocationSize); +} + +VOID * +EFIAPI +AllocateReservedPool ( + IN UINTN AllocationSize + ) +{ + return AllocatePool (AllocationSize); +} + +VOID * +EFIAPI +AllocateZeroPool ( + IN UINTN AllocationSize + ) +{ + VOID *Buffer; + Buffer = malloc (AllocationSize); + if (Buffer == NULL) { + return NULL; + } + memset (Buffer, 0, AllocationSize); + return Buffer; +} + +VOID * +EFIAPI +AllocateRuntimeZeroPool ( + IN UINTN AllocationSize + ) +{ + return AllocateZeroPool (AllocationSize); +} + +VOID * +EFIAPI +AllocateReservedZeroPool ( + IN UINTN AllocationSize + ) +{ + return AllocateZeroPool (AllocationSize); +} + +VOID * +EFIAPI +AllocateCopyPool ( + IN UINTN AllocationSize, + IN CONST VOID *Buffer + ) +{ + VOID *Memory; + Memory = malloc (AllocationSize); + if (Memory == NULL) { + return NULL; + } + memcpy (Memory, Buffer, AllocationSize); + return Memory; +} + +VOID * +EFIAPI +AllocateRuntimeCopyPool ( + IN UINTN AllocationSize, + IN CONST VOID *Buffer + ) +{ + return AllocateCopyPool (AllocationSize, Buffer); +} + +VOID * +EFIAPI +AllocateReservedCopyPool ( + IN UINTN AllocationSize, + IN CONST VOID *Buffer + ) +{ + return AllocateCopyPool (AllocationSize, Buffer); +} + +VOID * +EFIAPI +ReallocatePool ( + IN UINTN OldSize, + IN UINTN NewSize, + IN VOID *OldBuffer OPTIONAL + ) +{ + VOID *NewBuffer; + NewBuffer = malloc (NewSize); + if (NewBuffer != NULL && OldBuffer != NULL) { + memcpy (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); + } + return NewBuffer; +} + +VOID * +EFIAPI +ReallocateRuntimePool ( + IN UINTN OldSize, + IN UINTN NewSize, + IN VOID *OldBuffer OPTIONAL + ) +{ + return ReallocatePool (OldSize, NewSize, OldBuffer); +} + +VOID * +EFIAPI +ReallocateReservedPool ( + IN UINTN OldSize, + IN UINTN NewSize, + IN VOID *OldBuffer OPTIONAL + ) +{ + return ReallocatePool (OldSize, NewSize, OldBuffer); +} + +VOID +EFIAPI +FreePool ( + IN VOID *Buffer + ) +{ + free (Buffer); +} diff --git a/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf b/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf new file mode 100644 index 00000000000..37d4c00cff7 --- /dev/null +++ b/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf @@ -0,0 +1,24 @@ +## @file +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MemoryAllocationLibHost + FILE_GUID = A1672454-A3D3-4AAC-A86B-8D63132BBB91 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + LIBRARY_CLASS = MemoryAllocationLib | HOST_APPLICATION + +[Sources] + MemoryAllocationLibHost.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/MdePkgTest.dsc index 2f6086aca26..92c0a4bb35d 100644 --- a/MdePkg/MdePkgTest.dsc +++ b/MdePkg/MdePkgTest.dsc @@ -1,5 +1,5 @@ ## @file MdePkgTest.dsc -# +# # Copyright (c) 2019, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -12,39 +12,24 @@ DSC_SPECIFICATION = 0x00010005 OUTPUT_DIRECTORY = Build/MdePkg SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = DEBUG|RELEASE|NOOPT + BUILD_TARGETS = NOOPT SKUID_IDENTIFIER = DEFAULT - FLASH_DEFINITION = MdePkg/MdePkgTest.fdf - - DEFINE UNIT_TEST_FRAMEWORK_MODE = CMOCKA - DEFINE UNIT_TEST_XML_MODE = FALSE - -[PcdsFixedAtBuild] - !if $(UNIT_TEST_XML_MODE) == TRUE - gUefiHostUnitTestPkgTokenSpaceGuid.HostUnitTestMode|0x1 - !endif [LibraryClasses] CmockaLib|CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf + BaseLib|MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf + BaseMemoryLib|MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf + DebugLib|MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf + MemoryAllocationLib|MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + OsServiceLib|UnitTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - BaseLib|MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf - BaseMemoryLib|MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf - DebugLib|MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf - DevicePathLib|MdePkg/HostLibrary/UefiDevicePathLibHost/UefiDevicePathLibHost.inf - DxeServicesTableLib|MdePkg/HostLibrary/DxeServicesTableLibHost/DxeServicesTableLibHost.inf - MemoryAllocationLib|MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - PeiServicesTablePointerLib|MdePkg/HostLibrary/PeiServicesTablePointerLibHost/PeiServicesTablePointerLibHost.inf - SmmServicesTableLib|MdePkg/HostLibrary/SmmServicesTableLibHost/SmmServicesTableLibHost.inf - UefiBootServicesTableLib|MdePkg/HostLibrary/UefiBootServicesTableLibHost/UefiBootServicesTableLibHost.inf - UefiRuntimeServicesTableLib|MdePkg/HostLibrary/UefiRuntimeServicesTableLibHost/UefiRuntimeServicesTableLibHost.inf - - OsServiceLib|UefiHostTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf UnitTestAssertLib|CmockaHostUnitTestPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf UnitTestLib|CmockaHostUnitTestPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf @@ -59,43 +44,25 @@ } MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf - MdePkg/Test/UnitTest/Library/PeiServicesLib/TestPeiServicesLib.inf - MdePkg/Test/UnitTest/Library/DxeServicesTableLib/TestDxeServicesTableLib.inf - MdePkg/Test/UnitTest/Library/SmmServicesTableLib/TestSmmServicesTableLib.inf - MdePkg/Test/UnitTest/Library/UefiBootServicesTableLib/TestUefiBootServicesTableLib.inf - MdePkg/Test/UnitTest/Library/MemoryAllocationLib/TestMemoryAllocationLib.inf - MdePkg/Test/UnitTest/Library/UefiRuntimeServicesTableLib/TestUefiRuntimeServicesTableLib.inf - - MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibStatic.inf { - - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - - gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidStrAsc|"StrAsc"|VOID*|12 - gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidStrUni|L"StrUni"|VOID*|28 - gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidBufAll0|{0x0, 0x0, 0x0}|VOID*|5 - gTestCasePkgTokenSpaceGuid.PcdTestPatchableInModuleVoidBufAll1|{0xFF, 0xFF, 0xFF}|VOID*|5 - } - MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibDynamic.inf { - - PcdLib|MdePkg/HostLibrary/BasePcdLibHost/BasePcdLibHost.inf - } - MdePkg/HostLibrary/BaseCacheMaintenanceLibHost/BaseCacheMaintenanceLibHost.inf - MdePkg/HostLibrary/BaseCpuLibHost/BaseCpuLibHost.inf + + #compile all host application components MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf - MdePkg/HostLibrary/BaseTimerLibHost/BaseTimerLibHost.inf MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf - MdePkg/HostLibrary/DxeServicesTableLibHost/DxeServicesTableLibHost.inf - MdePkg/HostLibrary/HobLibHost/HobLibHost.inf MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - MdePkg/HostLibrary/PeimEntryPointHost/PeimEntryPointHost.inf - MdePkg/HostLibrary/PeiServicesTablePointerLibHost/PeiServicesTablePointerLibHost.inf - MdePkg/HostLibrary/SmmMemLibHost/SmmMemLibHost.inf - MdePkg/HostLibrary/SmmServicesTableLibHost/SmmServicesTableLibHost.inf - MdePkg/HostLibrary/UefiBootServicesTableLibHost/UefiBootServicesTableLibHost.inf - MdePkg/HostLibrary/UefiLibHost/UefiLibHost.inf - MdePkg/HostLibrary/UefiRuntimeServicesTableLibHost/UefiRuntimeServicesTableLibHost.inf - -!include UefiHostUnitTestPkg/UefiHostUnitTestBuildOption.dsc \ No newline at end of file + + +[BuildOptions] + MSFT:*_*_IA32_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /Gm /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /DHOST_DEBUG_MESSAGE=1 + MSFT:*_*_X64_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /Gm /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /DHOST_DEBUG_MESSAGE=1 + +[BuildOptions.common.EDKII.HOST_APPLICATION] + MSFT:*_*_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /MAP /OPT:REF /DEBUG /MACHINE:I386 /LTCG Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib + MSFT:*_*_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB:libcmt.lib /IGNORE:4001 /MAP /OPT:REF /DEBUG /MACHINE:x86 Kernel32.lib MSVCRTD.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib + + MSFT:*_*_IA32_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /wd4305 + + MSFT:*_*_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB:libcmt.lib /IGNORE:4001 /MAP /OPT:REF /DEBUG /MACHINE:X64 MSVCRTD.lib Kernel32.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib + MSFT:*_*_X64_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c new file mode 100644 index 00000000000..a6910fe175f --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -0,0 +1,538 @@ +/** +@file +IA32-specific functions for unit-testing INTN and UINTN functions in +SafeIntLib. + + +Copyright (c) 2017, Microsoft Corporation +Copyright (c) 2019, Intel Corporation. All rights reserved.
+ +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +**/ + +#include "TestBaseSafeIntLib.h" + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5bababab; + UINTN Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt32ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0x5bababab; + INTN Result = 0; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Status = SafeUint32ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bababab; + INT32 Result = 0; + + // + // INTN is same as INT32 in IA32, so this is just a cast + // + Status = SafeIntnToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bababab; + UINT32 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeIntnToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0xabababab; + UINT32 Result = 0; + + // + // UINTN is same as UINT32 in IA32, so this is just a cast + // + Status = SafeUintnToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5bababab; + INTN Result = 0; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Status = SafeUintnToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0xabababab; + INT64 Result = 0; + + // + // UINTN is same as UINT32 in IA32, and UINT32 is a subset of + // INT64, so this is just a cast + // + Status = SafeUintnToInt64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5bababab; + INTN Result = 0; + + // + // If Operand is between MIN_INTN and MAX_INTN2 inclusive, then it's a cast + // + Status = SafeInt64ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeInt64ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0xabababab; + UINTN Result = 0; + + // + // If Operand is between 0 and MAX_UINTN inclusive, then it's a cast + // + Status = SafeInt64ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5bababab; + INTN Result = 0; + + // + // If Operand is <= MAX_INTN, then it's a cast + // + Status = SafeUint64ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0xabababab; + UINTN Result = 0; + + // + // If Operand is <= MAX_UINTN, then it's a cast + // + Status = SafeUint64ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Augend = 0x3a3a3a3a; + UINTN Addend = 0x3a3a3a3a; + UINTN Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINTN, then it's addition + // + Status = SafeUintnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74747474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabababab; + Addend = 0xbcbcbcbc; + Status = SafeUintnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Augend = 0x3a3a3a3a; + INTN Addend = 0x3a3a3a3a; + INTN Result = 0; + + // + // If the result of addition doesn't overflow MAX_INTN + // and doesn't underflow MIN_INTN, then it's addition + // + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74747474, Result); + + Augend = (-976894522); + Addend = (-976894522); + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-1953789044), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a; + Addend = 0x5a5a5a5a; + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-1515870810); + Addend = (-1515870810); + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Minuend = 0x5a5a5a5a; + UINTN Subtrahend = 0x3b3b3b3b; + UINTN Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUintnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x6d6d6d6d; + Status = SafeUintnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Minuend = 0x5a5a5a5a; + INTN Subtrahend = 0x3a3a3a3a; + INTN Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INTN or + // underflow MIN_INTN, then it's subtraction + // + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x20202020, Result); + + Minuend = 0x3a3a3a3a; + Subtrahend = 0x5a5a5a5a; + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-538976288), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-2054847098); + Subtrahend = 2054847098; + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (2054847098); + Subtrahend = (-2054847098); + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Multiplicand = 0xa122a; + UINTN Multiplier = 0xd23; + UINTN Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed + // + Status = SafeUintnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x844c9dbe, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0xa122a; + Multiplier = 0xed23; + Status = SafeUintnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Multiplicand = 0x123456; + INTN Multiplier = 0x678; + INTN Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INTN and doesn't + // underflow MIN_UINTN, it will succeed + // + Status = SafeIntnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x75c28c50, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456; + Multiplier = 0xabc; + Status = SafeIntnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} \ No newline at end of file diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c new file mode 100644 index 00000000000..8a7d40fd926 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -0,0 +1,2911 @@ +/** +@file +UEFI OS based application for unit testing the SafeIntLib. + + +Copyright (c) 2017, Microsoft Corporation +Copyright (c) 2018, Intel Corporation. All rights reserved.
+ +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +**/ + +#include "TestBaseSafeIntLib.h" + +#define UNIT_TEST_NAME L"Int Safe Lib Unit Test Application" +#define UNIT_TEST_VERSION L"0.1" + +// +// Conversion function tests: +// +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Operand = 0x5b; + UINT8 Result = 0; + + // + // Positive UINT8 should result in just a cast + // + Status = SafeInt8ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Operand = 0x5b; + UINT16 Result = 0; + + // + // Positive UINT8 should result in just a cast + // + Status = SafeInt8ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8ToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Operand = 0x5b; + UINT32 Result = 0; + + // + // Positive UINT8 should result in just a cast + // + Status = SafeInt8ToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Operand = 0x5b; + UINTN Result = 0; + + // + // Positive UINT8 should result in just a cast + // + Status = SafeInt8ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8ToUint64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Operand = 0x5b; + UINT64 Result = 0; + + // + // Positive UINT8 should result in just a cast + // + Status = SafeInt8ToUint64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Negative number should result in an error status + // + Operand = (-56); + Status = SafeInt8ToUint64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint8ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT8 Operand = 0x5b; + INT8 Result = 0; + + // + // Operand <= 0x7F (MAX_INT8) should result in a cast + // + Status = SafeUint8ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Operand larger than 0x7f should result in an error status + // + Operand = 0xaf; + Status = SafeUint8ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint8ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT8 Operand = 0x5b; + CHAR8 Result = 0; + + // + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + // + + // + // Operand <= 0x7F (MAX_INT8) should result in a cast + // + Status = SafeUint8ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Operand larger than 0x7f should result in an error status + // + Operand = 0xaf; + Status = SafeUint8ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt16ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-35); + Status = SafeInt16ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-35), Result); + + // + // Otherwise should result in an error status + // + Operand = 0x1234; + Status = SafeInt16ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b; + CHAR8 Result = 0; + + // + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + // + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-35); + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-35), Result); + + // + // Otherwise should result in an error status + // + Operand = 0x1234; + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b; + UINT8 Result = 0; + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt16ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = 0x1234; + Status = SafeInt16ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-17835); + Status = SafeInt16ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b5b; + UINT16 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt16ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b5b; + UINT32 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt16ToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b5b; + UINTN Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt16ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16ToUint64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Operand = 0x5b5b; + UINT64 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt16ToUint64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17835); + Status = SafeInt16ToUint64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is <= MAX_INT8, it's a cast + // + Status = SafeUint16ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, it's a cast + // + Status = SafeUint16ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is <= MAX_UINT8 (0xff), it's a cast + // + Status = SafeUint16ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5b5b); + Status = SafeUint16ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16ToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Operand = 0x5b5b; + INT16 Result = 0; + + // + // If Operand is <= MAX_INT16 (0x7fff), it's a cast + // + Status = SafeUint16ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUint16ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt32ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-57); + Status = SafeInt32ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-57), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeInt32ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-57); + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-57), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5b; + UINT8 Result = 0; + + // + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt32ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (-57); + Status = SafeInt32ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeInt32ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5b5b; + INT16 Result = 0; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Status = SafeInt32ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b5b, Result); + + Operand = (-17857); + Status = SafeInt32ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-17857), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeInt32ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Status = SafeInt32ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-17857); + Status = SafeInt32ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (0x5bababab); + Status = SafeInt32ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeInt32ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5bababab; + UINT32 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt32ToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUint64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5bababab; + UINT64 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt32ToUint64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUint64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUint32ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeUint32ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUint32ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeUint32ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Status = SafeUint32ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0x5bab; + INT16 Result = 0; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Status = SafeUint32ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Status = SafeUint32ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0x5bababab; + INT32 Result = 0; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Status = SafeUint32ToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUint32ToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeIntnToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-53); + Status = SafeIntnToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-53), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-53); + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-53), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast + // + Status = SafeIntnToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bab; + INT16 Result = 0; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Status = SafeIntnToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bab, Result); + + Operand = (-23467); + Status = SafeIntnToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-23467), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Status = SafeIntnToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5bababab); + Status = SafeIntnToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-1537977259); + Status = SafeIntnToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bababab; + UINTN Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeIntnToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bababab; + UINT64 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeIntnToUint64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeIntnToUint64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUintnToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUintnToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Status = SafeUintnToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5bab; + INT16 Result = 0; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Status = SafeUintnToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabab); + Status = SafeUintnToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Status = SafeUintnToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5bababab; + INT32 Result = 0; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Status = SafeUintnToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xabababab); + Status = SafeUintnToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt64ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-37); + Status = SafeInt64ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-37), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + Operand = (-37); + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-37), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast + // + Status = SafeInt64ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5bab; + INT16 Result = 0; + + // + // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast + // + Status = SafeInt64ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bab, Result); + + Operand = (-23467); + Status = SafeInt64ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-23467), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast + // + Status = SafeInt64ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5bababab; + INT32 Result = 0; + + // + // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast + // + Status = SafeInt64ToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeInt64ToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0xabababab; + UINT32 Result = 0; + + // + // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast + // + Status = SafeInt64ToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeInt64ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeInt64ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUint64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5babababefefefef; + UINT64 Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt64ToUint64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (-6605562033422200815); + Status = SafeInt64ToUint64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToInt8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5b; + INT8 Result = 0; + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUint64ToInt8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToChar8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5b; + CHAR8 Result = 0; + + // CHAR8 is typedefed as char, which by default is signed, thus + // CHAR8 is same as INT8, so same tests as above: + + // + // If Operand is <= MAX_INT8, then it's a cast + // + Status = SafeUint64ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5b, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUint8( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0xab; + UINT8 Result = 0; + + // + // If Operand is <= MAX_UINT8, then it's a cast + // + Status = SafeUint64ToUint8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToInt16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5bab; + INT16 Result = 0; + + // + // If Operand is <= MAX_INT16, then it's a cast + // + Status = SafeUint64ToInt16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUint16( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0xabab; + UINT16 Result = 0; + + // + // If Operand is <= MAX_UINT16, then it's a cast + // + Status = SafeUint64ToUint16(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint16(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5bababab; + INT32 Result = 0; + + // + // If Operand is <= MAX_INT32, then it's a cast + // + Status = SafeUint64ToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0xabababab; + UINT32 Result = 0; + + // + // If Operand is <= MAX_UINT32, then it's a cast + // + Status = SafeUint64ToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToInt64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5babababefefefef; + INT64 Result = 0; + + // + // If Operand is <= MAX_INT64, then it's a cast + // + Status = SafeUint64ToInt64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToInt64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +// +// Addition function tests: +// +UNIT_TEST_STATUS +EFIAPI +TestSafeUint8Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT8 Augend = 0x3a; + UINT8 Addend = 0x3a; + UINT8 Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINT8, then it's addition + // + Status = SafeUint8Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xab; + Addend = 0xbc; + Status = SafeUint8Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Augend = 0x3a3a; + UINT16 Addend = 0x3a3a; + UINT16 Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINT16, then it's addition + // + Status = SafeUint16Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabab; + Addend = 0xbcbc; + Status = SafeUint16Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Augend = 0x3a3a3a3a; + UINT32 Addend = 0x3a3a3a3a; + UINT32 Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINT32, then it's addition + // + Status = SafeUint32Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74747474, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xabababab; + Addend = 0xbcbcbcbc; + Status = SafeUint32Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Augend = 0x3a3a3a3a12121212; + UINT64 Addend = 0x3a3a3a3a12121212; + UINT64 Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINT64, then it's addition + // + Status = SafeUint64Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474747424242424, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xababababefefefef; + Addend = 0xbcbcbcbcdededede; + Status = SafeUint64Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Augend = 0x3a; + INT8 Addend = 0x3a; + INT8 Result = 0; + + // + // If the result of addition doesn't overflow MAX_INT8 + // and doesn't underflow MIN_INT8, then it's addition + // + Status = SafeInt8Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74, Result); + + Augend = (-58); + Addend = (-58); + Status = SafeInt8Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-116), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a; + Addend = 0x5a; + Status = SafeInt8Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-90); + Addend = (-90); + Status = SafeInt8Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; + +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Augend = 0x3a3a; + INT16 Addend = 0x3a3a; + INT16 Result = 0; + + // + // If the result of addition doesn't overflow MAX_INT16 + // and doesn't underflow MIN_INT16, then it's addition + // + Status = SafeInt16Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474, Result); + + Augend = (-14906); + Addend = (-14906); + Status = SafeInt16Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-29812), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a; + Addend = 0x5a5a; + Status = SafeInt16Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-23130); + Addend = (-23130); + Status = SafeInt16Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Augend = 0x3a3a3a3a; + INT32 Addend = 0x3a3a3a3a; + INT32 Result = 0; + + // + // If the result of addition doesn't overflow MAX_INT32 + // and doesn't underflow MIN_INT32, then it's addition + // + Status = SafeInt32Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x74747474, Result); + + Augend = (-976894522); + Addend = (-976894522); + Status = SafeInt32Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-1953789044), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a; + Addend = 0x5a5a5a5a; + Status = SafeInt32Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-1515870810); + Addend = (-1515870810); + Status = SafeInt32Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64Add( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Augend = 0x3a3a3a3a3a3a3a3a; + INT64 Addend = 0x3a3a3a3a3a3a3a3a; + INT64 Result = 0; + + // + // If the result of addition doesn't overflow MAX_INT64 + // and doesn't underflow MIN_INT64, then it's addition + // + Status = SafeInt64Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474747474747474, Result); + + Augend = (-4195730024608447034); + Addend = (-4195730024608447034); + Status = SafeInt64Add(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-8391460049216894068), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a5a5a5a5a; + Addend = 0x5a5a5a5a5a5a5a5a; + Status = SafeInt64Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-6510615555426900570); + Addend = (-6510615555426900570); + Status = SafeInt64Add(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +// +// Subtraction function tests: +// +UNIT_TEST_STATUS +EFIAPI +TestSafeUint8Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT8 Minuend = 0x5a; + UINT8 Subtrahend = 0x3b; + UINT8 Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUint8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a; + Subtrahend = 0x6d; + Status = SafeUint8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Minuend = 0x5a5a; + UINT16 Subtrahend = 0x3b3b; + UINT16 Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUint16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a; + Subtrahend = 0x6d6d; + Status = SafeUint16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Minuend = 0x5a5a5a5a; + UINT32 Subtrahend = 0x3b3b3b3b; + UINT32 Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUint32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x6d6d6d6d; + Status = SafeUint32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Minuend = 0x5a5a5a5a5a5a5a5a; + UINT64 Subtrahend = 0x3b3b3b3b3b3b3b3b; + UINT64 Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUint64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f1f1f1f1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x6d6d6d6d6d6d6d6d; + Status = SafeUint64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Minuend = 0x5a; + INT8 Subtrahend = 0x3a; + INT8 Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INT8 or + // underflow MIN_INT8, then it's subtraction + // + Status = SafeInt8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x20, Result); + + Minuend = 58; + Subtrahend = 78; + Status = SafeInt8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-20), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-80); + Subtrahend = 80; + Status = SafeInt8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (80); + Subtrahend = (-80); + Status = SafeInt8Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Minuend = 0x5a5a; + INT16 Subtrahend = 0x3a3a; + INT16 Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INT16 or + // underflow MIN_INT16, then it's subtraction + // + Status = SafeInt16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x2020, Result); + + Minuend = 0x3a3a; + Subtrahend = 0x5a5a; + Status = SafeInt16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-8224), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-31354); + Subtrahend = 31354; + Status = SafeInt16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (31354); + Subtrahend = (-31354); + Status = SafeInt16Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Minuend = 0x5a5a5a5a; + INT32 Subtrahend = 0x3a3a3a3a; + INT32 Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INT32 or + // underflow MIN_INT32, then it's subtraction + // + Status = SafeInt32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x20202020, Result); + + Minuend = 0x3a3a3a3a; + Subtrahend = 0x5a5a5a5a; + Status = SafeInt32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-538976288), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-2054847098); + Subtrahend = 2054847098; + Status = SafeInt32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (2054847098); + Subtrahend = (-2054847098); + Status = SafeInt32Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64Sub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Minuend = 0x5a5a5a5a5a5a5a5a; + INT64 Subtrahend = 0x3a3a3a3a3a3a3a3a; + INT64 Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INT64 or + // underflow MIN_INT64, then it's subtraction + // + Status = SafeInt64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x2020202020202020, Result); + + Minuend = 0x3a3a3a3a3a3a3a3a; + Subtrahend = 0x5a5a5a5a5a5a5a5a; + Status = SafeInt64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-2314885530818453536), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-8825501086245354106); + Subtrahend = 8825501086245354106; + Status = SafeInt64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (8825501086245354106); + Subtrahend = (-8825501086245354106); + Status = SafeInt64Sub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +// +// Multiplication function tests: +// +UNIT_TEST_STATUS +EFIAPI +TestSafeUint8Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT8 Multiplicand = 0x12; + UINT8 Multiplier = 0xa; + UINT8 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINT8, it will succeed + // + Status = SafeUint8Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xb4, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x12; + Multiplier = 0x23; + Status = SafeUint8Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint16Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT16 Multiplicand = 0x212; + UINT16 Multiplier = 0x7a; + UINT16 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINT16, it will succeed + // + Status = SafeUint16Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xfc94, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x1234; + Multiplier = 0x213; + Status = SafeUint16Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Multiplicand = 0xa122a; + UINT32 Multiplier = 0xd23; + UINT32 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINT32, it will succeed + // + Status = SafeUint32Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x844c9dbe, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0xa122a; + Multiplier = 0xed23; + Status = SafeUint32Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Multiplicand = 0x123456789a; + UINT64 Multiplier = 0x1234567; + UINT64 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINT64, it will succeed + // + Status = SafeUint64Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x14b66db9745a07f6, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789a; + Multiplier = 0x12345678; + Status = SafeUint64Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt8Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT8 Multiplicand = 0x12; + INT8 Multiplier = 0x7; + INT8 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INT8 and doesn't + // underflow MIN_UINT8, it will succeed + // + Status = SafeInt8Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7e, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x12; + Multiplier = 0xa; + Status = SafeInt8Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt16Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT16 Multiplicand = 0x123; + INT16 Multiplier = 0x67; + INT16 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INT16 and doesn't + // underflow MIN_UINT16, it will succeed + // + Status = SafeInt16Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7515, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123; + Multiplier = 0xab; + Status = SafeInt16Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Multiplicand = 0x123456; + INT32 Multiplier = 0x678; + INT32 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INT32 and doesn't + // underflow MIN_UINT32, it will succeed + // + Status = SafeInt32Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x75c28c50, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456; + Multiplier = 0xabc; + Status = SafeInt32Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64Mult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Multiplicand = 0x123456789; + INT64 Multiplier = 0x6789abcd; + INT64 Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INT64 and doesn't + // underflow MIN_UINT64, it will succeed + // + Status = SafeInt64Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x75cd9045220d6bb5, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789; + Multiplier = 0xa789abcd; + Status = SafeInt64Mult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +/** + + Main fuction sets up the unit test environment + +**/ +EFI_STATUS +EFIAPI +UefiTestMain ( + VOID + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Fw; + UNIT_TEST_SUITE *ConversionTestSuite; + UNIT_TEST_SUITE *AdditionSubtractionTestSuite; + UNIT_TEST_SUITE *MultiplicationTestSuite; + CHAR16 ShortName[100]; + + Fw = NULL; + ConversionTestSuite = NULL; + AdditionSubtractionTestSuite = NULL; + MultiplicationTestSuite = NULL; + + AsciiStrToUnicodeStrS (gEfiCallerBaseName, ShortName, sizeof(ShortName)/sizeof(ShortName[0])); + DEBUG((DEBUG_INFO, "%s v%s\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Fw, UNIT_TEST_NAME, ShortName, UNIT_TEST_VERSION); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + /// + // Test the conversion functions + // + Status = CreateUnitTestSuite (&ConversionTestSuite, Fw, L"Int Safe Conversions Test Suite", L"Common.SafeInt.Convert", NULL, NULL); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Conversions Test Suite\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint8", L"Common.SafeInt.Convert.TestSafeInt8ToUint8", TestSafeInt8ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint16", L"Common.SafeInt.Convert.TestSafeInt8ToUint16", TestSafeInt8ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint32", L"Common.SafeInt.Convert.TestSafeInt8ToUint32", TestSafeInt8ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUintn", L"Common.SafeInt.Convert.TestSafeInt8ToUintn", TestSafeInt8ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint64", L"Common.SafeInt.Convert.TestSafeInt8ToUint64", TestSafeInt8ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint8ToInt8", L"Common.SafeInt.Convert.TestSafeUint8ToInt8", TestSafeUint8ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint8ToChar8", L"Common.SafeInt.Convert.TestSafeUint8ToChar8", TestSafeUint8ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToInt8", L"Common.SafeInt.Convert.TestSafeInt16ToInt8", TestSafeInt16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToChar8", L"Common.SafeInt.Convert.TestSafeInt16ToChar8", TestSafeInt16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint8", L"Common.SafeInt.Convert.TestSafeInt16ToUint8", TestSafeInt16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint16", L"Common.SafeInt.Convert.TestSafeInt16ToUint16", TestSafeInt16ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint32", L"Common.SafeInt.Convert.TestSafeInt16ToUint32", TestSafeInt16ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUintn", L"Common.SafeInt.Convert.TestSafeInt16ToUintn", TestSafeInt16ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint64", L"Common.SafeInt.Convert.TestSafeInt16ToUint64", TestSafeInt16ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint16ToInt8", L"Common.SafeInt.Convert.TestSafeUint16ToInt8", TestSafeUint16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint16ToChar8", L"Common.SafeInt.Convert.TestSafeUint16ToChar8", TestSafeUint16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint16ToUint8", L"Common.SafeInt.Convert.TestSafeUint16ToUint8", TestSafeUint16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint16ToInt16", L"Common.SafeInt.Convert.TestSafeUint16ToInt16", TestSafeUint16ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToInt8", L"Common.SafeInt.Convert.TestSafeInt32ToInt8", TestSafeInt32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToChar8", L"Common.SafeInt.Convert.TestSafeInt32ToChar8", TestSafeInt32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint8", L"Common.SafeInt.Convert.TestSafeInt32ToUint8", TestSafeInt32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToInt16", L"Common.SafeInt.Convert.TestSafeInt32ToInt16", TestSafeInt32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint16", L"Common.SafeInt.Convert.TestSafeInt32ToUint16", TestSafeInt32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint32", L"Common.SafeInt.Convert.TestSafeInt32ToUint32", TestSafeInt32ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUintn", L"Common.SafeInt.Convert.TestSafeInt32ToUintn", TestSafeInt32ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint64", L"Common.SafeInt.Convert.TestSafeInt32ToUint64", TestSafeInt32ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt8", L"Common.SafeInt.Convert.TestSafeUint32ToInt8", TestSafeUint32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToChar8", L"Common.SafeInt.Convert.TestSafeUint32ToChar8", TestSafeUint32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToUint8", L"Common.SafeInt.Convert.TestSafeUint32ToUint8", TestSafeUint32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt16", L"Common.SafeInt.Convert.TestSafeUint32ToInt16", TestSafeUint32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToUint16", L"Common.SafeInt.Convert.TestSafeUint32ToUint16", TestSafeUint32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt32", L"Common.SafeInt.Convert.TestSafeUint32ToInt32", TestSafeUint32ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint32ToIntn", L"Common.SafeInt.Convert.TestSafeUint32ToIntn", TestSafeUint32ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt8", L"Common.SafeInt.Convert.TestSafeIntnToInt8", TestSafeIntnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToChar8", L"Common.SafeInt.Convert.TestSafeIntnToChar8", TestSafeIntnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint8", L"Common.SafeInt.Convert.TestSafeIntnToUint8", TestSafeIntnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt16", L"Common.SafeInt.Convert.TestSafeIntnToInt16", TestSafeIntnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint16", L"Common.SafeInt.Convert.TestSafeIntnToUint16", TestSafeIntnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt32", L"Common.SafeInt.Convert.TestSafeIntnToInt32", TestSafeIntnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint32", L"Common.SafeInt.Convert.TestSafeIntnToUint32", TestSafeIntnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToUintn", L"Common.SafeInt.Convert.TestSafeIntnToUintn", TestSafeIntnToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint64", L"Common.SafeInt.Convert.TestSafeIntnToUint64", TestSafeIntnToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt8", L"Common.SafeInt.Convert.TestSafeUintnToInt8", TestSafeUintnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToChar8", L"Common.SafeInt.Convert.TestSafeUintnToChar8", TestSafeUintnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint8", L"Common.SafeInt.Convert.TestSafeUintnToUint8", TestSafeUintnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt16", L"Common.SafeInt.Convert.TestSafeUintnToInt16", TestSafeUintnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint16", L"Common.SafeInt.Convert.TestSafeUintnToUint16", TestSafeUintnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt32", L"Common.SafeInt.Convert.TestSafeUintnToInt32", TestSafeUintnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint32", L"Common.SafeInt.Convert.TestSafeUintnToUint32", TestSafeUintnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToIntn", L"Common.SafeInt.Convert.TestSafeUintnToIntn", TestSafeUintnToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt64", L"Common.SafeInt.Convert.TestSafeUintnToInt64", TestSafeUintnToInt64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt8", L"Common.SafeInt.Convert.TestSafeInt64ToInt8", TestSafeInt64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToChar8", L"Common.SafeInt.Convert.TestSafeInt64ToChar8", TestSafeInt64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint8", L"Common.SafeInt.Convert.TestSafeInt64ToUint8", TestSafeInt64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt16", L"Common.SafeInt.Convert.TestSafeInt64ToInt16", TestSafeInt64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint16", L"Common.SafeInt.Convert.TestSafeInt64ToUint16", TestSafeInt64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt32", L"Common.SafeInt.Convert.TestSafeInt64ToInt32", TestSafeInt64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint32", L"Common.SafeInt.Convert.TestSafeInt64ToUint32", TestSafeInt64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToIntn", L"Common.SafeInt.Convert.TestSafeInt64ToIntn", TestSafeInt64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUintn", L"Common.SafeInt.Convert.TestSafeInt64ToUintn", TestSafeInt64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint64", L"Common.SafeInt.Convert.TestSafeInt64ToUint64", TestSafeInt64ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt8", L"Common.SafeInt.Convert.TestSafeUint64ToInt8", TestSafeUint64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToChar8", L"Common.SafeInt.Convert.TestSafeUint64ToChar8", TestSafeUint64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint8", L"Common.SafeInt.Convert.TestSafeUint64ToUint8", TestSafeUint64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt16", L"Common.SafeInt.Convert.TestSafeUint64ToInt16", TestSafeUint64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint16", L"Common.SafeInt.Convert.TestSafeUint64ToUint16", TestSafeUint64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt32", L"Common.SafeInt.Convert.TestSafeUint64ToInt32", TestSafeUint64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint32", L"Common.SafeInt.Convert.TestSafeUint64ToUint32", TestSafeUint64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToIntn", L"Common.SafeInt.Convert.TestSafeUint64ToIntn", TestSafeUint64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUintn", L"Common.SafeInt.Convert.TestSafeUint64ToUintn", TestSafeUint64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt64", L"Common.SafeInt.Convert.TestSafeUint64ToInt64", TestSafeUint64ToInt64, NULL, NULL, NULL); + + // + // Test the addition and subtraction functions + // + Status = CreateUnitTestSuite(&AdditionSubtractionTestSuite, Fw, L"Int Safe Add/Subtract Test Suite", L"Common.SafeInt.AddSubtract", NULL, NULL); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Add/Subtract Test Suite\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint8Add", L"Common.SafeInt.AddSubtract.TestSafeUint8Add", TestSafeUint8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint16Add", L"Common.SafeInt.AddSubtract.TestSafeUint16Add", TestSafeUint16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint32Add", L"Common.SafeInt.AddSubtract.TestSafeUint32Add", TestSafeUint32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUintnAdd", L"Common.SafeInt.AddSubtract.TestSafeUintnAdd", TestSafeUintnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint64Add", L"Common.SafeInt.AddSubtract.TestSafeUint64Add", TestSafeUint64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt8Add", L"Common.SafeInt.AddSubtract.TestSafeInt8Add", TestSafeInt8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt16Add", L"Common.SafeInt.AddSubtract.TestSafeInt16Add", TestSafeInt16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt32Add", L"Common.SafeInt.AddSubtract.TestSafeInt32Add", TestSafeInt32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeIntnAdd", L"Common.SafeInt.AddSubtract.TestSafeIntnAdd", TestSafeIntnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt64Add", L"Common.SafeInt.AddSubtract.TestSafeInt64Add", TestSafeInt64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint8Sub", L"Common.SafeInt.AddSubtract.TestSafeUint8Sub", TestSafeUint8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint16Sub", L"Common.SafeInt.AddSubtract.TestSafeUint16Sub", TestSafeUint16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint32Sub", L"Common.SafeInt.AddSubtract.TestSafeUint32Sub", TestSafeUint32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUintnSub", L"Common.SafeInt.AddSubtract.TestSafeUintnSub", TestSafeUintnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint64Sub", L"Common.SafeInt.AddSubtract.TestSafeUint64Sub", TestSafeUint64Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt8Sub", L"Common.SafeInt.AddSubtract.TestSafeInt8Sub", TestSafeInt8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt16Sub", L"Common.SafeInt.AddSubtract.TestSafeInt16Sub", TestSafeInt16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt32Sub", L"Common.SafeInt.AddSubtract.TestSafeInt32Sub", TestSafeInt32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeIntnSub", L"Common.SafeInt.AddSubtract.TestSafeIntnSub", TestSafeIntnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt64Sub", L"Common.SafeInt.AddSubtract.TestSafeInt64Sub", TestSafeInt64Sub, NULL, NULL, NULL); + + // + // Test the multiplication functions + // + Status = CreateUnitTestSuite(&MultiplicationTestSuite, Fw, L"Int Safe Multiply Test Suite", L"Common.SafeInt.Multiply", NULL, NULL); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Multiply Test Suite\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase(MultiplicationTestSuite, L"Test SafeUint8Mult", L"Common.SafeInt.Multiply.TestSafeUint8Mult", TestSafeUint8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeUint16Mult", L"Common.SafeInt.Multiply.TestSafeUint16Mult", TestSafeUint16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeUint32Mult", L"Common.SafeInt.Multiply.TestSafeUint32Mult", TestSafeUint32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeUintnMult", L"Common.SafeInt.Multiply.TestSafeUintnMult", TestSafeUintnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeUint64Mult", L"Common.SafeInt.Multiply.TestSafeUint64Mult", TestSafeUint64Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeInt8Mult", L"Common.SafeInt.Multiply.TestSafeInt8Mult", TestSafeInt8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeInt16Mult", L"Common.SafeInt.Multiply.TestSafeInt16Mult", TestSafeInt16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeInt32Mult", L"Common.SafeInt.Multiply.TestSafeInt32Mult", TestSafeInt32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeIntnMult", L"Common.SafeInt.Multiply.TestSafeIntnMult", TestSafeIntnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, L"Test SafeInt64Mult", L"Common.SafeInt.Multiply.TestSafeInt64Mult", TestSafeInt64Mult, NULL, NULL, NULL); + + // + // Execute the tests. + // + Status = RunAllTestSuites(Fw); + +EXIT: + if (Fw != NULL) { + FreeUnitTestFramework(Fw); + } + + return Status; +} + +int main (void) +{ + return UefiTestMain (); +} + diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h new file mode 100644 index 00000000000..c1d8ee8f7ca --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -0,0 +1,162 @@ +/** +@file +UEFI OS based application for unit testing the SafeIntLib. + + +Copyright (c) 2017, Microsoft Corporation +Copyright (c) 2018, Intel Corporation. All rights reserved.
+ +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +**/ + +#ifndef _TEST_BASE_SAFE_INT_LIB_H_ +#define _TEST_BASE_SAFE_INT_LIB_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ); + +#endif \ No newline at end of file diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf new file mode 100644 index 00000000000..631bdbce06e --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf @@ -0,0 +1,59 @@ +## @file +# Uefi OS based Application that Unit Tests the SafeIntLib +# +# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLib + FILE_GUID = 95487689-9E30-41AD-B773-3650C94BCBE2 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + +[Sources.Ia32] + IA32/SafeIntLibUintnIntnUnitTests.c + +[Sources.X64] + X64/SafeIntLibUintnIntnUnitTests.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + +[LibraryClasses] + BaseLib + DebugLib + SafeIntLib + UnitTestLib + UnitTestAssertLib diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c new file mode 100644 index 00000000000..372139f3d7e --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -0,0 +1,542 @@ +/** +@file +x64-specific functions for unit-testing INTN and UINTN functions in +SafeIntLib. + + +Copyright (c) 2017, Microsoft Corporation +Copyright (c) 2019, Intel Corporation. All rights reserved.
+ +All rights reserved. +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, +this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, +this list of conditions and the following disclaimer in the documentation +and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +**/ + +#include "TestBaseSafeIntLib.h" + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt32ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT32 Operand = 0x5bababab; + UINTN Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt32ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (-1537977259); + Status = SafeInt32ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint32ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT32 Operand = 0xabababab; + INTN Result = 0; + + // + // For x64, INTN is same as INT64 which is a superset of INT32 + // This is just a cast then, and it'll never fail + // + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeUint32ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToInt32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0x5bababab; + INT32 Result = 0; + + // + // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast + // + Status = SafeIntnToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5bababab, Result); + + Operand = (-1537977259); + Status = SafeIntnToInt32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-1537977259), Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeIntnToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeIntnToInt32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Operand = 0xabababab; + UINT32 Result = 0; + + // + // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast + // + Status = SafeIntnToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0x5babababefefefef); + Status = SafeIntnToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Operand = (-6605562033422200815); + Status = SafeIntnToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToUint32( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0xabababab; + UINT32 Result = 0; + + // + // If Operand is <= MAX_UINT32, then it's a cast + // + Status = SafeUintnToUint32(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xabababab, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToUint32(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5babababefefefef; + INTN Result = 0; + + // + // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast + // + Status = SafeUintnToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnToInt64( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Operand = 0x5babababefefefef; + INT64 Result = 0; + + // + // If Operand is <= MAX_INT64, then it's a cast + // + Status = SafeUintnToInt64(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUintnToInt64(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5babababefefefef; + INTN Result = 0; + + // + // INTN is same as INT64 in x64, so this is just a cast + // + Status = SafeInt64ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeInt64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INT64 Operand = 0x5babababefefefef; + UINTN Result = 0; + + // + // If Operand is non-negative, then it's a cast + // + Status = SafeInt64ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (-6605562033422200815); + Status = SafeInt64ToUintn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToIntn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0x5babababefefefef; + INTN Result = 0; + + // + // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast + // + Status = SafeUint64ToIntn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x5babababefefefef, Result); + + // + // Otherwise should result in an error status + // + Operand = (0xababababefefefef); + Status = SafeUint64ToIntn(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUint64ToUintn( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINT64 Operand = 0xababababefefefef; + UINTN Result = 0; + + // + // UINTN is same as UINT64 in x64, so this is just a cast + // + Status = SafeUint64ToUintn(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0xababababefefefef, Result); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Augend = 0x3a3a3a3a12121212; + UINTN Addend = 0x3a3a3a3a12121212; + UINTN Result = 0; + + // + // If the result of addition doesn't overflow MAX_UINTN, then it's addition + // + Status = SafeUintnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474747424242424, Result); + + // + // Otherwise should result in an error status + // + Augend = 0xababababefefefef; + Addend = 0xbcbcbcbcdededede; + Status = SafeUintnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnAdd( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Augend = 0x3a3a3a3a3a3a3a3a; + INTN Addend = 0x3a3a3a3a3a3a3a3a; + INTN Result = 0; + + // + // If the result of addition doesn't overflow MAX_INTN + // and doesn't underflow MIN_INTN, then it's addition + // + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x7474747474747474, Result); + + Augend = (-4195730024608447034); + Addend = (-4195730024608447034); + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-8391460049216894068), Result); + + // + // Otherwise should result in an error status + // + Augend = 0x5a5a5a5a5a5a5a5a; + Addend = 0x5a5a5a5a5a5a5a5a; + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Augend = (-6510615555426900570); + Addend = (-6510615555426900570); + Status = SafeIntnAdd(Augend, Addend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Minuend = 0x5a5a5a5a5a5a5a5a; + UINTN Subtrahend = 0x3b3b3b3b3b3b3b3b; + UINTN Result = 0; + + // + // If Minuend >= Subtrahend, then it's subtraction + // + Status = SafeUintnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x1f1f1f1f1f1f1f1f, Result); + + // + // Otherwise should result in an error status + // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x6d6d6d6d6d6d6d6d; + Status = SafeUintnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnSub( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Minuend = 0x5a5a5a5a5a5a5a5a; + INTN Subtrahend = 0x3a3a3a3a3a3a3a3a; + INTN Result = 0; + + // + // If the result of subtractions doesn't overflow MAX_INTN or + // underflow MIN_INTN, then it's subtraction + // + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x2020202020202020, Result); + + Minuend = 0x3a3a3a3a3a3a3a3a; + Subtrahend = 0x5a5a5a5a5a5a5a5a; + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL((-2314885530818453536), Result); + + // + // Otherwise should result in an error status + // + Minuend = (-8825501086245354106); + Subtrahend = 8825501086245354106; + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + Minuend = (8825501086245354106); + Subtrahend = (-8825501086245354106); + Status = SafeIntnSub(Minuend, Subtrahend, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeUintnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + UINTN Multiplicand = 0x123456789a; + UINTN Multiplier = 0x1234567; + UINTN Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed + // + Status = SafeUintnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x14b66db9745a07f6, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789a; + Multiplier = 0x12345678; + Status = SafeUintnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} + +UNIT_TEST_STATUS +EFIAPI +TestSafeIntnMult( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + EFI_STATUS Status; + INTN Multiplicand = 0x123456789; + INTN Multiplier = 0x6789abcd; + INTN Result = 0; + + // + // If the result of multiplication doesn't overflow MAX_INTN and doesn't + // underflow MIN_UINTN, it will succeed + // + Status = SafeIntnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(0x75cd9045220d6bb5, Result); + + // + // Otherwise should result in an error status + // + Multiplicand = 0x123456789; + Multiplier = 0xa789abcd; + Status = SafeIntnMult(Multiplicand, Multiplier, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + + return UNIT_TEST_PASSED; +} \ No newline at end of file From 6206e5cbfe2eb9808c87149a6cdc46188778e72c Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 13 Nov 2019 15:05:08 -0800 Subject: [PATCH 100/384] Set up the pipeline to run on server builds. --- .azurepipelines/templates/pr-gate-steps.yml | 7 +++++++ .pytool/CISettings.py | 6 ++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml index a969661dea1..e278cc3b183 100644 --- a/.azurepipelines/templates/pr-gate-steps.yml +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -48,6 +48,13 @@ steps: - template: spell-check-prereq-steps.yml # Build repo +- task: CmdLine@1 + displayName: CI Setup ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} + inputs: + filename: stuart_ci_setup + arguments: -c .pytool/CISettings.py -p $(pkgs_to_build) -t ${{ parameters.build_targets}} -a ${{ parameters.build_archs}} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} + condition: and(gt(variables.pkg_count, 0), succeeded()) + - task: CmdLine@1 displayName: Setup ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} inputs: diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index e52620c0797..d9b8aa97d33 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -118,11 +118,13 @@ def SetTargets(self, list_of_requested_target): def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' - # scopes = ("cibuild","edk2-build","host-based-test") - scopes = ("host-based-test", "host-test-win", "edk2-build") + scopes = ("cibuild","edk2-build","host-based-test") self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") + if GetHostInfo().os.upper() == "WINDOWS": + scopes += ('host-test-win',) + if GetHostInfo().os.upper() == "LINUX" and self.ActualToolChainTag.upper().startswith("GCC"): if "AARCH64" in self.ActualArchitectures: scopes += ("gcc_aarch64_linux",) From c9af866cdd6214d65c1539e7008f6a7255316c80 Mon Sep 17 00:00:00 2001 From: Jian J Wang Date: Tue, 12 Nov 2019 16:45:48 +0800 Subject: [PATCH 101/384] MdePkg: add null version of RngLib Ref: https://bugzilla.tianocore.org/show_bug.cgi?id=1871 This is null version of RngLib which should be used with modules that inherit an (indirect) dependency on the RngLib class, but never actually call RngLib APIs for consuming randomness. To be more specific, if following components or functionalities are used in a platform, the BaseRngLibNull should *not* be used. Instead, a non-Null version of RngLib must be used (like BaseRngLib for IA32/X64, or future DxeRngLibRngProtocol for all ARCHs). - HddPasswordDxe.inf - AES, TLS (TlsDxe.inf, TlsLib.inf), RSA_OAEP, RSA_PK1 - (If BaseRngLibNull interface ASSERTed at boot time) Signed-off-by: Jian J Wang Reviewed-by: Laszlo Ersek Reviewed-by: Liming Gao --- .../Library/BaseRngLibNull/BaseRngLibNull.c | 94 +++++++++++++++++++ .../Library/BaseRngLibNull/BaseRngLibNull.inf | 30 ++++++ .../Library/BaseRngLibNull/BaseRngLibNull.uni | 14 +++ MdePkg/MdePkg.dsc | 1 + 4 files changed, 139 insertions(+) create mode 100644 MdePkg/Library/BaseRngLibNull/BaseRngLibNull.c create mode 100644 MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf create mode 100644 MdePkg/Library/BaseRngLibNull/BaseRngLibNull.uni diff --git a/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.c b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.c new file mode 100644 index 00000000000..cad30599eae --- /dev/null +++ b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.c @@ -0,0 +1,94 @@ +/** @file + Null version of Random number generator services. + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +/** + Generates a 16-bit random number. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the 16-bit random value. + + @retval TRUE Random number generated successfully. + @retval FALSE Failed to generate the random number. + +**/ +BOOLEAN +EFIAPI +GetRandomNumber16 ( + OUT UINT16 *Rand + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Generates a 32-bit random number. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the 32-bit random value. + + @retval TRUE Random number generated successfully. + @retval FALSE Failed to generate the random number. + +**/ +BOOLEAN +EFIAPI +GetRandomNumber32 ( + OUT UINT32 *Rand + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Generates a 64-bit random number. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the 64-bit random value. + + @retval TRUE Random number generated successfully. + @retval FALSE Failed to generate the random number. + +**/ +BOOLEAN +EFIAPI +GetRandomNumber64 ( + OUT UINT64 *Rand + ) +{ + ASSERT (FALSE); + return FALSE; +} + +/** + Generates a 128-bit random number. + + if Rand is NULL, then ASSERT(). + + @param[out] Rand Buffer pointer to store the 128-bit random value. + + @retval TRUE Random number generated successfully. + @retval FALSE Failed to generate the random number. + +**/ +BOOLEAN +EFIAPI +GetRandomNumber128 ( + OUT UINT64 *Rand + ) +{ + ASSERT (FALSE); + return FALSE; +} diff --git a/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf new file mode 100644 index 00000000000..f21e20a9cca --- /dev/null +++ b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf @@ -0,0 +1,30 @@ +## @file +# Null instance of RNG (Random Number Generator) Library. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010029 + BASE_NAME = BaseRngLibNull + MODULE_UNI_FILE = BaseRngLibNull.uni + FILE_GUID = CD8991F8-2061-4084-8C9E-9C6F352DC58D + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = RngLib + +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 EBC +# + +[Sources] + BaseRngLibNull.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + DebugLib diff --git a/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.uni b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.uni new file mode 100644 index 00000000000..f32be6a617e --- /dev/null +++ b/MdePkg/Library/BaseRngLibNull/BaseRngLibNull.uni @@ -0,0 +1,14 @@ +// /** @file +// Null Instance of RNG (Random Number Generator) Library. +// +// Copyright (c) 2019, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Null Instance of RNG Library" + +#string STR_MODULE_DESCRIPTION #language en-US "This library instance should be used with modules that inherit an (indirect) dependency on the RngLib class, but never actually call RngLib APIs for consuming randomness." + diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index c1278e79070..0aeafaaacca 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -61,6 +61,7 @@ MdePkg/Library/BaseUefiDecompressLib/BaseUefiTianoCustomDecompressLib.inf MdePkg/Library/BaseSmbusLibNull/BaseSmbusLibNull.inf MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + MdePkg/Library/BaseRngLibNull/BaseRngLibNull.inf MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf MdePkg/Library/DxeCoreHobLib/DxeCoreHobLib.inf From 70c50f19205e7c93292306fa67998b59b1f137c0 Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:53 +0530 Subject: [PATCH 102/384] MdePkg/SmBios.h: SMBIOS 3.3.0 add PCI gen4 values for type 9 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 System Slots (Type 9): - SMBIOSCR00184: add PCI Express Gen 4 values Cc: Michael D Kinney Cc: Liming Gao Cc: Sai Chaganty Reviewed-by: Sai Chaganty Reviewed-by: Liming Gao Signed-off-by: Zhichao Gao --- MdePkg/Include/IndustryStandard/SmBios.h | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h index f504cc84e70..0a31e37f18f 100644 --- a/MdePkg/Include/IndustryStandard/SmBios.h +++ b/MdePkg/Include/IndustryStandard/SmBios.h @@ -1,7 +1,7 @@ /** @file Industry Standard Definitions of SMBIOS Table Specification v3.3.0. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2015-2017 Hewlett Packard Enterprise Development LP
(C) Copyright 2015 - 2019 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -1307,7 +1307,13 @@ typedef enum { SlotTypePciExpressGen3X2 = 0xB3, SlotTypePciExpressGen3X4 = 0xB4, SlotTypePciExpressGen3X8 = 0xB5, - SlotTypePciExpressGen3X16 = 0xB6 + SlotTypePciExpressGen3X16 = 0xB6, + SlotTypePciExpressGen4 = 0xB8, + SlotTypePciExpressGen4X1 = 0xB9, + SlotTypePciExpressGen4X2 = 0xBA, + SlotTypePciExpressGen4X4 = 0xBB, + SlotTypePciExpressGen4X8 = 0xBC, + SlotTypePciExpressGen4X16 = 0xBD } MISC_SLOT_TYPE; /// From 9e50ef63e864787daa6b2e785bae651c4426d86e Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:54 +0530 Subject: [PATCH 103/384] MdePkg/SmBios.h: SMBIOS 3.3.0 add support for CXL Flexbus REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Various: - SMBIOSCR00183: add support for CXL Flexbus Cc: Michael D Kinney Cc: Liming Gao Cc: Sai Chaganty Reviewed-by: Sai Chaganty Reviewed-by: Liming Gao Signed-off-by: Zhichao Gao --- MdePkg/Include/IndustryStandard/SmBios.h | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h index 0a31e37f18f..54ec837671c 100644 --- a/MdePkg/Include/IndustryStandard/SmBios.h +++ b/MdePkg/Include/IndustryStandard/SmBios.h @@ -1285,6 +1285,7 @@ typedef enum { SlotTypePciExpressMini52pinWithBSKO = 0x21, ///< PCI Express Mini 52-pin (CEM spec. 2.0) with bottom-side keep-outs. SlotTypePciExpressMini52pinWithoutBSKO = 0x22, ///< PCI Express Mini 52-pin (CEM spec. 2.0) without bottom-side keep-outs. SlotTypePciExpressMini76pin = 0x23, ///< PCI Express Mini 76-pin (CEM spec. 2.0) Corresponds to Display-Mini card. + SlotTypeCXLFlexbus10 = 0x30, SlotTypePC98C20 = 0xA0, SlotTypePC98C24 = 0xA1, SlotTypePC98E = 0xA2, @@ -1612,7 +1613,8 @@ typedef enum { MemoryArrayLocationPc98C20AddonCard = 0xA0, MemoryArrayLocationPc98C24AddonCard = 0xA1, MemoryArrayLocationPc98EAddonCard = 0xA2, - MemoryArrayLocationPc98LocalBusAddonCard = 0xA3 + MemoryArrayLocationPc98LocalBusAddonCard = 0xA3, + MemoryArrayLocationCXLFlexbus10AddonCard = 0xA4 } MEMORY_ARRAY_LOCATION; /// From 8019eb589a19ed5fe50b6325502c442c77db5191 Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:55 +0530 Subject: [PATCH 104/384] MdePkg/SmBios.h: SMBIOS 3.3.0 Add value HBM and Die for type 17 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Memory Device (Type 17): - SMBIOSCR00178: add new memory device type value (HBM) and new form factor value (Die) Cc: Michael D Kinney Cc: Liming Gao Cc: Sai Chaganty Reviewed-by: Liming Gao Signed-off-by: Zhichao Gao --- MdePkg/Include/IndustryStandard/SmBios.h | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h index 54ec837671c..9aa8cf3e72d 100644 --- a/MdePkg/Include/IndustryStandard/SmBios.h +++ b/MdePkg/Include/IndustryStandard/SmBios.h @@ -1681,7 +1681,8 @@ typedef enum { MemoryFormFactorRimm = 0x0C, MemoryFormFactorSodimm = 0x0D, MemoryFormFactorSrimm = 0x0E, - MemoryFormFactorFbDimm = 0x0F + MemoryFormFactorFbDimm = 0x0F, + MemoryFormFactorDie = 0x10 } MEMORY_FORM_FACTOR; /// @@ -1715,7 +1716,9 @@ typedef enum { MemoryTypeLpddr2 = 0x1C, MemoryTypeLpddr3 = 0x1D, MemoryTypeLpddr4 = 0x1E, - MemoryTypeLogicalNonVolatileDevice = 0x1F + MemoryTypeLogicalNonVolatileDevice = 0x1F, + MemoryTypeHBM = 0x20, + MemoryTypeHBM2 = 0x21 } MEMORY_DEVICE_TYPE; /// From 4b7edd78a03f22bf23ef5b9bc2ede61fee866222 Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:56 +0530 Subject: [PATCH 105/384] MdePkg/SmBios.h: SMBIOS 3.3.0 Update Intel Persistent Memory string REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Memory Device (Type 17): - SMBIOSCR00179: update the string for Intel persistent memory Cc: Michael D Kinney Cc: Liming Gao Cc: Sai Chaganty Reviewed-by: Liming Gao Signed-off-by: Zhichao Gao --- MdePkg/Include/IndustryStandard/SmBios.h | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/MdePkg/Include/IndustryStandard/SmBios.h b/MdePkg/Include/IndustryStandard/SmBios.h index 9aa8cf3e72d..8b3c4d7ba9d 100644 --- a/MdePkg/Include/IndustryStandard/SmBios.h +++ b/MdePkg/Include/IndustryStandard/SmBios.h @@ -1753,6 +1753,10 @@ typedef enum { MemoryTechnologyNvdimmN = 0x04, MemoryTechnologyNvdimmF = 0x05, MemoryTechnologyNvdimmP = 0x06, + // + // This definition is updated to represent Intel + // Optane DC Presistent Memory in SMBIOS spec 3.3.0 + // MemoryTechnologyIntelPersistentMemory = 0x07 } MEMORY_DEVICE_TECHNOLOGY; From 2a9ff5f33f733727b83930c5ccf207613254b13b Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:57 +0530 Subject: [PATCH 106/384] ShellPkg/SmbiosView: SMBIOS 3.3.0 add PCI gen4 values for type 9 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 System Slots (Type 9): - SMBIOSCR00184: add PCI Express Gen 4 values Add the SmBios.h to use the MARCOs or enums. Cc: Ray Ni Cc: Sai Chaganty Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- .../SmbiosView/QueryTable.c | 26 ++++++++++++++++++- .../SmbiosView/QueryTable.h | 4 ++- 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c index fdb7a47d332..94d995bda1e 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c @@ -2,7 +2,7 @@ Build a table, each item is (Key, Info) pair. And give a interface of query a string out of a table. - Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2005 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2016-2019 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -1523,6 +1523,30 @@ TABLE_ITEM SystemSlotTypeTable[] = { { 0xB6, L"PCI Express Gen 3 X16" + }, + { + SlotTypePciExpressGen4, + L"PCI Express Gen 4" + }, + { + SlotTypePciExpressGen4X1, + L"PCI Express Gen 4 X1" + }, + { + SlotTypePciExpressGen4X2, + L"PCI Express Gen 4 X2" + }, + { + SlotTypePciExpressGen4X4, + L"PCI Express Gen 4 X4" + }, + { + SlotTypePciExpressGen4X8, + L"PCI Express Gen 4 X8" + }, + { + SlotTypePciExpressGen4X16, + L"PCI Express Gen 4 X16" } }; diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h index 60fb42c59c3..756009b2f2a 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.h @@ -2,7 +2,7 @@ Build a table, each item is (key, info) pair. and give a interface of query a string out of a table. - Copyright (c) 2005 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2005 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -10,6 +10,8 @@ #ifndef _SMBIOS_QUERY_TABLE_H_ #define _SMBIOS_QUERY_TABLE_H_ +#include + #define QUERY_TABLE_UNFOUND 0xFF typedef struct TABLE_ITEM { From 16efcbbd3ce983e659571671e280d14cdd87ed45 Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:58 +0530 Subject: [PATCH 107/384] ShellPkg/SmbiosView: SMBIOS 3.3.0 add support for CXL Flexbus REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Various: - SMBIOSCR00183: add support for CXL Flexbus Cc: Ray Ni Cc: Sai Chaganty Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- .../UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c index 94d995bda1e..8ed2bae4d34 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c @@ -1432,6 +1432,10 @@ TABLE_ITEM SystemSlotTypeTable[] = { 0x23, L"PCI Express Mini 76-pin (CEM spec. 2.0) Corresponds to Display-Mini card" }, + { + SlotTypeCXLFlexbus10, + L"CXL Flexbus 1.0" + }, { 0xA0, L"PC-98/C20 " @@ -2290,6 +2294,10 @@ TABLE_ITEM PMALocationTable[] = { { 0xA3, L" PC-98/Local bus add-on card" + }, + { + MemoryArrayLocationCXLFlexbus10AddonCard, + L" CXL Flexbus 1.0 add-on card" } }; From 77ad48a263964facdadfb37b4049aab19ce5513c Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:18:59 +0530 Subject: [PATCH 108/384] ShellPkg/SmbiosView: SMBIOS 3.3.0 Add value HBM and Die for type 17 REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Memory Device (Type 17): - SMBIOSCR00178: add new memory device type value (HBM) and new form factor value (Die) Cc: Ray Ni Cc: Sai Chaganty Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- .../SmbiosView/QueryTable.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c index 8ed2bae4d34..16b75f2667d 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c @@ -2423,6 +2423,10 @@ TABLE_ITEM MemoryDeviceFormFactorTable[] = { { 0x0F, L" FB-DIMM" + }, + { + MemoryFormFactorDie, + L" Die" } }; @@ -2538,6 +2542,14 @@ TABLE_ITEM MemoryDeviceTypeTable[] = { { 0x1F, L" Logical non-volatile device" + }, + { + MemoryTypeHBM, + L" HBM (High Bandwidth Memory)" + }, + { + MemoryTypeHBM2, + L" HBM2 (High Bandwidth Memory Generation 2)" } }; From da178f5c5c5832476d37c8a3734815ceea16af86 Mon Sep 17 00:00:00 2001 From: "Gao, Zhichao" Date: Tue, 12 Nov 2019 09:19:00 +0530 Subject: [PATCH 109/384] ShellPkg/SmbiosView: SMBIOS 3.3.0 Update "Intel persistent memory" REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2305 Memory Device (Type 17): - SMBIOSCR00179: update the string for Intel persistent memory Cc: Ray Ni Cc: Sai Chaganty Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- .../UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c index 16b75f2667d..b80e16d56a6 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/SmbiosView/QueryTable.c @@ -2638,8 +2638,8 @@ TABLE_ITEM MemoryDeviceMemoryTechnologyTable[] = { L" NVDIMM-P" }, { - 0x07, - L" Intel persistent memory" + MemoryTechnologyIntelPersistentMemory, + L" Intel Optane DC Persistent Memory" } }; From 6fe77f347ed820c5924f2ac6ddc43aa869cdbd5e Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Sun, 10 Nov 2019 20:03:21 -0800 Subject: [PATCH 110/384] MdeModulePkg/Variable: Fix volatile variable RT cache update logic REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2333 During a SetVariable () invocation, UpdateVariable () is called. UpdateVariable () contains logic to determine whether a volatile or non-volatile UEFI variable was set so the corresponding runtime cache can be updated to reflect the change. The current logic simply evaluates Variable->Volatile to determine which runtime cache should be updated. The problem is Variable->Volatile does not always reflect whether a volatile variable is being set. Variable->Volatile is set to TRUE only in the case a pre-existing variable is found in the volatile variable store. Therefore, the value is FALSE when a new volatile variable is written. This change updates the logic to take this into account. If a new variable is written successfully, the Attributes will accurately reflect whether the variable is non-volatile. If a pre-existing variable is modified, the Volatile field will reflect the type of variable (Attributes are not reliable; e.g. 0x0 indicates deletion). * Observable symptom: A volatile variable that was set successfully might return EFI_NOT_FOUND when the variable should be found. * The issue is a regression introduced to the variable services only when the variable runtime cache is enabled by the following PCD being set to TRUE: gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache * The issue was implemented in commit aab3b9b9a1 but the PCD was not set to TRUE by default enabling the issue until commit e07b7d024a. Fixes: aab3b9b9a1e5e1f3fa966fb1667fc3e6c47e7706 Cc: Liming Gao Cc: Michael D Kinney Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Jian J Wang --- MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index 29d6aca9938..b0ee5e50d00 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -2296,10 +2296,10 @@ UpdateVariable ( Done: if (!EFI_ERROR (Status)) { - if (Variable->Volatile) { - VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache); - } else { + if ((Variable->CurrPtr != NULL && !Variable->Volatile) || (Attributes & EFI_VARIABLE_NON_VOLATILE) != 0) { VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache); + } else { + VolatileCacheInstance = &(mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeVolatileCache); } if (VolatileCacheInstance->Store != NULL) { From 088f35cd0ca05b0b6913703f22fdda997aa027ce Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 14 Nov 2019 17:16:08 -0800 Subject: [PATCH 111/384] Address the test runner not running. --- .azurepipelines/templates/pr-gate-build-job.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index 981acd68a19..c7cada71360 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -22,7 +22,7 @@ jobs: matrix: TARGET_MDE_CPU: Build.Pkgs: 'MdePkg,UefiCpuPkg' - Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_MDEMODULE_DEBUG: Build.Pkgs: 'MdeModulePkg' Build.Targets: 'DEBUG' From 9639c1f3e7f4f0d2df4072a60f754a9c43f2d784 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Tue, 12 Nov 2019 16:47:44 +0800 Subject: [PATCH 112/384] MdeModulePkg: Unify the definitions of size_t REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2338 Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Zhiguang Liu Reviewed-by: Liming Gao --- .../Library/BrotliCustomDecompressLib/brotli/types.h | 6 +----- MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h | 6 +----- 2 files changed, 2 insertions(+), 10 deletions(-) diff --git a/MdeModulePkg/Library/BrotliCustomDecompressLib/brotli/types.h b/MdeModulePkg/Library/BrotliCustomDecompressLib/brotli/types.h index 2867d206f78..35c95696423 100644 --- a/MdeModulePkg/Library/BrotliCustomDecompressLib/brotli/types.h +++ b/MdeModulePkg/Library/BrotliCustomDecompressLib/brotli/types.h @@ -13,11 +13,7 @@ #define BROTLI_COMMON_TYPES_H_ //#include /* for size_t */ -#ifndef _SIZE_T_DEFINED -#if !defined(_WIN64) || defined(__GNUC__) -typedef unsigned int size_t; -#endif -#endif +typedef UINTN size_t; #if defined(_MSC_VER) && (_MSC_VER < 1600) typedef __int8 int8_t; diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h b/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h index cbdecd377bc..e1315b6ec33 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/UefiLzma.h @@ -18,11 +18,7 @@ #undef _WIN32 #endif -#ifndef _SIZE_T_DEFINED -#if !defined(_WIN64) || defined(__GNUC__) -typedef unsigned int size_t; -#endif -#endif +typedef UINTN size_t; #ifdef _WIN64 #undef _WIN64 From 14672c34bdced0b09d4a4226e648e14701442b3e Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 14 Nov 2019 16:00:53 +0800 Subject: [PATCH 113/384] BaseTools: Rename tool chain CLANG9 to CLANGPDB BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2341 Based on feedback from https://edk2.groups.io/g/devel/message/50466, CLANGPDB is the most acceptable tool chain name, because this tool chain generates PE/COFF image with PDB debug symbol. The following changes are made in this patch. 1. Update tool chain name from CLANG9 to CLANGPDB. 2. Update tool chain BUILDRULEFAMILY from CLANGPE to CLANGPDB. 3. Update CLANG9_BIN env name to CLANG_BIN without version info. Signed-off-by: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- BaseTools/Conf/build_rule.template | 14 +-- BaseTools/Conf/tools_def.template | 156 ++++++++++++++--------------- 2 files changed, 85 insertions(+), 85 deletions(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index 3a58ac8015e..84d8426e7d8 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -260,7 +260,7 @@ $(OUTPUT_DIR)(+)$(MODULE_NAME).lib - + "$(SLINK)" $(SLINK_FLAGS) /OUT:${dst} @$(OBJECT_FILES_LIST) @@ -291,7 +291,7 @@ "$(DLINK)" /OUT:${dst} $(DLINK_FLAGS) $(DLINK2_FLAGS) $(DLINK_SPATH) @$(STATIC_LIBRARY_FILES_LIST) "$(DLINK)" /OUT:${dst} $(DLINK_FLAGS) $(DLINK_SPATH) @$(STATIC_LIBRARY_FILES_LIST) - + "$(DLINK)" /OUT:${dst} $(DLINK_FLAGS) $(DLINK_SPATH) @$(STATIC_LIBRARY_FILES_LIST) $(DLINK2_FLAGS) @@ -334,7 +334,7 @@ $(DEBUG_DIR)(+)$(MODULE_NAME) - + "$(DLINK)" $(DLINK_FLAGS) $(DLINK_SPATH) @$(STATIC_LIBRARY_FILES_LIST) @@ -358,7 +358,7 @@ $(OUTPUT_DIR)(+)$(MODULE_NAME).efi - + "$(GENFW)" -e $(MODULE_TYPE) -o ${dst} ${src} $(GENFW_FLAGS) $(CP) ${dst} $(DEBUG_DIR) $(CP) ${dst} $(BIN_DIR)(+)$(MODULE_NAME_GUID).efi @@ -466,7 +466,7 @@ "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) - + "$(ASLCC)" -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(INC) ${src} "$(ASLDLINK)" /OUT:$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) @@ -630,13 +630,13 @@ *.hpk - + $(OUTPUT_DIR)(+)$(MODULE_NAME)hii.lib $(OUTPUT_DIR)(+)$(MODULE_NAME)hii.rc - + "$(GENFW)" -o $(OUTPUT_DIR)(+)$(MODULE_NAME)hii.rc -g $(MODULE_GUID) --hiipackage $(HII_BINARY_PACKAGES) $(GENFW_FLAGS) "$(RC)" /Fo${dst} $(OUTPUT_DIR)(+)$(MODULE_NAME)hii.rc diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index afa13a7cae7..ca0b122dbb6 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -282,7 +282,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc # Required to build platforms or ACPI tables: # Intel(r) ACPI Compiler from # https://acpica.org/downloads -# CLANG9 -Linux, Windows, Mac- Requires: +# CLANGPDB -Linux, Windows, Mac- Requires: # Clang 9 or above from http://releases.llvm.org/ # Optional: # Required to compile nasm source: @@ -2723,97 +2723,97 @@ RELEASE_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_DLINK_FLAGS) -flto -Wl #################################################################################### # -# CLANG9 - This configuration is used to compile under Windows/Linux/Mac to produce +# CLANGPDB - This configuration is used to compile under Windows/Linux/Mac to produce # PE/COFF binaries using LLVM/Clang/LLD with Link Time Optimization enabled # #################################################################################### -*_CLANG9_*_*_FAMILY = GCC -*_CLANG9_*_*_BUILDRULEFAMILY = CLANGPE -*_CLANG9_*_MAKE_PATH = ENV(CLANG_HOST_BIN)make -*_CLANG9_*_*_DLL = ENV(CLANG9_DLL) -*_CLANG9_*_ASL_PATH = DEF(UNIX_IASL_BIN) +*_CLANGPDB_*_*_FAMILY = GCC +*_CLANGPDB_*_*_BUILDRULEFAMILY = CLANGPDB +*_CLANGPDB_*_MAKE_PATH = ENV(CLANG_HOST_BIN)make +*_CLANGPDB_*_*_DLL = ENV(CLANGPDB_DLL) +*_CLANGPDB_*_ASL_PATH = DEF(UNIX_IASL_BIN) -*_CLANG9_*_APP_FLAGS = -*_CLANG9_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS) -*_CLANG9_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS) -*_CLANG9_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS) +*_CLANGPDB_*_APP_FLAGS = +*_CLANGPDB_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS) +*_CLANGPDB_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS) +*_CLANGPDB_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS) -DEFINE CLANG9_IA32_PREFIX = ENV(CLANG9_BIN) -DEFINE CLANG9_X64_PREFIX = ENV(CLANG9_BIN) +DEFINE CLANGPDB_IA32_PREFIX = ENV(CLANG_BIN) +DEFINE CLANGPDB_X64_PREFIX = ENV(CLANG_BIN) -DEFINE CLANG9_IA32_TARGET = -target i686-unknown-windows -DEFINE CLANG9_X64_TARGET = -target x86_64-unknown-windows +DEFINE CLANGPDB_IA32_TARGET = -target i686-unknown-windows +DEFINE CLANGPDB_X64_TARGET = -target x86_64-unknown-windows -DEFINE CLANG9_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-tautological-compare -Wno-tautological-constant-out-of-range-compare -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-microsoft-enum-forward-reference -DEFINE CLANG9_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANG9_WARNING_OVERRIDES) -fno-stack-protector -mms-bitfields -Wno-address -Wno-shift-negative-value -Wno-unknown-pragmas -Wno-incompatible-library-redeclaration -fno-asynchronous-unwind-tables -mno-implicit-float -ftrap-function=undefined_behavior_has_been_optimized_away_by_clang -funsigned-char -fno-ms-extensions -Wno-null-dereference -fms-compatibility -mno-stack-arg-probe +DEFINE CLANGPDB_WARNING_OVERRIDES = -Wno-parentheses-equality -Wno-tautological-compare -Wno-tautological-constant-out-of-range-compare -Wno-empty-body -Wno-unused-const-variable -Wno-varargs -Wno-unknown-warning-option -Wno-microsoft-enum-forward-reference +DEFINE CLANGPDB_ALL_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) DEF(CLANGPDB_WARNING_OVERRIDES) -fno-stack-protector -mms-bitfields -Wno-address -Wno-shift-negative-value -Wno-unknown-pragmas -Wno-incompatible-library-redeclaration -fno-asynchronous-unwind-tables -mno-implicit-float -ftrap-function=undefined_behavior_has_been_optimized_away_by_clang -funsigned-char -fno-ms-extensions -Wno-null-dereference -fms-compatibility -mno-stack-arg-probe ########################### -# CLANG9 IA32 definitions +# CLANGPDB IA32 definitions ########################### -*_CLANG9_IA32_CC_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_SLINK_PATH = DEF(CLANG9_IA32_PREFIX)llvm-lib -*_CLANG9_IA32_DLINK_PATH = DEF(CLANG9_IA32_PREFIX)lld-link -*_CLANG9_IA32_ASLDLINK_PATH = DEF(CLANG9_IA32_PREFIX)lld-link -*_CLANG9_IA32_ASM_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_PP_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_VFRPP_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_ASLCC_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_ASLPP_PATH = DEF(CLANG9_IA32_PREFIX)clang -*_CLANG9_IA32_RC_PATH = DEF(CLANG9_IA32_PREFIX)llvm-rc - -*_CLANG9_IA32_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -m32 -fno-lto DEF(CLANG9_IA32_TARGET) -*_CLANG9_IA32_ASM_FLAGS = DEF(GCC_ASM_FLAGS) -m32 -march=i386 DEF(CLANG9_IA32_TARGET) -*_CLANG9_IA32_OBJCOPY_FLAGS = -*_CLANG9_IA32_NASM_FLAGS = -f win32 -*_CLANG9_IA32_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG9_IA32_TARGET) -*_CLANG9_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG9_IA32_TARGET) -*_CLANG9_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG9_IA32_TARGET) - -DEBUG_CLANG9_IA32_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG9_IA32_TARGET) -gcodeview -DEBUG_CLANG9_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap -DEBUG_CLANG9_IA32_DLINK2_FLAGS = - -RELEASE_CLANG9_IA32_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANG9_IA32_TARGET) -RELEASE_CLANG9_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /MERGE:.rdata=.data /lldmap -RELEASE_CLANG9_IA32_DLINK2_FLAGS = - -NOOPT_CLANG9_IA32_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANG9_IA32_TARGET) -gcodeview -NOOPT_CLANG9_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap -NOOPT_CLANG9_IA32_DLINK2_FLAGS = +*_CLANGPDB_IA32_CC_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_SLINK_PATH = DEF(CLANGPDB_IA32_PREFIX)llvm-lib +*_CLANGPDB_IA32_DLINK_PATH = DEF(CLANGPDB_IA32_PREFIX)lld-link +*_CLANGPDB_IA32_ASLDLINK_PATH = DEF(CLANGPDB_IA32_PREFIX)lld-link +*_CLANGPDB_IA32_ASM_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_PP_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_VFRPP_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_ASLCC_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_ASLPP_PATH = DEF(CLANGPDB_IA32_PREFIX)clang +*_CLANGPDB_IA32_RC_PATH = DEF(CLANGPDB_IA32_PREFIX)llvm-rc + +*_CLANGPDB_IA32_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -m32 -fno-lto DEF(CLANGPDB_IA32_TARGET) +*_CLANGPDB_IA32_ASM_FLAGS = DEF(GCC_ASM_FLAGS) -m32 -march=i386 DEF(CLANGPDB_IA32_TARGET) +*_CLANGPDB_IA32_OBJCOPY_FLAGS = +*_CLANGPDB_IA32_NASM_FLAGS = -f win32 +*_CLANGPDB_IA32_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANGPDB_IA32_TARGET) +*_CLANGPDB_IA32_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANGPDB_IA32_TARGET) +*_CLANGPDB_IA32_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANGPDB_IA32_TARGET) + +DEBUG_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview +DEBUG_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap +DEBUG_CLANGPDB_IA32_DLINK2_FLAGS = + +RELEASE_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -Oz -flto -march=i586 DEF(CLANGPDB_IA32_TARGET) +RELEASE_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /MERGE:.rdata=.data /lldmap +RELEASE_CLANGPDB_IA32_DLINK2_FLAGS = + +NOOPT_CLANGPDB_IA32_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m32 -O0 -march=i586 DEF(CLANGPDB_IA32_TARGET) -gcodeview +NOOPT_CLANGPDB_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /MACHINE:X86 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap +NOOPT_CLANGPDB_IA32_DLINK2_FLAGS = ########################## # CLANGWIN X64 definitions ########################## -*_CLANG9_X64_CC_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_SLINK_PATH = DEF(CLANG9_X64_PREFIX)llvm-lib -*_CLANG9_X64_DLINK_PATH = DEF(CLANG9_X64_PREFIX)lld-link -*_CLANG9_X64_ASLDLINK_PATH = DEF(CLANG9_X64_PREFIX)lld-link -*_CLANG9_X64_ASM_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_PP_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_VFRPP_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_ASLCC_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_ASLPP_PATH = DEF(CLANG9_X64_PREFIX)clang -*_CLANG9_X64_RC_PATH = DEF(CLANG9_IA32_PREFIX)llvm-rc - -*_CLANG9_X64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -m64 -fno-lto DEF(CLANG9_X64_TARGET) -*_CLANG9_X64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) -m64 DEF(CLANG9_X64_TARGET) -*_CLANG9_X64_OBJCOPY_FLAGS = -*_CLANG9_X64_NASM_FLAGS = -f win64 -*_CLANG9_X64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANG9_X64_TARGET) -*_CLANG9_X64_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANG9_X64_TARGET) -*_CLANG9_X64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANG9_X64_TARGET) - -DEBUG_CLANG9_X64_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -Oz -flto DEF(CLANG9_X64_TARGET) -gcodeview -DEBUG_CLANG9_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap -DEBUG_CLANG9_X64_DLINK2_FLAGS = - -RELEASE_CLANG9_X64_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -Oz -flto DEF(CLANG9_X64_TARGET) -RELEASE_CLANG9_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /MERGE:.rdata=.data /lldmap -RELEASE_CLANG9_X64_DLINK2_FLAGS = - -NOOPT_CLANG9_X64_CC_FLAGS = DEF(CLANG9_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -O0 DEF(CLANG9_X64_TARGET) -gcodeview -NOOPT_CLANG9_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap -NOOPT_CLANG9_X64_DLINK2_FLAGS = +*_CLANGPDB_X64_CC_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_SLINK_PATH = DEF(CLANGPDB_X64_PREFIX)llvm-lib +*_CLANGPDB_X64_DLINK_PATH = DEF(CLANGPDB_X64_PREFIX)lld-link +*_CLANGPDB_X64_ASLDLINK_PATH = DEF(CLANGPDB_X64_PREFIX)lld-link +*_CLANGPDB_X64_ASM_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_PP_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_VFRPP_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_ASLCC_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_ASLPP_PATH = DEF(CLANGPDB_X64_PREFIX)clang +*_CLANGPDB_X64_RC_PATH = DEF(CLANGPDB_IA32_PREFIX)llvm-rc + +*_CLANGPDB_X64_ASLCC_FLAGS = DEF(GCC_ASLCC_FLAGS) -m64 -fno-lto DEF(CLANGPDB_X64_TARGET) +*_CLANGPDB_X64_ASM_FLAGS = DEF(GCC_ASM_FLAGS) -m64 DEF(CLANGPDB_X64_TARGET) +*_CLANGPDB_X64_OBJCOPY_FLAGS = +*_CLANGPDB_X64_NASM_FLAGS = -f win64 +*_CLANGPDB_X64_PP_FLAGS = DEF(GCC_PP_FLAGS) DEF(CLANGPDB_X64_TARGET) +*_CLANGPDB_X64_ASLPP_FLAGS = DEF(GCC_ASLPP_FLAGS) DEF(CLANGPDB_X64_TARGET) +*_CLANGPDB_X64_VFRPP_FLAGS = DEF(GCC_VFRPP_FLAGS) DEF(CLANGPDB_X64_TARGET) + +DEBUG_CLANGPDB_X64_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -Oz -flto DEF(CLANGPDB_X64_TARGET) -gcodeview +DEBUG_CLANGPDB_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap +DEBUG_CLANGPDB_X64_DLINK2_FLAGS = + +RELEASE_CLANGPDB_X64_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -Oz -flto DEF(CLANGPDB_X64_TARGET) +RELEASE_CLANGPDB_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /IGNORE:4254 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /MERGE:.rdata=.data /lldmap +RELEASE_CLANGPDB_X64_DLINK2_FLAGS = + +NOOPT_CLANGPDB_X64_CC_FLAGS = DEF(CLANGPDB_ALL_CC_FLAGS) -m64 "-DEFIAPI=__attribute__((ms_abi))" -mno-red-zone -mcmodel=small -O0 DEF(CLANGPDB_X64_TARGET) -gcodeview +NOOPT_CLANGPDB_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT:ICF=10 /ALIGN:32 /FILEALIGN:32 /SECTION:.xdata,D /SECTION:.pdata,D /Machine:X64 /DLL /ENTRY:$(IMAGE_ENTRY_POINT) /SUBSYSTEM:EFI_BOOT_SERVICE_DRIVER /SAFESEH:NO /BASE:0 /DEBUG:GHASH /lldmap +NOOPT_CLANGPDB_X64_DLINK2_FLAGS = # From 6321ec4eaf20991454dbeaed08e2a4defc1ee99d Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 14 Nov 2019 16:02:18 +0800 Subject: [PATCH 114/384] MdeModulePkg RegularExpressionDxe: Update tool chain name to CLANGPDB BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2341 Signed-off-by: Liming Gao Cc: Jian J Wang Reviewed-by: Jian J Wang --- .../Universal/RegularExpressionDxe/RegularExpressionDxe.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf b/MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf index e9c885465d8..dd33205fceb 100644 --- a/MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf +++ b/MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf @@ -108,7 +108,7 @@ GCC:*_*_*_CC_FLAGS = -Wno-error=maybe-uninitialized # Oniguruma: implicit conversion from 'UINTN' (aka 'unsigned long long') to 'long' - GCC:*_CLANG9_*_CC_FLAGS = -Wno-error=constant-conversion + GCC:*_CLANGPDB_*_CC_FLAGS = -Wno-error=constant-conversion # Not add -Wno-error=maybe-uninitialized option for XCODE # XCODE doesn't know this option From 8ecd8c49e4904ad65609378ef49e34dbc01a3708 Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 14 Nov 2019 16:03:24 +0800 Subject: [PATCH 115/384] CryptoPkg CryptoLib: Update tool chain name to CLANGPDB BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2341 Signed-off-by: Liming Gao Cc: Jian J Wang Reviewed-by: Jian J Wang --- CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf | 2 +- CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf | 2 +- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 2 +- CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf | 2 +- 6 files changed, 6 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf index dc9e6e5d45f..1bbe4f435ae 100644 --- a/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/BaseCryptLib.inf @@ -102,6 +102,6 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf index 7b07dd13d2f..c836c257f84 100644 --- a/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/PeiCryptLib.inf @@ -96,6 +96,6 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf index d9e29ef660a..bff308a4f5e 100644 --- a/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/RuntimeCryptLib.inf @@ -107,6 +107,6 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types XCODE:*_*_*_CC_FLAGS = -std=c99 diff --git a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf index b4faaf3f80f..cc0b65fd250 100644 --- a/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf +++ b/CryptoPkg/Library/BaseCryptLib/SmmCryptLib.inf @@ -104,4 +104,4 @@ GCC:*_CLANG35_*_CC_FLAGS = -std=c99 GCC:*_CLANG38_*_CC_FLAGS = -std=c99 - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=incompatible-pointer-types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index b28dd9e4800..44e050f08d4 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -663,7 +663,7 @@ GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types diff --git a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf index 1b6ff5ed547..f1f9fbb938b 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLibCrypto.inf @@ -612,7 +612,7 @@ GCC:*_*_AARCH64_CC_FLAGS = $(OPENSSL_FLAGS) -Wno-error=maybe-uninitialized -Wno-format -Wno-error=unused-but-set-variable GCC:*_CLANG35_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized GCC:*_CLANG38_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized - GCC:*_CLANG9_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize + GCC:*_CLANGPDB_*_CC_FLAGS = -std=c99 -Wno-error=uninitialized -Wno-error=incompatible-pointer-types -Wno-error=pointer-sign -Wno-error=implicit-function-declaration -Wno-error=ignored-pragma-optimize # suppress the following warnings in openssl so we don't break the build with warnings-as-errors: # 1295: Deprecated declaration - give arg types From 0769224ac7b8b074259501561c41957c1d709029 Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 14 Nov 2019 16:04:01 +0800 Subject: [PATCH 116/384] OvmfPkg DSC: Update tool chain name to CLANGPDB BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2341 Signed-off-by: Liming Gao Cc: Laszlo Ersek Reviewed-by: Laszlo Ersek --- OvmfPkg/OvmfPkgIa32.dsc | 6 +++--- OvmfPkg/OvmfPkgIa32X64.dsc | 6 +++--- OvmfPkg/OvmfPkgX64.dsc | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index d350b756304..9a60eb8fe2b 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -67,7 +67,7 @@ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG -!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANG9" +!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANGPDB" GCC:*_*_*_CC_FLAGS = -mno-mmx -mno-sse !endif @@ -81,14 +81,14 @@ [BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 # Force PE/COFF sections to be aligned at 4KB boundaries to support page level # protection of DXE_SMM_DRIVER/SMM_CORE modules [BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 ################################################################################ # diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 1ef82cafe4a..1d1480b50b0 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -67,7 +67,7 @@ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG -!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANG9" +!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANGPDB" GCC:*_*_*_CC_FLAGS = -mno-mmx -mno-sse !endif !if $(SOURCE_DEBUG_ENABLE) == TRUE @@ -86,14 +86,14 @@ [BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 # Force PE/COFF sections to be aligned at 4KB boundaries to support page level # protection of DXE_SMM_DRIVER/SMM_CORE modules [BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 ################################################################################ # diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index 232815c08e1..c287a436f8e 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -67,7 +67,7 @@ GCC:RELEASE_*_*_CC_FLAGS = -DMDEPKG_NDEBUG INTEL:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG MSFT:RELEASE_*_*_CC_FLAGS = /D MDEPKG_NDEBUG -!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANG9" +!if $(TOOL_CHAIN_TAG) != "XCODE5" && $(TOOL_CHAIN_TAG) != "CLANGPDB" GCC:*_*_*_CC_FLAGS = -mno-mmx -mno-sse !endif !if $(SOURCE_DEBUG_ENABLE) == TRUE @@ -86,14 +86,14 @@ [BuildOptions.common.EDKII.DXE_RUNTIME_DRIVER] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 # Force PE/COFF sections to be aligned at 4KB boundaries to support page level # protection of DXE_SMM_DRIVER/SMM_CORE modules [BuildOptions.common.EDKII.DXE_SMM_DRIVER, BuildOptions.common.EDKII.SMM_CORE] GCC:*_*_*_DLINK_FLAGS = -z common-page-size=0x1000 XCODE:*_*_*_DLINK_FLAGS = - CLANGPE: *_*_*_DLINK_FLAGS = /ALIGN:4096 + CLANGPDB:*_*_*_DLINK_FLAGS = /ALIGN:4096 ################################################################################ # From 0b9ad0bc030bbd79073a26fc9b3527ff9128b9da Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 14 Nov 2019 16:04:36 +0800 Subject: [PATCH 117/384] EmulatorPkg DSC and WinHost.inf: Update tool chain name to CLANGPDB BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2341 Signed-off-by: Liming Gao Cc: Ray Ni Cc: Andrew Fish Reviewed-by: Ray Ni --- EmulatorPkg/EmulatorPkg.dsc | 12 ++++++------ EmulatorPkg/Win/Host/WinHost.inf | 8 ++++---- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/EmulatorPkg/EmulatorPkg.dsc b/EmulatorPkg/EmulatorPkg.dsc index 109685b0627..1fc924ae5a1 100644 --- a/EmulatorPkg/EmulatorPkg.dsc +++ b/EmulatorPkg/EmulatorPkg.dsc @@ -240,7 +240,7 @@ !if "MSFT" in $(FAMILY) || $(WIN_HOST_BUILD) == TRUE ## # Emulator, OS WIN application - # CLANG9 is cross OS tool chain. It depends on WIN_HOST_BUILD flag + # CLANGPDB is cross OS tool chain. It depends on WIN_HOST_BUILD flag # to build WinHost application. ## EmulatorPkg/Win/Host/WinHost.inf @@ -421,7 +421,7 @@ MSFT:DEBUG_*_*_CC_FLAGS = /Od /Oy- MSFT:NOOPT_*_*_CC_FLAGS = /Od /Oy- - GCC:DEBUG_CLANG9_*_CC_FLAGS =-O0 -Wno-unused-command-line-argument -Wno-incompatible-pointer-types -Wno-enum-conversion -Wno-incompatible-pointer-types -Wno-sometimes-uninitialized -Wno-constant-conversion -Wno-main-return-type + GCC:DEBUG_CLANGPDB_*_CC_FLAGS =-O0 -Wno-unused-command-line-argument -Wno-incompatible-pointer-types -Wno-enum-conversion -Wno-incompatible-pointer-types -Wno-sometimes-uninitialized -Wno-constant-conversion -Wno-main-return-type MSFT:*_*_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 @@ -429,9 +429,9 @@ !if $(WIN_HOST_BUILD) == TRUE # - # CLANG9 tool chain depends on WIN_HOST_BUILD flag to generate the windows application. + # CLANGPDB tool chain depends on WIN_HOST_BUILD flag to generate the windows application. # - GCC:*_CLANG9_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE - GCC:DEBUG_CLANG9_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 - GCC:NOOPT_CLANG9_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + GCC:*_CLANGPDB_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE + GCC:DEBUG_CLANGPDB_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 + GCC:NOOPT_CLANGPDB_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 !endif diff --git a/EmulatorPkg/Win/Host/WinHost.inf b/EmulatorPkg/Win/Host/WinHost.inf index 1adca10d79d..e0b3ecb15bf 100644 --- a/EmulatorPkg/Win/Host/WinHost.inf +++ b/EmulatorPkg/Win/Host/WinHost.inf @@ -96,8 +96,8 @@ MSFT:*_*_X64_ASM_FLAGS == /nologo /W3 /WX /c /Cx /Zd /W0 /Zi MSFT:*_*_X64_ASMLINK_FLAGS == /link /nologo - GCC:*_CLANG9_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /LIBPATH:"%VCToolsInstallDir%lib\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:AMD64 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint - GCC:*_CLANG9_X64_CC_FLAGS == -m64 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE + GCC:*_CLANGPDB_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /LIBPATH:"%VCToolsInstallDir%lib\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:AMD64 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint + GCC:*_CLANGPDB_X64_CC_FLAGS == -m64 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE - GCC:*_CLANG9_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /LIBPATH:"%VCToolsInstallDir%ib\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:I386 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint - GCC:*_CLANG9_IA32_CC_FLAGS == -m32 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE + GCC:*_CLANGPDB_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /LIBPATH:"%VCToolsInstallDir%ib\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:I386 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint + GCC:*_CLANGPDB_IA32_CC_FLAGS == -m32 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE From 9973b47ecc386123e27374c88021c42120405720 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 14 Nov 2019 22:05:42 -0800 Subject: [PATCH 118/384] Clean up a no-longer needed ignore file from the CISettings. --- MdePkg/MdePkg.ci.yaml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 0066d423059..e5aafd9697a 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -40,7 +40,7 @@ ## options defined ci/Plugin/HostUnitTestDscCompleteCheck "HostUnitTestDscCompleteCheck": { - "IgnoreInf": ["MdePkg/Test/UnitTest/Library/BasePcdLib/TestPcdLibDynamic.inf"], + "IgnoreInf": [""], "DscPath": "MdePkgTest.dsc" }, From 4a4db947136ec132bf108de4417c30e0b38c5192 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 15 Nov 2019 18:01:07 -0800 Subject: [PATCH 119/384] Drop in the readme file and start fleshing it out. --- Readme-RFC.md | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 Readme-RFC.md diff --git a/Readme-RFC.md b/Readme-RFC.md new file mode 100644 index 00000000000..0635b902373 --- /dev/null +++ b/Readme-RFC.md @@ -0,0 +1,75 @@ +# Testing + +UEFI FW Testing Infrastructure supports a few types of testing and this page will help provide some high level info and links for more information. + +_Note:_ This document only covers the host-based unit test component, and will grow as more testing features are added. + +## Testing Infrastructure - Definitions and Descriptions + +### Host-Based Unit Tests + +Host-based unit tests let you compile your unit tests to run as an application in the host. This method can also leverage "mocking" objects/functions so that unit tests can validate functionality in isolation and force unexpected edge cases. These unit tests call C functions directly with known parameter sets to force good and bad conditions. They are linked directly against C code in either a library instance or module. These tests leverage a UnitTest Library. + + +#### Library/Protocol/Ppi/Guid Interface + +An interface unit test should be written such that it would be valid against any implementation of the library or protocol. For example, an interface test of DxeImageVerification lib should produce valid results for both an OpenSSL implementation and an implementation using another crypto provider. This is not going to always be true for proprietary implementations of certain libraries, such as libraries that intentionally remove some defined functionality, but it should be the ultimate goal of all interface tests. + +*Note:* This assertion may not hold true for Null library implementations, which will usually return fixed values. + +#### Library/Driver(PEI/DXE/SMM) Implementation + +These tests expect a particular implementation of a library or a driver(PEI/DXE/SMM) and may have far more detailed test cases. For example, an implementation test could be written for both a Null instance and/or a proprietary implementation of a given library. + +### Host-Based Functionality Tests + +#### Tests for a functionality or feature + +These tests are written against larger chunks of business logic and may not have obvious divisions along a single library or protocol/ppi/guid interface. Test targets come from multiple folders or packages. Most of these will likely be UEFI-based tests, rather than host-based tests, but it's conceivable that some host-based examples may exist. + +### Shared Artifacts + +Some testing formats -- especially the host-based unit tests, the fuzzing tests, and the shell-based functional tests -- may find it convenient to share logic in the form of libraries and helpers. These helpers may include mocks and stubs. + +#### Shared Mocks (proposed definition) + +A true mock is a functional interface that has almost no internal logic and is entirely scripted by the testing engine. An example of this might be a mocked version of GetVariable. When this mocked function is called by the business logic (the logic under test), all it does is ask the test what values it should return. Each test can script the order and content of the return values. As such, this is not an actual variable store, but can easily be used to force certain code paths. + +#### Shared Stubs and Other Host Libs (proposed definition) + +Stubs are a little more complicated than mocks. Rather than blindly returning values, stubs might have shorthand implementations behind them. In the example above, instead of GetVariable being entirely scripted, you might have an entire VariableServices interface (GetVariable, SetVariable, GetNextVariableName) that is backed by a simple array or other data structure. This stubbed version would behave very similarly to a real variable store, but can be pre-populated with specific contents prior to each test to demonstrate and excercise desired behaviors. Stubs and Mocks can also be combined in some instances to produce intricate behaviors. + +## Where Should Things Live? + +### Test cases for a library/protocol/ppi/guid interface + +If what's being tested is an interface (e.g. a library with a public header file), the test should be localized to the parent package. + +``` +Pkg/Test/UnitTest/[Library|Protocol|Ppi|Guid]/ +``` + +### Test cases for the feature under one package + +Pkg/Test/HostFuncTest +Pkg/Test/[Shell|Dxe|Smm|Pei] + +### Test cases for a library/driver(PEI/DXE/SMM) implementation + +Pkg/Universal/EsrtFmpDxe/UnitTest/ + +### Test cases for the feature that spans multiple packages. + +UefiTestPkg/HostFuncTest +UefiTestPkg/[Shell|Dxe|Smm|Pei] + +Code/Test | Location +--------- | -------- +`1)` Host-Based Unit Tests for a library/protocol/ppi/guid interface | In the package that declares the library, protocol, ppi or guid interface in its .DEC file. Should be located in the *Pkg/Test/UnitTest/[Library|Protocol|Ppi|Guid] directory. +`2)` Host-Based Unit Tests for a library/driver(PEI/DXE/SMM) implementation | In the directory that contains the library/driver implementation, in a UnitTest subdirectory.

=============
Module Example: *Pkg/Universal/EsrtFmpDxe/UnitTest/
Library Example: *Pkg/Library/BaseMemoryLib/UnitTest/
=============

+`3)` Host-Based Fuzz Tests for a library/protocol/ppi/guid interface | In the package that declares the library, protocol, ppi or guid interface in its .DEC file. Should be located in the *Pkg/Test/FuzzTest/[Library|Protocol|Ppi|Guid] directory. +`4)` Host-Based Fuzz Tests for a library/driver(PEI/DXE/SMM) implementation | In the directory that contains the library/driver implementation, in a FuzzTest subdirectory.

=============
Module Example: *Pkg/Universal/EsrtFmpDxe/FuzzTest/
Library Example: *Pkg/Library/BaseMemoryLib/FuzzTest/
=============

+`5)` Host-Based Tests for a functionality or feature | If the feature is in one package, should be located in the*Pkg/Test/HostFuncTest directory.
(or)
If the feature spans multiple packages, should be located in the
(or)
UefiTestPkg/HostFuncTest directory. +`6)` Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a functionality or feature | If the feature is in one package, should be located in the *Pkg/Test/[Shell|Dxe|Smm|Pei]Test directory.

(Or)

if the feature spans multiple packages, should be located in UefiTestPkg/Feature/Functional/[Shell|Dxe|Smm|Pei]Test

=============
* PEI Example: MP_SERVICE_PPI. Or check MTRR configuration in a notification function.
* SMM Example: a test in a protocol callback function. (It is different with the solution that SmmAgent+ShellApp)
* DXE Example: a test in a UEFI event call back to check SPI/SMRAM status.
* Shell Example: the SMM handler audit test has a shell-based app that interacts with an SMM handler to get information. The SMM paging audit test gathers information about both DXE and SMM. And the SMM paging functional test actually forces errors into SMM via a DXE driver.
=============

+`7)` Host-Based Library Implementations | Host-Based Implementations of common libraries (eg. MemoryAllocationLibHost) should live in the same package that declares the library interface in its .DEC file in the `*Pkg/HostLibrary` directory. Should have 'Host' in the name. +`8)` Host-Based Mocks and Stubs | Mock and Stub libraries should live in the `UefiHostTestPkg/Helpers` with either 'Mock' or 'Stub' in the library name. From 64859fd604175a6ab1115d5cdacecddff3b4a4b7 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 15 Nov 2019 23:23:58 -0800 Subject: [PATCH 120/384] Clean up the document as it exists. Need to add the "how to start writing a test" section. --- Readme-RFC.md | 26 ++++++++++++++++---------- 1 file changed, 16 insertions(+), 10 deletions(-) diff --git a/Readme-RFC.md b/Readme-RFC.md index 0635b902373..46021034d5e 100644 --- a/Readme-RFC.md +++ b/Readme-RFC.md @@ -43,25 +43,31 @@ Stubs are a little more complicated than mocks. Rather than blindly returning va ### Test cases for a library/protocol/ppi/guid interface -If what's being tested is an interface (e.g. a library with a public header file), the test should be localized to the parent package. +If what's being tested is an interface (e.g. a library with a public header file, like DebugLib), the test should be scoped to the parent package. ``` -Pkg/Test/UnitTest/[Library|Protocol|Ppi|Guid]/ +MdePkg/Test/UnitTest/[Library|Protocol|Ppi|Guid]/ ``` -### Test cases for the feature under one package +### Test cases for a library/driver (PEI/DXE/SMM) implementation -Pkg/Test/HostFuncTest -Pkg/Test/[Shell|Dxe|Smm|Pei] +If what's being tested is a specific implementation (e.g. BaseDebugLibSerialPort for DebugLib), the test should be scoped to the implementation directory itself. -### Test cases for a library/driver(PEI/DXE/SMM) implementation +``` +MdePkg/Library/BaseDebugLibSerialPort/UnitTest/ +``` -Pkg/Universal/EsrtFmpDxe/UnitTest/ +### Test cases for a feature under one package -### Test cases for the feature that spans multiple packages. +``` +Pkg/Test/HostFuncTest/ +``` -UefiTestPkg/HostFuncTest -UefiTestPkg/[Shell|Dxe|Smm|Pei] +### Test cases for a feature that spans multiple packages. + +``` +UefiTestPkg/HostFuncTest/ +``` Code/Test | Location --------- | -------- From 4ab8146c326f9e3f149bd736653fc7a374913808 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 18 Nov 2019 14:17:32 -0800 Subject: [PATCH 121/384] Take a step towards the minified UnitTestPkg. --- .../Include/Library/UnitTestAssertLib.h | 136 +++ UnitTestPkg/Include/Library/UnitTestLib.h | 139 +++ UnitTestPkg/Include/Library/UnitTestLogLib.h | 63 ++ .../Include/Library/UnitTestPersistenceLib.h | 77 ++ .../Include/Library/UnitTestResultReportLib.h | 25 + UnitTestPkg/Include/UnitTestTypes.h | 203 ++++ .../UnitTestAssertLib/UnitTestAssertLib.c | 181 ++++ .../UnitTestAssertLib/UnitTestAssertLib.inf | 37 + UnitTestPkg/Library/UnitTestLib/Md5.c | 347 +++++++ UnitTestPkg/Library/UnitTestLib/Md5.h | 69 ++ UnitTestPkg/Library/UnitTestLib/UnitTestLib.c | 979 ++++++++++++++++++ .../Library/UnitTestLib/UnitTestLibDxe.inf | 46 + .../Library/UnitTestLib/UnitTestLibDxeStub.c | 30 + .../Library/UnitTestLib/UnitTestLibPei.inf | 44 + .../Library/UnitTestLib/UnitTestLibPeiStub.c | 28 + .../Library/UnitTestLib/UnitTestLibSmm.inf | 45 + .../Library/UnitTestLib/UnitTestLibSmmStub.c | 28 + .../Library/UnitTestLogLib/UnitTestLogLib.c | 251 +++++ .../Library/UnitTestLogLib/UnitTestLogLib.inf | 42 + .../UnitTestPersistenceLibNull.c | 93 ++ .../UnitTestPersistenceLibNull.inf | 44 + .../UnitTestResultReportLibDebug.c | 208 ++++ .../UnitTestResultReportLibDebug.inf | 34 + .../UnitTestResultReportLibPlainTextOutput.c | 208 ++++ ...UnitTestResultReportLibPlainTextOutput.inf | 37 + UnitTestPkg/ReadMe.md | 73 ++ .../SampleUnitTestApp/SampleUnitTestApp.c | 213 ++++ .../SampleUnitTestApp/SampleUnitTestApp.inf | 42 + .../SampleUnitTestPeim/SampleUnitTestPeim.c | 215 ++++ .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 42 + .../SampleUnitTestSmm/SampleUnitTestSmm.c | 213 ++++ .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 43 + UnitTestPkg/UnitTestPkg.dec | 62 ++ UnitTestPkg/UnitTestPkg.dsc | 191 ++++ 34 files changed, 4488 insertions(+) create mode 100644 UnitTestPkg/Include/Library/UnitTestAssertLib.h create mode 100644 UnitTestPkg/Include/Library/UnitTestLib.h create mode 100644 UnitTestPkg/Include/Library/UnitTestLogLib.h create mode 100644 UnitTestPkg/Include/Library/UnitTestPersistenceLib.h create mode 100644 UnitTestPkg/Include/Library/UnitTestResultReportLib.h create mode 100644 UnitTestPkg/Include/UnitTestTypes.h create mode 100644 UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c create mode 100644 UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf create mode 100644 UnitTestPkg/Library/UnitTestLib/Md5.c create mode 100644 UnitTestPkg/Library/UnitTestLib/Md5.h create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLib.c create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf create mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c create mode 100644 UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c create mode 100644 UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf create mode 100644 UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c create mode 100644 UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf create mode 100644 UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c create mode 100644 UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf create mode 100644 UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c create mode 100644 UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf create mode 100644 UnitTestPkg/ReadMe.md create mode 100644 UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c create mode 100644 UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf create mode 100644 UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c create mode 100644 UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf create mode 100644 UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c create mode 100644 UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf create mode 100644 UnitTestPkg/UnitTestPkg.dec create mode 100644 UnitTestPkg/UnitTestPkg.dsc diff --git a/UnitTestPkg/Include/Library/UnitTestAssertLib.h b/UnitTestPkg/Include/Library/UnitTestAssertLib.h new file mode 100644 index 00000000000..83162e6b73d --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestAssertLib.h @@ -0,0 +1,136 @@ +/** @file + Provides a unit test assert helpers. This allows tests to focus on testing logic + and the library to handle common assertions. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_ASSERT_LIB_H__ +#define __UNIT_TEST_ASSERT_LIB_H__ + + +#define UT_ASSERT_TRUE(Expression) \ + if(!UnitTestAssertTrue( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_FALSE(Expression) \ + if(!UnitTestAssertFalse( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ + if(!UnitTestAssertMemEqual( Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertNotEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_EFI_ERROR(Status) \ + if(!UnitTestAssertNotEfiError( Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ + if(!UnitTestAssertStatusEqual( Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_NULL(Pointer) \ + if(!UnitTestAssertNotNull(Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { return UNIT_TEST_ERROR_TEST_FAILED; } + + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ); + +#endif \ No newline at end of file diff --git a/UnitTestPkg/Include/Library/UnitTestLib.h b/UnitTestPkg/Include/Library/UnitTestLib.h new file mode 100644 index 00000000000..be185727134 --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestLib.h @@ -0,0 +1,139 @@ +/** @file + Provides a unit test framework. This allows tests to focus on testing logic + and the framework to focus on runnings, reporting, statistics, etc. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_LIB_H__ +#define __UNIT_TEST_LIB_H__ + +/* +Method to Initialize the Unit Test framework + +@param Framework - Unit test framework to be created. +@param Title - String name of the framework. String is copied. +@param ShortTitle - Short string name of the framework. String is copied. +@param VersionString - Version string for the framework. String is copied. + +@retval Success - Unit Test init. +@retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK **Framework, + IN CHAR16 *Title, + IN CHAR16 *ShortTitle, + IN CHAR16 *VersionString + ); + +/* +Creates Unit Test Suite in the Unit Test Framework + +@param Suite - Suite to create +@param Framework - Framework to add suite to +@param Title - String name of the suite. String is copied. +@param Package - String name of the package. String is copied. +@param Sup - Setup function, runs before suite. +@param Tdn - Teardown function, runs after suite. + +@retval Success - Unit Test Suite was created. +@retval EFI_OUT_OF_RESOURCES - Unit Test Suite failed to be created. +*/ +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE **Suite, + IN UNIT_TEST_FRAMEWORK *Framework, + IN CHAR16 *Title, + IN CHAR16 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ); + +/* +Adds test case to Suite + +@param Suite - Suite to add test to. +@param Description - String describing test. String is copied. +@param ClassName - String name of the test. String is copied. +@param Func - Test function. +@param PreReq - Prep function, runs before test. +@param CleanUp - Clean up function, runs after test. +@param Context - Pointer to context. + +@retval Success - Unit test was added. +@retval EFI_OUT_OF_RESOURCES - Unit test failed to be added. +*/ +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE *Suite, + IN CHAR16 *Description, + IN CHAR16 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ); + +EFI_STATUS +EFIAPI +RunAllTestSuites( + IN UNIT_TEST_FRAMEWORK *Framework + ); + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK *Framework + ); + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ); + +EFI_STATUS +EFIAPI +SaveFrameworkStateAndQuit ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ); + +/** + NOTE: Takes in a ResetType, but currently only supports EfiResetCold + and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. + If a more specific reset is required, use SaveFrameworkState() and + call gRT->ResetSystem() directly. + +**/ +EFI_STATUS +EFIAPI +SaveFrameworkStateAndReboot ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize, + IN EFI_RESET_TYPE ResetType + ); + +/** + Set the boot manager to boot from a specific device on the next boot. + This should be set only for the next boot and shouldn't + require any manual clean up +**/ +EFI_STATUS +EFIAPI +SetFrameworkBootNextDevice ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ); + +#endif \ No newline at end of file diff --git a/UnitTestPkg/Include/Library/UnitTestLogLib.h b/UnitTestPkg/Include/Library/UnitTestLogLib.h new file mode 100644 index 00000000000..ef163691ecb --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestLogLib.h @@ -0,0 +1,63 @@ +/** @file + Provides a unit test framework logging. This allows tests to focus on testing logic + and the library to handle unit test specific logging. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_LOG_LIB_H__ +#define __UNIT_TEST_LOG_LIB_H__ + + + +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST LOGGING DEFINITIONS AND FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// IMPORTANT NOTE: These macros should ONLY be used in a Unit Test. +// They will consume the Framework Handle and update the Framework->CurrentTest. + +#define UT_LOG_ERROR(Format, ...) \ + UnitTestLog( Framework, DEBUG_ERROR, Format, __VA_ARGS__ ); +#define UT_LOG_WARNING(Format, ...) \ + UnitTestLog( Framework, DEBUG_WARN, Format, __VA_ARGS__ ); +#define UT_LOG_INFO(Format, ...) \ + UnitTestLog( Framework, DEBUG_INFO, Format, __VA_ARGS__ ); +#define UT_LOG_VERBOSE(Format, ...) \ + UnitTestLog( Framework, DEBUG_VERBOSE, Format, __VA_ARGS__ ); + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ); + +VOID +EFIAPI +UnitTestLogInit ( +IN OUT UNIT_TEST *Test, +IN UINT8 *Buffer OPTIONAL, +IN UINTN BufferSize +); + +VOID +EFIAPI +UnitTestLogFailure( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, + ... +); + +#endif \ No newline at end of file diff --git a/UnitTestPkg/Include/Library/UnitTestPersistenceLib.h b/UnitTestPkg/Include/Library/UnitTestPersistenceLib.h new file mode 100644 index 00000000000..27bfb16bc38 --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestPersistenceLib.h @@ -0,0 +1,77 @@ +/** @file -- UnitTestPersistenceLib.h + This header file describes a library that contains functions to save and + restore unit test internal state, in case the test needs to pause and resume + (eg. a reboot-based test). + + Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _UNIT_TEST_PERSISTENCE_LIB_H_ +#define _UNIT_TEST_PERSISTENCE_LIB_H_ + +#define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ); + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ); + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ); + +#endif // _UNIT_TEST_PERSISTENCE_LIB_H_ diff --git a/UnitTestPkg/Include/Library/UnitTestResultReportLib.h b/UnitTestPkg/Include/Library/UnitTestResultReportLib.h new file mode 100644 index 00000000000..96b5da7eeae --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestResultReportLib.h @@ -0,0 +1,25 @@ +/** @file + Provides a unit test result report. This allows new result output formats to be easily + customized. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_RESULT_REPORT_LIB_H__ +#define __UNIT_TEST_RESULT_REPORT_LIB_H__ + +/* +Method to produce the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework +); + +#endif \ No newline at end of file diff --git a/UnitTestPkg/Include/UnitTestTypes.h b/UnitTestPkg/Include/UnitTestTypes.h new file mode 100644 index 00000000000..d1f9e86c248 --- /dev/null +++ b/UnitTestPkg/Include/UnitTestTypes.h @@ -0,0 +1,203 @@ +/** @file + Provides the basic types and common elements of the unit test framework + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_TYPES_H__ +#define __UNIT_TEST_TYPES_H__ + +///================================================================================================ +///================================================================================================ +/// +/// HANDY DEFINITIONS +/// +///================================================================================================ +///================================================================================================ +#define UNIT_TEST_MAX_STRING_LENGTH (120) + +#define UNIT_TEST_FINGERPRINT_SIZE (16) // Hardcoded to MD5_HASHSIZE. +#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) + +typedef UINT32 UNIT_TEST_STATUS; +#define UNIT_TEST_PASSED (0) +#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) +#define UNIT_TEST_ERROR_TEST_FAILED (2) +#define UNIT_TEST_SKIPPED (0xFFFFFFFD) +#define UNIT_TEST_RUNNING (0xFFFFFFFE) +#define UNIT_TEST_PENDING (0xFFFFFFFF) + +typedef UINT32 FAILURE_TYPE; +#define FAILURETYPE_NOFAILURE (0) +#define FAILURETYPE_OTHER (1) +#define FAILURETYPE_ASSERTTRUE (2) +#define FAILURETYPE_ASSERTFALSE (3) +#define FAILURETYPE_ASSERTEQUAL (4) +#define FAILURETYPE_ASSERTNOTEQUAL (5) +#define FAILURETYPE_ASSERTNOTEFIERROR (6) +#define FAILURETYPE_ASSERTSTATUSEQUAL (7) +#define FAILURETYPE_ASSERTNOTNULL (8) + +typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. +typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. +typedef VOID* UNIT_TEST_CONTEXT; + + +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST FUNCTION TYPE DEFINITIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Unit-Test Function pointer type. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_FUNCTION) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Prerequisite Function pointer type. +// NOTE: Should be the same as UnitTest. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_PREREQ) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Cleanup (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_CLEANUP) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Suite Setup (before) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_SETUP) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + +// +// Unit-Test Test Suite Teardown (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_TEARDOWN) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + + +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST DATA STRUCTURE DEFINITIONS +/// +///================================================================================================ +///================================================================================================ + + +typedef struct { + CHAR16 *Description; + CHAR16 *ClassName; //can't have spaces and should be short + CHAR16 *Log; + FAILURE_TYPE FailureType; + CHAR16 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + UNIT_TEST_STATUS Result; + UNIT_TEST_FUNCTION RunTest; + UNIT_TEST_PREREQ PreReq; + UNIT_TEST_CLEANUP CleanUp; + UNIT_TEST_CONTEXT Context; + UNIT_TEST_SUITE_HANDLE ParentSuite; +} UNIT_TEST; + +typedef struct { + LIST_ENTRY Entry; + UNIT_TEST UT; +} UNIT_TEST_LIST_ENTRY; + +typedef struct { + CHAR16 *Title; + CHAR16 *Package; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + UNIT_TEST_SUITE_SETUP Setup; + UNIT_TEST_SUITE_TEARDOWN Teardown; + LIST_ENTRY TestCaseList; // UNIT_TEST_LIST_ENTRY + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} UNIT_TEST_SUITE; + +typedef struct { + LIST_ENTRY Entry; + UNIT_TEST_SUITE UTS; +} UNIT_TEST_SUITE_LIST_ENTRY; + +typedef struct { + CHAR16 *Title; + CHAR16 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR16 *VersionString; + CHAR16 *Log; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY + EFI_TIME StartTime; + EFI_TIME EndTime; + UNIT_TEST *CurrentTest; + VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. +} UNIT_TEST_FRAMEWORK; + + +// +//Structures for the framework to serializing unit test status +// +#pragma pack (1) + +typedef struct +{ + UINT32 Size; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. + CHAR16 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + FAILURE_TYPE FailureType; + UNIT_TEST_STATUS Result; + // CHAR16 Log[]; +} UNIT_TEST_SAVE_TEST; + +typedef struct +{ + UINT32 Size; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. + // UINT8 Data[]; // Actual data of the context. +} UNIT_TEST_SAVE_CONTEXT; + +typedef struct +{ + UINT8 Version; + UINT32 BlobSize; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. + EFI_TIME StartTime; + UINT32 TestCount; + BOOLEAN HasSavedContext; + // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. + // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. + // CHAR16 Log[]; // NOTE: Not yet implemented!! +} UNIT_TEST_SAVE_HEADER; + +#pragma pack () + +#endif \ No newline at end of file diff --git a/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c new file mode 100644 index 00000000000..b8dc0a865b4 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c @@ -0,0 +1,181 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include + + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (!Expression) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); + } + return Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (Expression) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + } + return !Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (EFI_ERROR( Status )) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); + } + return !EFI_ERROR( Status ); +} + + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA != ValueB)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + return FALSE; + } + return TRUE; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA == ValueB)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA != ValueB); +} + + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if ((Status != Expected)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); + } + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + if (Pointer == NULL) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + } + return (Pointer != NULL); + +} diff --git a/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf new file mode 100644 index 00000000000..ff6360a0c47 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf @@ -0,0 +1,37 @@ +## @file +# Library to support simple and readable Unit Test Assert +# +# +# @copyright +# Copyright (c) 2017 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestAssertLib +FILE_GUID = FDDB0735-04FE-447C-B987-305988BDC983 +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestAssertLib + + +[LibraryClasses] + DebugLib + BaseLib + BaseMemoryLib + UnitTestLogLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + +[Sources] + UnitTestAssertLib.c diff --git a/UnitTestPkg/Library/UnitTestLib/Md5.c b/UnitTestPkg/Library/UnitTestLib/Md5.c new file mode 100644 index 00000000000..16e91f84058 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/Md5.c @@ -0,0 +1,347 @@ +/** @file + Implementation of MD5 algorithm. + +Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +#include "Md5.h" + +CONST UINT32 Md5_Data[][2] = { + { 0, 1 }, + { 1, 5 }, + { 5, 3 }, + { 0, 7 } +}; + +CONST UINT32 Md5_S[][4] = { + { 7, 22, 17, 12 }, + { 5, 20, 14, 9 }, + { 4, 23, 16 ,11 }, + { 6, 21, 15, 10 }, +}; + +CONST UINT32 Md5_T[] = { + 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, + 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, + 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, + 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, + 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, + 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, + 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, + 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, + 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, + 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, + 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, + 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, + 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, + 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, + 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, + 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 +}; + +CONST UINT8 Md5HashPadding[] = +{ + 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 +}; + +// +// ROTATE_LEFT rotates x left n bits. +// +#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) + +#define SA MedStates[Index2 & 3] +#define SB MedStates[(Index2 + 1) & 3] +#define SC MedStates[(Index2 + 2) & 3] +#define SD MedStates[(Index2 + 3) & 3] + +/** + Tf1 is one basic MD5 transform function. + + @param[in] A A 32-bit quantity. + @param[in] B A 32-bit quantity. + @param[in] C A 32-bit quantity. + + @return Output was produced as a 32-bit quantity based on the + three 32-bit input quantity. +**/ +UINT32 +Tf1 ( + IN UINT32 A, + IN UINT32 B, + IN UINT32 C + ) +{ + return (A & B) | (~A & C); +} + +/** + Tf2 is one basic MD5 transform function. + + @param[in] A A 32-bit quantity. + @param[in] B A 32-bit quantity. + @param[in] C A 32-bit quantity. + + @return Output was produced as a 32-bit quantity based on the + three 32-bit input quantity. +**/ +UINT32 +Tf2 ( + IN UINT32 A, + IN UINT32 B, + IN UINT32 C + ) +{ + return (A & C) | (B & ~C); +} + +/** + Tf3 is one basic MD5 transform function. + + @param[in] A A 32-bit quantity. + @param[in] B A 32-bit quantity. + @param[in] C A 32-bit quantity. + + @return Output was produced as a 32-bit quantity based on the + three 32-bit input quantity. +**/ +UINT32 +Tf3 ( + IN UINT32 A, + IN UINT32 B, + IN UINT32 C + ) +{ + return A ^ B ^ C; +} + +/** + Tf4 is one basic MD5 transform function. + + @param[in] A A 32-bit quantity. + @param[in] B A 32-bit quantity. + @param[in] C A 32-bit quantity. + + @return Output was produced as a 32-bit quantity based on the + three 32-bit input quantity. +**/ +UINT32 +Tf4 ( + IN UINT32 A, + IN UINT32 B, + IN UINT32 C + ) +{ + return B ^ (A | ~C); +} + +typedef +UINT32 +(*MD5_TRANSFORM_FUNC) ( + IN UINT32 A, + IN UINT32 B, + IN UINT32 C + ); + +CONST MD5_TRANSFORM_FUNC Md5_F[] = { + Tf1, + Tf2, + Tf3, + Tf4 +}; + +/** + Perform the MD5 transform on 64 bytes data segment. + + @param[in, out] Md5Ctx It includes the data segment for Md5 transform. +**/ +VOID +MD5Transform ( + IN OUT MD5_CTX *Md5Ctx + ) +{ + UINT32 Index1; + UINT32 Index2; + UINT32 MedStates[MD5_HASHSIZE >> 2]; + UINT32 *Data; + UINT32 IndexD; + UINT32 IndexT; + + Data = (UINT32 *) Md5Ctx->M; + + // + // Copy MD5 states to MedStates + // + CopyMem (MedStates, Md5Ctx->States, MD5_HASHSIZE); + + IndexT = 0; + for (Index1 = 0; Index1 < 4; Index1++) { + IndexD = Md5_Data[Index1][0]; + for (Index2 = 16; Index2 > 0; Index2--) { + SA += (*Md5_F[Index1]) (SB, SC, SD) + Data[IndexD] + Md5_T[IndexT]; + SA = ROTATE_LEFT (SA, Md5_S[Index1][Index2 & 3]); + SA += SB; + + IndexD += Md5_Data[Index1][1]; + IndexD &= 15; + + IndexT++; + } + } + + for (Index1 = 0; Index1 < 4; Index1++) { + Md5Ctx->States[Index1] += MedStates[Index1]; + } +} + +/** + Copy data segment into the M field of MD5_CTX structure for later transform. + If the length of data segment is larger than 64 bytes, then does the transform + immediately and the generated Md5 code is stored in the States field of MD5_CTX + data struct for later accumulation. + All of Md5 code generated for the sequential 64-bytes data segaments are be + accumulated in MD5Final() function. + + @param[in, out] Md5Ctx The data structure of storing the original data + segment and the final result. + @param[in] Data The data wanted to be transformed. + @param[in] DataLen The length of data. +**/ +VOID +MD5UpdateBlock ( + IN OUT MD5_CTX *Md5Ctx, + IN CONST UINT8 *Data, + IN UINTN DataLen + ) +{ + UINTN Limit; + + for (Limit = 64 - Md5Ctx->Count; DataLen >= 64 - Md5Ctx->Count; Limit = 64) { + CopyMem (Md5Ctx->M + Md5Ctx->Count, (VOID *)Data, Limit); + MD5Transform (Md5Ctx); + + Md5Ctx->Count = 0; + Data += Limit; + DataLen -= Limit; + } + + CopyMem (Md5Ctx->M + Md5Ctx->Count, (VOID *)Data, DataLen); + Md5Ctx->Count += DataLen; +} + +/** + Initialize four 32-bits chaining variables and use them to do the Md5 transform. + + @param[out] Md5Ctx The data structure of Md5. + + @retval EFI_SUCCESS Initialization is ok. +**/ +EFI_STATUS +MD5Init ( + OUT MD5_CTX *Md5Ctx + ) +{ + ZeroMem (Md5Ctx, sizeof (*Md5Ctx)); + + // + // Set magic initialization constants. + // + Md5Ctx->States[0] = 0x67452301; + Md5Ctx->States[1] = 0xefcdab89; + Md5Ctx->States[2] = 0x98badcfe; + Md5Ctx->States[3] = 0x10325476; + + return EFI_SUCCESS; +} + +/** + the external interface of Md5 algorithm + + @param[in, out] Md5Ctx The data structure of storing the original data + segment and the final result. + @param[in] Data The data wanted to be transformed. + @param[in] DataLen The length of data. + + @retval EFI_SUCCESS The transform is ok. + @retval Others Other errors as indicated. +**/ +EFI_STATUS +MD5Update ( + IN OUT MD5_CTX *Md5Ctx, + IN VOID *Data, + IN UINTN DataLen + ) +{ + if (EFI_ERROR (Md5Ctx->Status)) { + return Md5Ctx->Status; + } + + MD5UpdateBlock (Md5Ctx, (CONST UINT8 *) Data, DataLen); + Md5Ctx->Length += DataLen; + return EFI_SUCCESS; +} + +/** + Accumulate the MD5 value of every data segment and generate the finial + result according to MD5 algorithm. + + @param[in, out] Md5Ctx The data structure of storing the original data + segment and the final result. + @param[out] HashVal The final 128-bits output. + + @retval EFI_SUCCESS The transform is ok. + @retval Others Other errors as indicated. +**/ +EFI_STATUS +MD5Final ( + IN OUT MD5_CTX *Md5Ctx, + OUT UINT8 *HashVal + ) +{ + UINTN PadLength; + + if (Md5Ctx->Status == EFI_ALREADY_STARTED) { + // + // Store Hashed value & Zeroize sensitive context information. + // + CopyMem (HashVal, (UINT8 *) Md5Ctx->States, MD5_HASHSIZE); + ZeroMem ((UINT8 *)Md5Ctx, sizeof (*Md5Ctx)); + + return EFI_SUCCESS; + } + + if (EFI_ERROR (Md5Ctx->Status)) { + return Md5Ctx->Status; + } + + PadLength = Md5Ctx->Count >= 56 ? 120 : 56; + PadLength -= Md5Ctx->Count; + MD5UpdateBlock (Md5Ctx, Md5HashPadding, PadLength); + Md5Ctx->Length = LShiftU64 (Md5Ctx->Length, 3); + MD5UpdateBlock (Md5Ctx, (CONST UINT8 *) &Md5Ctx->Length, 8); + + ZeroMem (Md5Ctx->M, sizeof (Md5Ctx->M)); + Md5Ctx->Length = 0; + Md5Ctx->Status = EFI_ALREADY_STARTED; + return MD5Final (Md5Ctx, HashVal); +} + diff --git a/UnitTestPkg/Library/UnitTestLib/Md5.h b/UnitTestPkg/Library/UnitTestLib/Md5.h new file mode 100644 index 00000000000..320f443ac01 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/Md5.h @@ -0,0 +1,69 @@ +/** @file + Header file for Md5. + +Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _MD5_H_ +#define _MD5_H_ + +#define MD5_HASHSIZE 16 + +typedef struct _MD5_CTX { + EFI_STATUS Status; + UINT64 Length; + UINT32 States[MD5_HASHSIZE / sizeof (UINT32)]; + UINT8 M[64]; + UINTN Count; +} MD5_CTX; + +/** + Initialize four 32-bits chaining variables and use them to do the Md5 transform. + + @param[out] Md5Ctx The data structure of Md5. + + @retval EFI_SUCCESS Initialization is ok. +**/ +EFI_STATUS +MD5Init ( + OUT MD5_CTX *Md5Ctx + ); + +/** + the external interface of Md5 algorithm + + @param[in, out] Md5Ctx The data structure of storing the original data + segment and the final result. + @param[in] Data The data wanted to be transformed. + @param[in] DataLen The length of data. + + @retval EFI_SUCCESS The transform is ok. + @retval Others Other errors as indicated. +**/ +EFI_STATUS +MD5Update ( + IN OUT MD5_CTX *Md5Ctx, + IN VOID *Data, + IN UINTN DataLen + ); + +/** + Accumulate the MD5 value of every data segment and generate the finial + result according to MD5 algorithm. + + @param[in, out] Md5Ctx The data structure of storing the original data + segment and the final result. + @param[out] HashVal The final 128-bits output. + + @retval EFI_SUCCESS The transform is ok. + @retval Others Other errors as indicated. +**/ +EFI_STATUS +MD5Final ( + IN OUT MD5_CTX *Md5Ctx, + OUT UINT8 *HashVal + ); + +#endif diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c new file mode 100644 index 00000000000..1021e7510cb --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c @@ -0,0 +1,979 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "Md5.h" + +MD5_CTX mFingerprintCtx; + +VOID +FrameworkExit ( + VOID + ); + +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ); + +// Prototyped here so that it can be included near the functions that +// it logically goes with. +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ); + + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + + +/** + This function will determine whether the short name violates any rules that would + prevent it from being used as a reporting name or as a serialization name. + + Example: If the name cannot be serialized to a filesystem file name. + + @param[in] ShortTitleString A pointer to the short title string to be evaluated. + + @retval TRUE The string is acceptable. + @retval FALSE The string should not be used. + +**/ +STATIC +BOOLEAN +IsFrameworkShortNameValid ( + IN CHAR16 *ShortTitleString + ) +{ + // TODO: Finish this function. + return TRUE; +} // IsFrameworkShortNameValid() + + +STATIC +CHAR16* +AllocateAndCopyString ( + IN CHAR16 *StringToCopy + ) +{ + CHAR16 *NewString = NULL; + UINTN NewStringLength; + + NewStringLength = StrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; + NewString = AllocatePool( NewStringLength * sizeof( CHAR16 ) ); + if (NewString != NULL) + { + StrCpyS( NewString, NewStringLength, StringToCopy ); + } + + return NewString; +} // AllocateAndCopyString () + + +STATIC +VOID +SetFrameworkFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + MD5Init( &mFingerprintCtx ); + + // For this one we'll just use the title and version as the unique fingerprint. + MD5Update( &mFingerprintCtx, Framework->Title, (StrLen( Framework->Title ) * sizeof( CHAR16 )) ); + MD5Update( &mFingerprintCtx, Framework->VersionString, (StrLen( Framework->VersionString ) * sizeof( CHAR16 )) ); + + MD5Final( &mFingerprintCtx, &Framework->Fingerprint[0] ); + return; +} // SetFrameworkFingerprint() + + +STATIC +VOID +SetSuiteFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework, + IN UNIT_TEST_SUITE *Suite + ) +{ + MD5Init( &mFingerprintCtx ); + + // For this one, we'll use the fingerprint from the framework, and the title of the suite. + MD5Update( &mFingerprintCtx, &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + MD5Update( &mFingerprintCtx, Suite->Title, (StrLen( Suite->Title ) * sizeof( CHAR16 )) ); + MD5Update(&mFingerprintCtx, Suite->Package, (StrLen(Suite->Package) * sizeof(CHAR16))); + + MD5Final( &mFingerprintCtx, &Suite->Fingerprint[0] ); + return; +} // SetSuiteFingerprint() + + +STATIC +VOID +SetTestFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_SUITE *Suite, + IN UNIT_TEST *Test + ) +{ + MD5Init( &mFingerprintCtx ); + + // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. + MD5Update( &mFingerprintCtx, &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + MD5Update( &mFingerprintCtx, Test->Description, (StrLen( Test->Description ) * sizeof( CHAR16 )) ); + MD5Update(&mFingerprintCtx, Test->ClassName, (StrLen(Test->ClassName) * sizeof(CHAR16))); + + MD5Final( &mFingerprintCtx, &Test->Fingerprint[0] ); + return; +} // SetTestFingerprint() + + +STATIC +BOOLEAN +CompareFingerprints ( + IN UINT8 *FingerprintA, + IN UINT8 *FingerprintB + ) +{ + return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); +} // SetTestFingerprint() + + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestFramework() + + +STATIC +EFI_STATUS +FreeUnitTestSuiteEntry ( + IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestSuiteEntry() + + +STATIC +EFI_STATUS +FreeUnitTestTestEntry ( + IN UNIT_TEST_LIST_ENTRY *TestEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestTestEntry() + + +//============================================================================= +// +// ---------------- TEST SETUP FUNCTIONS ------------------------------------- +// +//============================================================================= + + +/* +Method to Initialize the Unit Test framework + +@retval Success - Unit Test init. +@retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK **Framework, + IN CHAR16 *Title, + IN CHAR16 *ShortTitle, + IN CHAR16 *VersionString + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_FRAMEWORK *NewFramework = NULL; + + // + // First, check all pointers and make sure nothing's broked. + if (Framework == NULL || Title == NULL || + ShortTitle == NULL || VersionString == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, determine whether all of the strings are good to use. + if (!IsFrameworkShortNameValid( ShortTitle )) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, set aside some space to start messing with the framework. + NewFramework = AllocateZeroPool( sizeof( UNIT_TEST_FRAMEWORK ) ); + if (NewFramework == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Next, set up all the test data. + NewFramework->Title = AllocateAndCopyString( Title ); + NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); + NewFramework->VersionString = AllocateAndCopyString( VersionString ); + NewFramework->Log = NULL; + NewFramework->CurrentTest = NULL; + NewFramework->SavedState = NULL; + if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || + NewFramework->VersionString == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + InitializeListHead( &(NewFramework->TestSuiteList) ); + + // + // Create the framework fingerprint. + SetFrameworkFingerprint( &NewFramework->Fingerprint[0], NewFramework ); + + // + // If there is a persisted context, load it now. + if (DoesCacheExist( NewFramework )) + { + UNIT_TEST_SAVE_HEADER *SavedState = (UNIT_TEST_SAVE_HEADER*)NewFramework->SavedState; + Status = LoadUnitTestCache( NewFramework, &SavedState ); + if (EFI_ERROR( Status )) + { + // Don't actually report it as an error, but emit a warning. + DEBUG(( DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__ )); + Status = EFI_SUCCESS; + } + } + +Exit: + // + // If we're good, then let's copy the framework. + if (!EFI_ERROR( Status )) + { + *Framework = NewFramework; + } + // Otherwise, we need to undo this horrible thing that we've done. + else + { + FreeUnitTestFramework( NewFramework ); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE **Suite, + IN UNIT_TEST_FRAMEWORK *Framework, + IN CHAR16 *Title, + IN CHAR16 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + + // + // First, let's check to make sure that our parameters look good. + if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewSuiteEntry = AllocateZeroPool( sizeof( UNIT_TEST_SUITE_LIST_ENTRY ) ); + if (NewSuiteEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); + NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); + NewSuiteEntry->UTS.Setup = Sup; + NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.ParentFramework = Framework; + InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. + InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. + if (NewSuiteEntry->UTS.Title == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + if (NewSuiteEntry->UTS.Package == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the suite fingerprint. + SetSuiteFingerprint( &NewSuiteEntry->UTS.Fingerprint[0], Framework, &NewSuiteEntry->UTS ); + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(Framework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); + *Suite = &NewSuiteEntry->UTS; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestSuiteEntry( NewSuiteEntry ); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE *Suite, + IN CHAR16 *Description, + IN CHAR16 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_LIST_ENTRY *NewTestEntry; + UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; + + // + // First, let's check to make sure that our parameters look good. + if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewTestEntry = AllocateZeroPool( sizeof( UNIT_TEST_LIST_ENTRY ) ); + if (NewTestEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewTestEntry->UT.Description = AllocateAndCopyString( Description ); + NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); + NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; + NewTestEntry->UT.FailureMessage[0] = '\0'; + NewTestEntry->UT.Log = NULL; + NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.CleanUp = CleanUp; + NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.Context = Context; + NewTestEntry->UT.Result = UNIT_TEST_PENDING; + NewTestEntry->UT.ParentSuite = Suite; + InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. + if (NewTestEntry->UT.Description == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the test fingerprint. + SetTestFingerprint( &NewTestEntry->UT.Fingerprint[0], Suite, &NewTestEntry->UT ); + + // TODO: Make sure that duplicate fingerprints cannot be created. + + // + // If there is saved test data, update this record. + if (ParentFramework->SavedState != NULL) + { + UpdateTestFromSave( &NewTestEntry->UT, ParentFramework->SavedState ); + } + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(Suite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestTestEntry( NewTestEntry ); + } + + return Status; +} + + +//============================================================================= +// +// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +EFI_STATUS +RunTestSuite ( + IN UNIT_TEST_SUITE *Suite + ) +{ + UNIT_TEST_LIST_ENTRY *TestEntry = NULL; + UNIT_TEST *Test; + UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; + + if (Suite == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %s\n", Suite->Title)); + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + if (Suite->Setup != NULL) + { + Suite->Setup( Suite->ParentFramework ); + } + + // + // Iterate all tests within the suite + // + for (TestEntry = (UNIT_TEST_LIST_ENTRY*)GetFirstNode( &(Suite->TestCaseList) ); // Start at the beginning. + (LIST_ENTRY*)TestEntry != &(Suite->TestCaseList); // Go until you loop back to the head. + TestEntry = (UNIT_TEST_LIST_ENTRY*)GetNextNode( &(Suite->TestCaseList), (LIST_ENTRY*)TestEntry) ) // Always get the next test. + { + Test = &TestEntry->UT; + ParentFramework->CurrentTest = Test; + + DEBUG((DEBUG_VERBOSE, "*********************************************************\n")); + DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %s:\n", Test->Description)); + DEBUG((DEBUG_VERBOSE, "**********************************************************\n")); + + // + // First, check to see whether the test has already been run. + // NOTE: This would generally only be the case if a saved state was detected and loaded. + if (Test->Result != UNIT_TEST_PENDING && Test->Result != UNIT_TEST_RUNNING) + { + DEBUG(( DEBUG_VERBOSE, "Test was run on a previous pass. Skipping.\n" )); + ParentFramework->CurrentTest = NULL; + continue; + } + + // + // Next, if we're still running, make sure that our test prerequisites are in place. + if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) + { + DEBUG(( DEBUG_VERBOSE, "PREREQ\n" )); + if (Test->PreReq( Suite->ParentFramework, Test->Context ) != UNIT_TEST_PASSED) + { + DEBUG(( DEBUG_ERROR, "PreReq Not Met\n" )); + Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; + ParentFramework->CurrentTest = NULL; + continue; + } + } + + // + // Now we should be ready to call the actual test. + // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot + // or quit. The UNIT_TEST_RUNNING state will allow the test to resume + // but will prevent the PreReq from being dispatched a second time. + Test->Result = UNIT_TEST_RUNNING; + Test->Result = Test->RunTest( Suite->ParentFramework, Test->Context ); + + // + // Finally, clean everything up, if need be. + if (Test->CleanUp != NULL) + { + DEBUG(( DEBUG_VERBOSE, "CLEANUP\n" )); + Test->CleanUp( Suite->ParentFramework, Test->Context ); + } + + // + // End the test. + ParentFramework->CurrentTest = NULL; + } // End Test iteration + + + if (Suite->Teardown != NULL) + { + Suite->Teardown( Suite->ParentFramework ); + } + + return EFI_SUCCESS; +} + +EFI_STATUS +EFIAPI +RunAllTestSuites( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + EFI_STATUS Status; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + Status = RunTestSuite(&(Suite->UTS)); + if (EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); + } + } // End Suite iteration + + //Save current state so if test is started again it doesn't have to run. It will just report + SaveFrameworkState(Framework, NULL, 0); + OutputUnitTestFrameworkReport(Framework); + + return EFI_SUCCESS; +} + +//============================================================================= +// +// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- +// +//============================================================================= + + +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ) +{ + UNIT_TEST_SAVE_TEST *CurrentTest, *MatchingTest; + UINT8 *FloatingPointer; + UNIT_TEST_SAVE_CONTEXT *SavedContext; + UINTN Index; + + // + // First, evaluate the inputs. + if (Test == NULL || SavedState == NULL) + { + return; + } + if (SavedState->TestCount == 0) + { + return; + } + + // + // Next, determine whether a matching test can be found. + // Start at the beginning. + MatchingTest = NULL; + FloatingPointer = (UINT8*)SavedState + sizeof( *SavedState ); + for (Index = 0; Index < SavedState->TestCount; Index++) + { + CurrentTest = (UNIT_TEST_SAVE_TEST*)FloatingPointer; + if (CompareFingerprints( &Test->Fingerprint[0], &CurrentTest->Fingerprint[0] )) + { + MatchingTest = CurrentTest; + // If there's a saved context, it's important that we iterate through the entire list. + if (!SavedState->HasSavedContext) + { + break; + } + } + + // If we didn't find it, we have to increment to the next test. + FloatingPointer = (UINT8*)CurrentTest + CurrentTest->Size; + } + + // + // If a matching test was found, copy the status. + if (MatchingTest) + { + // Override the test status with the saved status. + Test->Result = MatchingTest->Result; + + Test->FailureType = MatchingTest->FailureType; + StrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + + // If there is a log string associated, grab that. + // We can tell that there's a log string because the "size" will be larger than + // the structure size. + // IMPORTANT NOTE: There are security implications here. + // This data is user-supplied and we're about to play kinda + // fast and loose with data buffers. + if (MatchingTest->Size > sizeof( UNIT_TEST_SAVE_TEST )) + { + UnitTestLogInit(Test, ((UINT8*)MatchingTest + sizeof( UNIT_TEST_SAVE_TEST )), MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); + } + } + + // + // If the saved context exists and matches this test, grab it, too. + if (SavedState->HasSavedContext) + { + // TODO: Reconcile the difference between the way "size" works for Test Saves + // and the way it works for Context Saves. Too confusing to use it different ways. + + // If there was a saved context, the "matching test" loop will have placed the FloatingPointer + // at the beginning of the context structure. + SavedContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; + if (SavedContext->Size > 0 && + CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) + { + // Override the test context with the saved context. + Test->Context = (VOID*)((UINT8*)SavedContext + sizeof( *SavedContext )); + } + } + + return; +} // UpdateTestFromSave() + + +STATIC +UNIT_TEST_SAVE_HEADER* +SerializeState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + UNIT_TEST_FRAMEWORK *Framework = FrameworkHandle; + UNIT_TEST_SAVE_HEADER *Header = NULL; + LIST_ENTRY *SuiteListHead, *Suite, *TestListHead, *Test; + UINT32 TestCount, TotalSize; + UINTN LogSize; + UNIT_TEST_SAVE_TEST *TestSaveData; + UNIT_TEST_SAVE_CONTEXT *TestSaveContext; + UNIT_TEST *UnitTest; + UINT8 *FloatingPointer; + + // + // First, let's not make assumptions about the parameters. + if (Framework == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) + { + return NULL; + } + + // + // Next, we've gotta figure out the resources that will be required to serialize the + // the framework state so that we can persist it. + // To start with, we're gonna need a header. + TotalSize = sizeof( UNIT_TEST_SAVE_HEADER ); + // Now we need to figure out how many tests there are. + TestCount = 0; + // Iterate all suites. + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) + { + // Iterate all tests within the suite. + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) + { + UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; + // Account for the size of a test structure. + TotalSize += sizeof( UNIT_TEST_SAVE_TEST ); + // If there's a log, make sure to account for the log size. + if (UnitTest->Log != NULL) + { + // The +1 is for the NULL character. Can't forget the NULL character. + LogSize = (StrLen( UnitTest->Log ) + 1) * sizeof( CHAR16 ); + ASSERT( LogSize < MAX_UINT32 ); + TotalSize += (UINT32)LogSize; + } + // Increment the test count. + TestCount++; + } + } + // If there are no tests, we're done here. + if (TestCount == 0) + { + return NULL; + } + // Add room for the context, if there is one. + if (ContextToSave != NULL) + { + TotalSize += sizeof( UNIT_TEST_SAVE_CONTEXT ) + (UINT32)ContextToSaveSize; + } + + // + // Now that we know the size, we need to allocate space for the serialized output. + Header = AllocateZeroPool( TotalSize ); + if (Header == NULL) + { + return NULL; + } + + // + // Alright, let's start setting up some data. + Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; + Header->BlobSize = TotalSize; + CopyMem( &Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + CopyMem( &Header->StartTime, &Framework->StartTime, sizeof( EFI_TIME ) ); + Header->TestCount = TestCount; + Header->HasSavedContext = FALSE; + + // + // Start adding all of the test cases. + // Set the floating pointer to the start of the current test save buffer. + FloatingPointer = (UINT8*)Header + sizeof( UNIT_TEST_SAVE_HEADER ); + // Iterate all suites. + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) + { + // Iterate all tests within the suite. + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) + { + TestSaveData = (UNIT_TEST_SAVE_TEST*)FloatingPointer; + UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; + + // Save the fingerprint. + CopyMem( &TestSaveData->Fingerprint[0], &UnitTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + + // Save the result. + TestSaveData->Result = UnitTest->Result; + TestSaveData->FailureType = UnitTest->FailureType; + StrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + + + // If there is a log, save the log. + FloatingPointer += sizeof( UNIT_TEST_SAVE_TEST ); + if (UnitTest->Log != NULL) + { + // The +1 is for the NULL character. Can't forget the NULL character. + LogSize = (StrLen( UnitTest->Log ) + 1) * sizeof( CHAR16 ); + CopyMem( FloatingPointer, UnitTest->Log, LogSize ); + FloatingPointer += LogSize; + } + + // Update the size once the structure is complete. + // NOTE: Should thise be a straight cast without validation? + // Maybe. + // Am I tired of writing code? + // Yes. + TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8*)TestSaveData); + } + } + + // + // If there is a context to save, let's do that now. + if (ContextToSave != NULL && Framework->CurrentTest != NULL) + { + TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; + TestSaveContext->Size = (UINT32)ContextToSaveSize; + CopyMem( &TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + CopyMem( ((UINT8*)TestSaveContext + sizeof( UNIT_TEST_SAVE_CONTEXT )), ContextToSave, ContextToSaveSize ); + Header->HasSavedContext = TRUE; + } + + return Header; +} + + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + EFI_STATUS Status; + UNIT_TEST_SAVE_HEADER *Header = NULL; + + // + // First, let's not make assumptions about the parameters. + if (FrameworkHandle == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) + { + return EFI_INVALID_PARAMETER; + } + + // + // Now, let's package up all the data for saving. + Header = SerializeState( FrameworkHandle, ContextToSave, ContextToSaveSize ); + if (Header == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // All that should be left to do is save it using the associated persistence lib. + Status = SaveUnitTestCache( FrameworkHandle, Header ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status )); + Status = EFI_DEVICE_ERROR; + } + + // + // Free data that was used. + FreePool( Header ); + + return Status; +} // SaveFrameworkState() + + +EFI_STATUS +EFIAPI +SaveFrameworkStateAndQuit ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + EFI_STATUS Status; + + // + // First, let's not make assumptions about the parameters. + if (FrameworkHandle == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Now, save all the data associated with this framework. + Status = SaveFrameworkState( FrameworkHandle, ContextToSave, ContextToSaveSize ); + + // + // If we're all good, let's book... + if (!EFI_ERROR( Status )) + { + // + // Free data that was used. + FreeUnitTestFramework( (UNIT_TEST_FRAMEWORK*)FrameworkHandle ); + + // + // Quit + FrameworkExit (); + DEBUG(( DEBUG_ERROR, "%a - Unit test failed to quit! Framework can no longer be used!\n", __FUNCTION__ )); + + // + // We REALLY shouldn't be here. + Status = EFI_ABORTED; + } + + return Status; +} // SaveFrameworkStateAndQuit() + + +/** + NOTE: Takes in a ResetType, but currently only supports EfiResetCold + and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. + If a more specific reset is required, use SaveFrameworkState() and + call gRT->ResetSystem() directly. + +**/ +EFI_STATUS +EFIAPI +SaveFrameworkStateAndReboot ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize, + IN EFI_RESET_TYPE ResetType + ) +{ + EFI_STATUS Status; + + // + // First, let's not make assumptions about the parameters. + if (FrameworkHandle == NULL || + (ResetType != EfiResetCold && ResetType != EfiResetWarm)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Now, save all the data associated with this framework. + Status = SaveFrameworkState( FrameworkHandle, ContextToSave, ContextToSaveSize ); + + // + // If we're all good, let's book... + if (!EFI_ERROR( Status )) + { + // + // Next, we want to update the BootNext variable to the device + // so that we have a fighting chance of coming back here. + // + SetBootNextDevice(); + + // + // Free data that was used. + FreeUnitTestFramework( (UNIT_TEST_FRAMEWORK*)FrameworkHandle ); + + // + // Reset + FrameworkResetSystem (ResetType); + DEBUG(( DEBUG_ERROR, "%a - Unit test failed to quit! Framework can no longer be used!\n", __FUNCTION__ )); + + // + // We REALLY shouldn't be here. + Status = EFI_ABORTED; + } + + return Status; +} // SaveFrameworkStateAndReboot() + +/** + Set the boot manager to boot from a specific device on the next boot. + This should be set only for the next boot and shouldn't + require any manual clean up +**/ +EFI_STATUS +EFIAPI +SetFrameworkBootNextDevice ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + return SetBootNextDevice(); +} // SaveFrameworkStateAndReboot() \ No newline at end of file diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf new file mode 100644 index 00000000000..d130859bfc0 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf @@ -0,0 +1,46 @@ +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibDxe +FILE_GUID = 98CEF9CA-15CE-40A3-ADE8-C299953CD0F6 +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UefiRuntimeServicesTableLib + UefiLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestBootLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c + UnitTestLibDxeStub.c + Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c new file mode 100644 index 00000000000..4ea06867db3 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c @@ -0,0 +1,30 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include + +VOID +FrameworkExit ( + VOID + ) +{ + gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); +} + +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); +} + diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf new file mode 100644 index 00000000000..d9de48391d4 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -0,0 +1,44 @@ +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibPei +FILE_GUID = 7DDA6F03-CD2D-4B5D-BC67-E5EA5AE3014B +VERSION_STRING = 1.0 +MODULE_TYPE = PEIM +LIBRARY_CLASS = UnitTestLib|PEIM + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestBootLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c + UnitTestLibPeiStub.c + Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c new file mode 100644 index 00000000000..fc4fd926403 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c @@ -0,0 +1,28 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include + +VOID +FrameworkExit ( + VOID + ) +{ + // TBD +} + +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + // TBD +} + diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf new file mode 100644 index 00000000000..d589bf4f6c8 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf @@ -0,0 +1,45 @@ +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibSmm +FILE_GUID = 9A991713-AE25-4C41-9E3D-F72D6E0E7CEE +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_SMM_DRIVER +PI_SPECIFICATION_VERSION = 0x0001000A +LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestBootLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c + UnitTestLibSmmStub.c + Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c new file mode 100644 index 00000000000..d71ffb605a3 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c @@ -0,0 +1,28 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include + +VOID +FrameworkExit ( + VOID + ) +{ + // TBD +} + +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + // TBD +} + diff --git a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c new file mode 100644 index 00000000000..fe764d015ef --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -0,0 +1,251 @@ +/** + +Implement UnitTestLogLib - Unit test debugging log + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) +#define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) + + + +struct _UNIT_TEST_LOG_PREFIX_STRING +{ + UNIT_TEST_STATUS LogLevel; + CHAR8 *String; +}; + +struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = +{ + { DEBUG_ERROR, "[ERROR] " }, + { DEBUG_WARN, "[WARNING] " }, + { DEBUG_INFO, "[INFO] " }, + { DEBUG_VERBOSE, "[VERBOSE] " } +}; +UINTN mLogPrefixStringsCount = sizeof( mLogPrefixStrings ) / sizeof( mLogPrefixStrings[0] ); + + + + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForStatusLogPrefix ( + IN UINTN LogLevel + ) +{ + UINTN Index; + CHAR8 *Result = NULL; + + for (Index = 0; Index < mLogPrefixStringsCount; Index++) + { + if (mLogPrefixStrings[Index].LogLevel == LogLevel) + { + Result = mLogPrefixStrings[Index].String; + break; + } + } + + return Result; +} + + + +STATIC +EFI_STATUS +AddStringToUnitTestLog ( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR16 *String + ) +{ + EFI_STATUS Status; + + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || String == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // If this is the first log for the test allocate log space + if (UnitTest->Log == NULL) + { + UnitTestLogInit(UnitTest, NULL, 0); + } + + if (UnitTest->Log == NULL) + { + DEBUG((DEBUG_ERROR, "Failed to allocate space for unit test log\n")); + ASSERT(UnitTest->Log != NULL); + return EFI_OUT_OF_RESOURCES; + } + + Status = StrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER/ sizeof(CHAR16), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); + if(EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); + return Status; + } + + return EFI_SUCCESS; +} + +STATIC +EFI_STATUS +AddUnitTestFailure( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR16 *FailureMessage, + FAILURE_TYPE FailureType +) +{ + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || FailureMessage == NULL) + { + return EFI_INVALID_PARAMETER; + } + + UnitTest->FailureType = FailureType; + StrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + + return EFI_SUCCESS; +} + + +//============================================================================= +// +// ---------------- PUBLIC FUNCTIONS ------------------------------------ +// +//============================================================================= +VOID +EFIAPI +UnitTestLogInit ( +IN OUT UNIT_TEST *Test, +IN UINT8 *Buffer, +IN UINTN BufferSize +) +{ + // + // Make sure that you're cooking with gas. + // + if (Test == NULL) + { + DEBUG((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); + return; + } + + // If this is the first log for the test allocate log space + if (Test->Log == NULL) + { + Test->Log = AllocateZeroPool(UNIT_TEST_MAX_LOG_BUFFER); + } + + //check again to make sure allocate worked + if(Test->Log == NULL) + { + DEBUG((DEBUG_ERROR, "Failed to allocate memory for the log\n")); + return; + } + + if((Buffer != NULL) && (BufferSize > 0) && ((BufferSize <= UNIT_TEST_MAX_LOG_BUFFER))) + { + CopyMem(Test->Log, Buffer, BufferSize); + } +} + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR16 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CONST CHAR8 *LogTypePrefix = NULL; + VA_LIST Marker; + UINTN LogLevel = (UINTN) PcdGet32(UnitTestLogLevel); + // + // Make sure that this debug mode is enabled. + // + if ((ErrorLevel & LogLevel) == 0) { + return; + } + + // + // If we need to define a new format string... + // well... get to it. + // + LogTypePrefix = GetStringForStatusLogPrefix( ErrorLevel ); + if (LogTypePrefix != NULL) + { + AsciiSPrint( NewFormatString, sizeof( NewFormatString ), "%a%a", LogTypePrefix, Format ); + } + else + { + AsciiStrCpyS( NewFormatString, sizeof( NewFormatString ), Format ); + } + + // + // Convert the message to an ASCII String + // + VA_START (Marker, Format); + UnicodeVSPrintAsciiFormat( LogString, sizeof( LogString ), NewFormatString, Marker ); + VA_END (Marker); + + // + // Finally, add the string to the log. + // + AddStringToUnitTestLog( ((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString ); + + return; +} + +VOID +EFIAPI +UnitTestLogFailure( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, + ... +) +{ + CHAR16 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + VA_LIST Marker; + + + // + // Convert the message to an ASCII String + // + VA_START(Marker, Format); + UnicodeVSPrintAsciiFormat(LogString, sizeof(LogString), Format, Marker); + VA_END(Marker); + + // + // Finally, add the string to the log. + // + AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); + + return; +} + diff --git a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf new file mode 100644 index 00000000000..9726ad06eb0 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf @@ -0,0 +1,42 @@ +## @file +# Library to support Logging in the Unit Tests +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLogLib +FILE_GUID = D5F2DF71-6378-4E17-AE59-AE4109D34B5A +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestLogLib + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + PrintLib + PcdLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestLogLib.c + +[Pcd] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES + diff --git a/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c new file mode 100644 index 00000000000..fa65ad39462 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -0,0 +1,93 @@ +/** @file -- UnitTestNullPersistenceLib.c +This is an instance of the Unit Test Persistence Lib that does nothing. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include +#include + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + return FALSE; +} // DoesCacheExist() + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + return EFI_UNSUPPORTED; +} // SaveUnitTestCache() + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + return EFI_UNSUPPORTED; +} // LoadUnitTestCache() diff --git a/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf new file mode 100644 index 00000000000..3230c4ea337 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -0,0 +1,44 @@ +## @file UnitTestPersistenceLibNull.inf +# This is an instance of the Unit Test Persistence Lib does nothing. +# +# @copyright +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +# +# +# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibNull + FILE_GUID = B8553C7A-0B0B-4BBD-9DF3-825804BF26AB + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestPersistenceLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + UnitTestPersistenceLibNull.c + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec diff --git a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c new file mode 100644 index 00000000000..aacea4a79ad --- /dev/null +++ b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c @@ -0,0 +1,208 @@ +/** + +Implement UnitTestResultReportLib doing plain txt out to console + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include + + + +struct _UNIT_TEST_STATUS_STRING +{ + UNIT_TEST_STATUS Status; + CHAR8 *String; +}; + +struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = +{ + { UNIT_TEST_PASSED, "PASSED" }, + { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, + { UNIT_TEST_RUNNING, "RUNNING" }, + { UNIT_TEST_PENDING, "PENDING" } +}; +UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); +CHAR8 *mUnknownStatus = "**UNKNOWN**"; + +struct _UNIT_TEST_FAILURE_TYPE_STRING +{ + FAILURE_TYPE Type; + CHAR8 *String; +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= +{ + { FAILURETYPE_NOFAILURE, "NO FAILURE"}, + { FAILURETYPE_OTHER, "OTHER FAILURE" }, + { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, + { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, + { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, + { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } +}; +UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); +CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; + +//============================================================================= +// +// ---------------- TEST REPORTING FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForUnitTestStatus ( + IN UNIT_TEST_STATUS Status + ) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownStatus; + for (Index = 0; Index < mStatusStringsCount; Index++) + { + if (mStatusStrings[Index].Status == Status) + { + Result = mStatusStrings[Index].String; + break; + } + } + + return Result; +} + +STATIC +CONST CHAR8* +GetStringForFailureType( + IN FAILURE_TYPE Failure +) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownFailureType; + for (Index = 0; Index < mFailureTypeStringsCount; Index++) + { + if (mFailureTypeStrings[Index].Type == Failure) + { + Result = mFailureTypeStrings[Index].String; + break; + } + } + if (Result == mUnknownFailureType) + { + DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + } + + return Result; +} + +/* +Method to print the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + INTN Passed = 0; + INTN Failed = 0; + INTN NotRun = 0; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); + DEBUG((DEBUG_INFO, "------------- UNIT TEST FRAMEWORK RESULTS ---------------\n")); + DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); + + //print the version and time + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + UNIT_TEST_LIST_ENTRY *Test = NULL; + INTN SPassed = 0; + INTN SFailed = 0; + INTN SNotRun = 0; + + DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); + DEBUG((DEBUG_INFO, " SUITE: %s\n", Suite->UTS.Title)); + DEBUG((DEBUG_INFO, " PACKAGE: %s\n", Suite->UTS.Package)); + DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); + + // + // Iterate all tests within the suite + // + for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); + (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); + Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) + { + + DEBUG((DEBUG_INFO, "*********************************************************\n")); + DEBUG((DEBUG_INFO, " CLASS NAME: %s\n", Test->UT.ClassName)); + DEBUG((DEBUG_INFO, " TEST: %s\n", Test->UT.Description)); + DEBUG((DEBUG_INFO, " STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ))); + DEBUG((DEBUG_INFO, " FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType))); + DEBUG((DEBUG_INFO, " FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage)); + + if (Test->UT.Log != NULL) + { + DEBUG((DEBUG_INFO, " LOG:\n")); + // NOTE: This has to be done directly because all of the other + // "formatted" print statements have caps on the string size. + DEBUG((DEBUG_INFO, "%s", Test->UT.Log)); + } + + switch (Test->UT.Result) + { + case UNIT_TEST_PASSED: SPassed++; break; + case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; + case UNIT_TEST_PENDING: // Fall through... + case UNIT_TEST_RUNNING: // Fall through... + case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; + default: break; + } + DEBUG((DEBUG_INFO, "**********************************************************\n")); + } //End Test iteration + + DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); + DEBUG((DEBUG_INFO, "Suite Stats\n")); + DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun))); + DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun))); + DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun))); + DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); + + Passed += SPassed; //add to global counters + Failed += SFailed; //add to global counters + NotRun += SNotRun; //add to global coutners + }//End Suite iteration + + DEBUG((DEBUG_INFO, "=========================================================\n")); + DEBUG((DEBUG_INFO, "Total Stats\n")); + DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, "=========================================================\n")); + + return EFI_SUCCESS; +} \ No newline at end of file diff --git a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf new file mode 100644 index 00000000000..3c18cc7ceba --- /dev/null +++ b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf @@ -0,0 +1,34 @@ +## @file +# Library to support printing out the unit test report using printlib and conout +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestResultReportLibDebug +FILE_GUID = BED736D4-D197-475F-B7CE-0D828FF2C9A6 +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestResultReportLib + +[LibraryClasses] + DebugLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestResultReportLibDebug.c diff --git a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c new file mode 100644 index 00000000000..45ac05688a3 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c @@ -0,0 +1,208 @@ +/** + +Implement UnitTestResultReportLib doing plain txt out to console + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include + + + +struct _UNIT_TEST_STATUS_STRING +{ + UNIT_TEST_STATUS Status; + CHAR8 *String; +}; + +struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = +{ + { UNIT_TEST_PASSED, "PASSED" }, + { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, + { UNIT_TEST_RUNNING, "RUNNING" }, + { UNIT_TEST_PENDING, "PENDING" } +}; +UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); +CHAR8 *mUnknownStatus = "**UNKNOWN**"; + +struct _UNIT_TEST_FAILURE_TYPE_STRING +{ + FAILURE_TYPE Type; + CHAR8 *String; +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= +{ + { FAILURETYPE_NOFAILURE, "NO FAILURE"}, + { FAILURETYPE_OTHER, "OTHER FAILURE" }, + { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, + { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, + { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, + { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } +}; +UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); +CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; + +//============================================================================= +// +// ---------------- TEST REPORTING FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForUnitTestStatus ( + IN UNIT_TEST_STATUS Status + ) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownStatus; + for (Index = 0; Index < mStatusStringsCount; Index++) + { + if (mStatusStrings[Index].Status == Status) + { + Result = mStatusStrings[Index].String; + break; + } + } + + return Result; +} + +STATIC +CONST CHAR8* +GetStringForFailureType( + IN FAILURE_TYPE Failure +) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownFailureType; + for (Index = 0; Index < mFailureTypeStringsCount; Index++) + { + if (mFailureTypeStrings[Index].Type == Failure) + { + Result = mFailureTypeStrings[Index].String; + break; + } + } + if (Result == mUnknownFailureType) + { + DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + } + + return Result; +} + +/* +Method to print the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + INTN Passed = 0; + INTN Failed = 0; + INTN NotRun = 0; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + Print( L"---------------------------------------------------------\n" ); + Print( L"------------- UNIT TEST FRAMEWORK RESULTS ---------------\n" ); + Print( L"---------------------------------------------------------\n" ); + + //print the version and time + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + UNIT_TEST_LIST_ENTRY *Test = NULL; + INTN SPassed = 0; + INTN SFailed = 0; + INTN SNotRun = 0; + + Print( L"/////////////////////////////////////////////////////////\n" ); + Print( L" SUITE: %s\n", Suite->UTS.Title ); + Print( L" PACKAGE: %s\n", Suite->UTS.Package); + Print( L"/////////////////////////////////////////////////////////\n" ); + + // + // Iterate all tests within the suite + // + for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); + (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); + Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) + { + + Print (L"*********************************************************\n" ); + Print (L" CLASS NAME: %s\n", Test->UT.ClassName); + Print( L" TEST: %s\n", Test->UT.Description ); + Print( L" STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ) ); + Print( L" FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType)); + Print( L" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); + + if (Test->UT.Log != NULL) + { + Print( L" LOG:\n" ); + // NOTE: This has to be done directly because all of the other + // "formatted" print statements have caps on the string size. + gST->ConOut->OutputString( gST->ConOut, Test->UT.Log ); + } + + switch (Test->UT.Result) + { + case UNIT_TEST_PASSED: SPassed++; break; + case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; + case UNIT_TEST_PENDING: // Fall through... + case UNIT_TEST_RUNNING: // Fall through... + case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; + default: break; + } + Print( L"**********************************************************\n" ); + } //End Test iteration + + Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); + Print( L"Suite Stats\n" ); + Print( L" Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun) ); + Print( L" Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun) ); + Print( L" Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun) ); + Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); + + Passed += SPassed; //add to global counters + Failed += SFailed; //add to global counters + NotRun += SNotRun; //add to global coutners + }//End Suite iteration + + Print( L"=========================================================\n" ); + Print( L"Total Stats\n" ); + Print( L" Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun) ); + Print( L" Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun) ); + Print( L" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun) ); + Print( L"=========================================================\n" ); + + return EFI_SUCCESS; +} \ No newline at end of file diff --git a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf new file mode 100644 index 00000000000..a5e70997c50 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf @@ -0,0 +1,37 @@ +## @file +# Library to support printing out the unit test report using printlib and conout +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestResultReportLibPlainTextOutput +FILE_GUID = C659641D-BA1F-4B58-946E-B1E1103903F9 +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestResultReportLib|DXE_DRIVER UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + UefiLib + UefiBootServicesTableLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + + +[Sources] + UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md new file mode 100644 index 00000000000..9bb4f6484d9 --- /dev/null +++ b/UnitTestPkg/ReadMe.md @@ -0,0 +1,73 @@ +# Unit Test Support Package + +## About + +This package adds a unit test framework targeted at the UEFI shell environment. +It allows for unit test development to focus on the tests and leave, error logging, result formatting, +context persistance, and test running to the framework. The unit test framework works well for low +level unit tests as well as system level tests and fits easily in automation frameworks. + +The code is designed for a unit test application to leverage the framework which is made +up of a number of libraries which allow for easy customization of the different elements. +A few different instances are created to both show how easy some behaviors can be customized as +well as provide different implementations that support different use cases. + +### UnitTestLib + +The main "framework" library. This provides the framework init, suite init, and add test case +functionality. It also supports the running of the suites and logging/reporting of results. + +### UnitTestAssetLib + +The UnitTestAssetLib provides helper macros and functions for checking test conditions and +reporting errors. Status and error info will be logged into the test context. There are a number +of Assert macros that make the unit test code friendly to view and easy to understand. + + +### UnitTestBootLib + +One of the unique features of the unit test framework is to be able to save text context +and reboot the system. Since unit tests are generally run from a bootable usb key the framework +has library calls to set boot next for usb. There is numerous ways this could be done on a given +platform / BDS implementation and therefore this simple library allows customization if needed. +This package supplies two instances: + +* UsbClass Lib: This uses the Usb Class boot option as defined in the UEFI spec and leveraged +by industry standard USB applications. +* UsbMicrosoft Lib: This uses a private boot option found in Microsoft UEFI to boot to usb + +### UnitTestLogLib + +Library to support logging information during the test execution. This data is logged to the test +context and will be available in the test reporting phase. This should be used for logging test +details and helpful messages to resolve test failures. + +### UnitTestResultReportLib + +Library provides function to run at the end of a framework test run and handles formatting the report. This is a common customization point and allows the unit test framework to fit +its output reports into other test infrastructure. In this package a simple library instances has +been supplied to output test results to the console as plain text. + +### UnitTestPersistenceLib + +Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests +that require exiting the active process and then resuming state can be maintained. This is critical +in supporting a system reboot in the middle of a test run. + +## Samples + +There is a sample unit test provided as both an example of how to write a unit test and leverage +many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. + + +## Copyright + +Copyright (c) 2017, Microsoft Corporation + +All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: +1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + + \ No newline at end of file diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c new file mode 100644 index 00000000000..66b1c2af5ac --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -0,0 +1,213 @@ +/** @file -- SampleUnitTestApp.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ +#include +#include +#include +#include +#include +#include +#include + + +#define UNIT_TEST_APP_NAME L"Sample Unit Test Library Application" +#define UNIT_TEST_APP_VERSION L"0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestApp + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestApp ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + CHAR16 ShortName[100]; + ShortName[0] = L'\0'; + + UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); + DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, ShortName, UNIT_TEST_APP_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Fw ); + +EXIT: + if (Fw) + { + FreeUnitTestFramework( Fw ); + } + + return Status; +} \ No newline at end of file diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf new file mode 100644 index 00000000000..9b7e0d9e6e3 --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -0,0 +1,42 @@ +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestApp + FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = SampleUnitTestApp + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestApp.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + + + + diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c new file mode 100644 index 00000000000..7c94e20e70f --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -0,0 +1,215 @@ +/** @file -- SampleUnitTestPeim.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include +#include +#include +#include + + +#define UNIT_TEST_PEIM_NAME L"Sample Unit Test Library PEIM" +#define UNIT_TEST_PEIM_VERSION L"0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestPeim + + @param FileHandle Handle of the file being invoked. Type + EFI_PEI_FILE_HANDLE is defined in + FfsFindNextFile(). + @param PeiServices Describes the list of possible PEI Services. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestPeim ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + CHAR16 ShortName[100]; + ShortName[0] = L'\0'; + + UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); + DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Fw, UNIT_TEST_PEIM_NAME, ShortName, UNIT_TEST_PEIM_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Fw ); + +EXIT: + if (Fw) + { + FreeUnitTestFramework( Fw ); + } + + return Status; +} \ No newline at end of file diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf new file mode 100644 index 00000000000..e9677d79bc1 --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -0,0 +1,42 @@ +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestPeim + FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = SampleUnitTestPeim + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestPeim.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + PeimEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + +[Depex] + gEfiPeiMemoryDiscoveredPpiGuid + diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c new file mode 100644 index 00000000000..c439aabc37b --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -0,0 +1,213 @@ +/** @file -- SampleUnitTestSmm.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include +#include +#include +#include + + +#define UNIT_TEST_SMM_NAME L"Sample Unit Test Library SMM" +#define UNIT_TEST_SMM_VERSION L"0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestSmm + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestSmm ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + CHAR16 ShortName[100]; + ShortName[0] = L'\0'; + + UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); + DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Fw, UNIT_TEST_SMM_NAME, ShortName, UNIT_TEST_SMM_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Fw ); + +EXIT: + if (Fw) + { + FreeUnitTestFramework( Fw ); + } + + return Status; +} \ No newline at end of file diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf new file mode 100644 index 00000000000..9fad2c994ce --- /dev/null +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -0,0 +1,43 @@ +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestSmm + FILE_GUID = 389B16DB-F622-424C-9000-9E43C69CBF71 + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + PI_SPECIFICATION_VERSION = 0x0001000A + ENTRY_POINT = SampleUnitTestSmm + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestSmm.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + UefiDriverEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + +[Depex] + gEfiSmmCpuProtocolGuid + diff --git a/UnitTestPkg/UnitTestPkg.dec b/UnitTestPkg/UnitTestPkg.dec new file mode 100644 index 00000000000..1197e78982d --- /dev/null +++ b/UnitTestPkg/UnitTestPkg.dec @@ -0,0 +1,62 @@ +## @file UnitTestPkg.dec +# +# This Package provides all definitions(including functions, MACROs, structures and library classes) +# and libraries instances, which are used to support Unit Testing and Interface testing +# +# Copyright (c) 2017, Microsoft Corporation. All rights reserved. +# +# +## + + +[Defines] + DEC_SPECIFICATION = 0x00010005 + PACKAGE_NAME = UnitTestPkg + PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 + PACKAGE_VERSION = 1.00 + + +[Includes] + Include + +[LibraryClasses] + + ## @libraryclass Provides a unit test framework + # + UnitTestLib|Include\Library\UnitTestLib.h + + ## @libraryclass Provide unit test assert helpers + # + UnitTestAssertLib|Include\Library\UnitTestAssertLib.h + + ## @libraryclass Provide unit test logging + # + UnitTestLogLib|Include\Library\UnitTestLogLib.h + + ## @libraryclass Provides a unit test result report + # + UnitTestResultReportLib|Include\Library\UnitTestResultReportLib.h + + ## @libraryclass Allows the platform to boot from a specific device on the next boot. + # + UnitTestBootLib|Include\Library\UnitTestBootLib.h + + ## @libraryclass Allows save and restore unit test internal state + # + UnitTestPersistenceLib|Include\Library\UnitTestPersistenceLib.h + +[Guids] + + gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } + +[Ppis] + +[Protocols] + +[PcdsFeatureFlag] + +[PcdsDynamic, PcdsDynamicEx] + +[PcdsFixedAtBuild] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 + \ No newline at end of file diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestPkg/UnitTestPkg.dsc new file mode 100644 index 00000000000..7237f04cd61 --- /dev/null +++ b/UnitTestPkg/UnitTestPkg.dsc @@ -0,0 +1,191 @@ +## @file +# UnitTestPkg +# +# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = UnitTestPkg + PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 + PLATFORM_VERSION = 1.00 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/UnitTestPkg + SUPPORTED_ARCHITECTURES = IA32|IPF|X64|EBC|ARM|AARCH64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT + +################################################################################################### +# +# Components Section - list of the modules and components that will be processed by compilation +# tools and the EDK II tools to generate PE32/PE32+/Coff image files. +# +# Note: The EDK II DSC file is not used to specify how compiled binary images get placed +# into firmware volume images. This section is just a list of modules to compile from +# source into UEFI-compliant binaries. +# It is the FDF file that contains information on combining binary files into firmware +# volume images, whose concept is beyond UEFI and is described in PI specification. +# Binary modules do not need to be listed in this section, as they should be +# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), +# Logo (Logo.bmp), and etc. +# There may also be modules listed in this section that are not required in the FDF file, +# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be +# generated for it, but the binary will not be put into any firmware volume. +# +################################################################################################### + +[LibraryClasses] + # + # Entry point + # + PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf + PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf + DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + # + # Basic + # + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf + PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf + PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf + PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf + CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf + PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf + PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf + SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf + # + # UEFI & PI + # + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf + UefiLib|MdePkg/Library/UefiLib/UefiLib.inf + UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf + PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf + DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf + SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf + UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + # + # Generic Modules + # + UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf + UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf + NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf + IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf + UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf + TcpIoLib|MdeModulePkg/Library/DxeTcpIoLib/DxeTcpIoLib.inf + DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf + SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf + TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf + SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf + FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf + # + # Misc + # + DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf + PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf + ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + ResetUtilityLib|MdeModulePkg/Library/ResetUtilityLib/ResetUtilityLib.inf ## MS_CHANGE + HwResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf ## MS_CHANGE + SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf + S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf + CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf + PlatformBootManagerLib|MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf + PciHostBridgeLib|MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf + TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf + AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf + VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf + + # + # Shell + # + ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf + ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf + ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf + HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf + +[LibraryClasses.common.PEIM] + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf + +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + +[LibraryClasses.common.DXE_SMM_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf + MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf + + # + # UnitTestPkg + # +[LibraryClasses] + UnitTestAssertLib|UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestLogLib|UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf + +[LibraryClasses.common.PEIM] + UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf + UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + +[LibraryClasses.common.DXE_SMM_DRIVER] + UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf + UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf + UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + +[Components] + UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf + UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf + UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf + UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestPkg/Library/UnitTestBootLibMicrosoftUsb/UnitTestBootLibMicrosoftUsb.inf + UnitTestPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf + UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf + UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf + +[BuildOptions] + *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES + MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE + MSFT:NOOPT_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE + MSFT:RELEASE_*_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 From 74403549bcdb6aab1417c590c476c4f0c660c8a6 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 18 Nov 2019 15:55:07 -0800 Subject: [PATCH 122/384] Silence a build warning. --- .../Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf | 1 + 1 file changed, 1 insertion(+) diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf index 631bdbce06e..7bc63699c46 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf @@ -40,6 +40,7 @@ [Sources] TestBaseSafeIntLib.c + TestBaseSafeIntLib.h [Sources.Ia32] IA32/SafeIntLibUintnIntnUnitTests.c From 75310669fb7e01e24f4288a7520d9759da9312de Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 13:02:40 -0800 Subject: [PATCH 123/384] Update DEC and DSC to match the new package divisions. --- UnitTestPkg/UnitTestPkg.dec | 20 ++++++++------------ UnitTestPkg/UnitTestPkg.dsc | 10 +++------- 2 files changed, 11 insertions(+), 19 deletions(-) diff --git a/UnitTestPkg/UnitTestPkg.dec b/UnitTestPkg/UnitTestPkg.dec index 1197e78982d..6de181e720c 100644 --- a/UnitTestPkg/UnitTestPkg.dec +++ b/UnitTestPkg/UnitTestPkg.dec @@ -21,30 +21,26 @@ [LibraryClasses] - ## @libraryclass Provides a unit test framework - # - UnitTestLib|Include\Library\UnitTestLib.h - ## @libraryclass Provide unit test assert helpers # UnitTestAssertLib|Include\Library\UnitTestAssertLib.h - ## @libraryclass Provide unit test logging - # - UnitTestLogLib|Include\Library\UnitTestLogLib.h - - ## @libraryclass Provides a unit test result report + ## @libraryclass Provides a unit test framework # - UnitTestResultReportLib|Include\Library\UnitTestResultReportLib.h + UnitTestLib|Include\Library\UnitTestLib.h - ## @libraryclass Allows the platform to boot from a specific device on the next boot. + ## @libraryclass Provide unit test logging # - UnitTestBootLib|Include\Library\UnitTestBootLib.h + UnitTestLogLib|Include\Library\UnitTestLogLib.h ## @libraryclass Allows save and restore unit test internal state # UnitTestPersistenceLib|Include\Library\UnitTestPersistenceLib.h + ## @libraryclass Provides a unit test result report + # + UnitTestResultReportLib|Include\Library\UnitTestResultReportLib.h + [Guids] gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestPkg/UnitTestPkg.dsc index 7237f04cd61..db6da8ea3f3 100644 --- a/UnitTestPkg/UnitTestPkg.dsc +++ b/UnitTestPkg/UnitTestPkg.dsc @@ -168,18 +168,14 @@ UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf [Components] + UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf - UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestPkg/Library/UnitTestBootLibMicrosoftUsb/UnitTestBootLibMicrosoftUsb.inf - UnitTestPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf From abfeabfd16078242c67de78b9259cbcbb3cbd6e9 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 13:31:54 -0800 Subject: [PATCH 124/384] Fix some problems introduced by the package split. --- MdePkg/MdePkg.ci.yaml | 3 ++- MdePkg/MdePkgTest.dsc | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index e5aafd9697a..10db2312572 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -23,7 +23,8 @@ ## options defined ci/Plugin/DependencyCheck "DependencyCheck": { "AcceptableDependencies": [ - "MdePkg/MdePkg.dec" + "MdePkg/MdePkg.dec", + "UnitTestPkg/UnitTestPkg.dec" ], # For host based unit tests "AcceptableDependencies-HOST_APPLICATION":[], diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/MdePkgTest.dsc index 92c0a4bb35d..2c4206e23a9 100644 --- a/MdePkg/MdePkgTest.dsc +++ b/MdePkg/MdePkgTest.dsc @@ -22,7 +22,7 @@ BaseMemoryLib|MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf DebugLib|MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf MemoryAllocationLib|MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - OsServiceLib|UnitTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf + OsServiceLib|HostBasedUnitTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf From 6f9bd48ab1954672abe8af2f4c5d0317e4e9858f Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 14:02:59 -0800 Subject: [PATCH 125/384] Pivot to the smaller test repo. --- .pytool/CISettings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index d9b8aa97d33..78d49ce0c6c 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -151,7 +151,7 @@ def GetDependencies(self): return [ { "Path": "EDK2_TEST", - "Url": "https://github.com/corthon/edk2-test-1.git", + "Url": "https://github.com/corthon/edk2-test.git", "Branch": "edk2-host-test_v2" } ] From 81f1e79ca934fd970f7d32d110dc3303dd081845 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 14:51:58 -0800 Subject: [PATCH 126/384] Get all but one problem resolved when building simple unit tests. --- .pytool/CISettings.py | 3 ++- UnitTestPkg/UnitTestPkg.ci.yaml | 48 +++++++++++++++++++++++++++++++++ UnitTestPkg/UnitTestPkg.dec | 10 +++---- UnitTestPkg/UnitTestPkg.dsc | 29 ++++++++++---------- 4 files changed, 70 insertions(+), 20 deletions(-) create mode 100644 UnitTestPkg/UnitTestPkg.ci.yaml diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 78d49ce0c6c..37331b44eef 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -49,7 +49,8 @@ def GetPackagesSupported(self): "FmpDevicePkg", "ShellPkg", "FatPkg", - "CryptoPkg" + "CryptoPkg", + "UnitTestPkg" ) def GetArchitecturesSupported(self): diff --git a/UnitTestPkg/UnitTestPkg.ci.yaml b/UnitTestPkg/UnitTestPkg.ci.yaml new file mode 100644 index 00000000000..2a78b3211ad --- /dev/null +++ b/UnitTestPkg/UnitTestPkg.ci.yaml @@ -0,0 +1,48 @@ +## @file +# CI configuration for UnitTestPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "UnitTestPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "UnitTestPkg/UnitTestPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "UnitTestPkg.dsc", + "IgnoreInf": [ + ] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} diff --git a/UnitTestPkg/UnitTestPkg.dec b/UnitTestPkg/UnitTestPkg.dec index 6de181e720c..3c8a3bd843b 100644 --- a/UnitTestPkg/UnitTestPkg.dec +++ b/UnitTestPkg/UnitTestPkg.dec @@ -23,23 +23,23 @@ ## @libraryclass Provide unit test assert helpers # - UnitTestAssertLib|Include\Library\UnitTestAssertLib.h + UnitTestAssertLib|Include/Library/UnitTestAssertLib.h ## @libraryclass Provides a unit test framework # - UnitTestLib|Include\Library\UnitTestLib.h + UnitTestLib|Include/Library/UnitTestLib.h ## @libraryclass Provide unit test logging # - UnitTestLogLib|Include\Library\UnitTestLogLib.h + UnitTestLogLib|Include/Library/UnitTestLogLib.h ## @libraryclass Allows save and restore unit test internal state # - UnitTestPersistenceLib|Include\Library\UnitTestPersistenceLib.h + UnitTestPersistenceLib|Include/Library/UnitTestPersistenceLib.h ## @libraryclass Provides a unit test result report # - UnitTestResultReportLib|Include\Library\UnitTestResultReportLib.h + UnitTestResultReportLib|Include/Library/UnitTestResultReportLib.h [Guids] diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestPkg/UnitTestPkg.dsc index db6da8ea3f3..cef75818284 100644 --- a/UnitTestPkg/UnitTestPkg.dsc +++ b/UnitTestPkg/UnitTestPkg.dsc @@ -82,11 +82,6 @@ # UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf - NetLib|MdeModulePkg/Library/DxeNetLib/DxeNetLib.inf - IpIoLib|MdeModulePkg/Library/DxeIpIoLib/DxeIpIoLib.inf - UdpIoLib|MdeModulePkg/Library/DxeUdpIoLib/DxeUdpIoLib.inf - TcpIoLib|MdeModulePkg/Library/DxeTcpIoLib/DxeTcpIoLib.inf - DpcLib|MdeModulePkg/Library/DxeDpcLib/DxeDpcLib.inf SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf @@ -141,6 +136,20 @@ HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + # + # It is not possible to prevent ARM compiler calls to generic intrinsic functions. + # This library provides the instrinsic functions generated by a given compiler. + # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. + # + NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf + + # + # Since software stack checking may be heuristically enabled by the compiler + # include BaseStackCheckLib unconditionally. + # + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf # # UnitTestPkg @@ -148,24 +157,19 @@ [LibraryClasses] UnitTestAssertLib|UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestLogLib|UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.PEIM] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.DXE_SMM_DRIVER] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestBootLib|UnitTestPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf [Components] UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf @@ -182,6 +186,3 @@ [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES - MSFT:DEBUG_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE - MSFT:NOOPT_*_*_DLINK_FLAGS = /EXPORT:InitializeDriver=$(IMAGE_ENTRY_POINT) /BASE:0x10000 /ALIGN:4096 /FILEALIGN:4096 /SUBSYSTEM:CONSOLE - MSFT:RELEASE_*_*_DLINK_FLAGS = /ALIGN:4096 /FILEALIGN:4096 From f6f1022cae8e5b8d87b849a1b99625502154ea58 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 15:51:02 -0800 Subject: [PATCH 127/384] Need to clean some build errors, but this is the future. --- .../Include/Library/UnitTestTerminationLib.h | 43 +++++++++++++++++ UnitTestPkg/Library/UnitTestLib/UnitTestLib.c | 37 ++------------- .../Library/UnitTestLib/UnitTestLibDxe.inf | 3 +- .../Library/UnitTestLib/UnitTestLibDxeStub.c | 30 ------------ .../Library/UnitTestLib/UnitTestLibPei.inf | 3 +- .../Library/UnitTestLib/UnitTestLibPeiStub.c | 28 ----------- .../Library/UnitTestLib/UnitTestLibSmm.inf | 3 +- .../Library/UnitTestLib/UnitTestLibSmmStub.c | 28 ----------- .../UnitTestTerminationLibDxe.c | 46 +++++++++++++++++++ .../UnitTestTerminationLibDxe.inf | 35 ++++++++++++++ .../UnitTestTerminationLibTbd.c | 45 ++++++++++++++++++ .../UnitTestTerminationLibTbd.inf | 31 +++++++++++++ UnitTestPkg/UnitTestPkg.dec | 5 ++ UnitTestPkg/UnitTestPkg.dsc | 3 ++ 14 files changed, 215 insertions(+), 125 deletions(-) create mode 100644 UnitTestPkg/Include/Library/UnitTestTerminationLib.h delete mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c delete mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c delete mode 100644 UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c create mode 100644 UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c create mode 100644 UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf create mode 100644 UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c create mode 100644 UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf diff --git a/UnitTestPkg/Include/Library/UnitTestTerminationLib.h b/UnitTestPkg/Include/Library/UnitTestTerminationLib.h new file mode 100644 index 00000000000..c22de0ca842 --- /dev/null +++ b/UnitTestPkg/Include/Library/UnitTestTerminationLib.h @@ -0,0 +1,43 @@ +/** @file -- UnitTestTerminationLib.h +This library abstracts the methods that a test could exit prematurely. +It allows tests written for different contexts to handle Quit()/Reboot() differently. + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _UNIT_TEST_TERMINATION_LIB_H_ +#define _UNIT_TEST_TERMINATION_LIB_H_ + + +/** + Specific function to take steps to quit the test in progress immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkExit ( + VOID + ); + +/** + Specific function to take steps to reboot the test machine immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ); + + +#endif // _UNIT_TEST_TERMINATION_LIB_H_ diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c index 1021e7510cb..a3ca011fd22 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c @@ -1,8 +1,9 @@ /** - Implement UnitTestLib -Copyright (c) Microsoft +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + **/ #include @@ -11,26 +12,16 @@ Copyright (c) Microsoft #include #include #include -#include #include #include #include #include +#include #include "Md5.h" MD5_CTX mFingerprintCtx; -VOID -FrameworkExit ( - VOID - ); - -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ); - // Prototyped here so that it can be included near the functions that // it logically goes with. STATIC @@ -941,12 +932,6 @@ SaveFrameworkStateAndReboot ( // If we're all good, let's book... if (!EFI_ERROR( Status )) { - // - // Next, we want to update the BootNext variable to the device - // so that we have a fighting chance of coming back here. - // - SetBootNextDevice(); - // // Free data that was used. FreeUnitTestFramework( (UNIT_TEST_FRAMEWORK*)FrameworkHandle ); @@ -963,17 +948,3 @@ SaveFrameworkStateAndReboot ( return Status; } // SaveFrameworkStateAndReboot() - -/** - Set the boot manager to boot from a specific device on the next boot. - This should be set only for the next boot and shouldn't - require any manual clean up -**/ -EFI_STATUS -EFIAPI -SetFrameworkBootNextDevice ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - return SetBootNextDevice(); -} // SaveFrameworkStateAndReboot() \ No newline at end of file diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf index d130859bfc0..f29ff0cd2e4 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf @@ -28,8 +28,8 @@ LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION UefiLib UnitTestLogLib UnitTestPersistenceLib - UnitTestBootLib UnitTestResultReportLib + UnitTestTerminationLib [Packages] @@ -42,5 +42,4 @@ LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION [Sources] UnitTestLib.c - UnitTestLibDxeStub.c Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c deleted file mode 100644 index 4ea06867db3..00000000000 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxeStub.c +++ /dev/null @@ -1,30 +0,0 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include -#include - -VOID -FrameworkExit ( - VOID - ) -{ - gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); -} - -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); -} - diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf index d9de48391d4..e9cdce949d6 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -26,8 +26,8 @@ LIBRARY_CLASS = UnitTestLib|PEIM BaseLib UnitTestLogLib UnitTestPersistenceLib - UnitTestBootLib UnitTestResultReportLib + UnitTestTerminationLib [Packages] @@ -40,5 +40,4 @@ LIBRARY_CLASS = UnitTestLib|PEIM [Sources] UnitTestLib.c - UnitTestLibPeiStub.c Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c deleted file mode 100644 index fc4fd926403..00000000000 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPeiStub.c +++ /dev/null @@ -1,28 +0,0 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include - -VOID -FrameworkExit ( - VOID - ) -{ - // TBD -} - -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - // TBD -} - diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf index d589bf4f6c8..f5870c545f8 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf @@ -27,8 +27,8 @@ LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER BaseLib UnitTestLogLib UnitTestPersistenceLib - UnitTestBootLib UnitTestResultReportLib + UnitTestTerminationLib [Packages] @@ -41,5 +41,4 @@ LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER [Sources] UnitTestLib.c - UnitTestLibSmmStub.c Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c deleted file mode 100644 index d71ffb605a3..00000000000 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmmStub.c +++ /dev/null @@ -1,28 +0,0 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include - -VOID -FrameworkExit ( - VOID - ) -{ - // TBD -} - -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - // TBD -} - diff --git a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c new file mode 100644 index 00000000000..9651007d650 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c @@ -0,0 +1,46 @@ +/** @file -- UnitTestTerminationLibDxe.c +DXE Driver-/Application-specific methods of exiting a test. + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include + + +/** + Specific function to take steps to quit the test in progress immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkExit ( + VOID + ) +{ + gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); +} // FrameworkExit() + +/** + Specific function to take steps to reboot the test machine immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); +} // FrameworkResetSystem() diff --git a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf new file mode 100644 index 00000000000..f6dd569a7fb --- /dev/null +++ b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf @@ -0,0 +1,35 @@ +## @file UnitTestTerminationLibDxe.inf +# DXE Driver-/Application-specific methods of exiting a test. +# +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestTerminationLibDxe + FILE_GUID = 85A01B72-6270-42B0-A349-7170CC6AC2AF + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = UnitTestTerminationLib|DXE_DRIVER UEFI_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + + +[Sources] + UnitTestTerminationLibDxe.c + + +[Packages] + MdePkg/MdePkg.dec + + +[LibraryClasses] + UefiBootServicesTableLib + UefiRuntimeServicesTableLib diff --git a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c new file mode 100644 index 00000000000..9afd38cf302 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c @@ -0,0 +1,45 @@ +/** @file -- UnitTestTerminationLibTbd.c +This is an invalid implementation of this lib while we figure out what +best to do in difficult contexts. + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + + +/** + Specific function to take steps to quit the test in progress immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkExit ( + VOID + ) +{ + // TBD +} // FrameworkExit() + +/** + Specific function to take steps to reboot the test machine immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + // TBD +} // FrameworkResetSystem() diff --git a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf new file mode 100644 index 00000000000..4e2a7e7c492 --- /dev/null +++ b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf @@ -0,0 +1,31 @@ +## @file UnitTestTerminationLibTbd.inf +# This is an invalid implementation of this lib while we figure out what +# best to do in difficult contexts. +# +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestTerminationLibTbd + FILE_GUID = DFD5BB45-A030-4182-BB93-F4697DCF4577 + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestTerminationLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + + +[Sources] + UnitTestTerminationLibTbd.c + + +[Packages] + MdePkg/MdePkg.dec diff --git a/UnitTestPkg/UnitTestPkg.dec b/UnitTestPkg/UnitTestPkg.dec index 3c8a3bd843b..69e2b7224c3 100644 --- a/UnitTestPkg/UnitTestPkg.dec +++ b/UnitTestPkg/UnitTestPkg.dec @@ -41,6 +41,11 @@ # UnitTestResultReportLib|Include/Library/UnitTestResultReportLib.h + ## @libraryclass Abstracts the methods that a test could exit prematurely. + # Allows tests written for different contexts to handle Quit()/Reboot() differently. + # + UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h + [Guids] gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestPkg/UnitTestPkg.dsc index cef75818284..d2bc9e18c20 100644 --- a/UnitTestPkg/UnitTestPkg.dsc +++ b/UnitTestPkg/UnitTestPkg.dsc @@ -162,14 +162,17 @@ [LibraryClasses.common.PEIM] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf [LibraryClasses.common.DXE_SMM_DRIVER] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf [Components] UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf From ba2d5c8c5c6b4e486d9974d859f566b49ec405c7 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 19 Nov 2019 17:02:53 -0800 Subject: [PATCH 128/384] Get all CI on UnitTestPkg working. --- .azurepipelines/templates/pr-gate-build-job.yml | 4 ++-- .../UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c | 2 +- .../UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c | 2 +- UnitTestPkg/UnitTestPkg.dsc | 2 ++ 4 files changed, 6 insertions(+), 4 deletions(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index c7cada71360..fe8a2d80bb0 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -35,8 +35,8 @@ jobs: TARGET_OTHER: Build.Pkgs: 'PcAtChipsetPkg,ShellPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET' - TARGET_FMP: - Build.Pkgs: 'FmpDevicePkg,FatPkg' + TARGET_FMP_FAT_TEST: + Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET' TARGET_CRYPTO: Build.Pkgs: 'CryptoPkg' diff --git a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c index 9651007d650..eb051c57889 100644 --- a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c +++ b/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c @@ -6,7 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include +#include #include #include diff --git a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c index 9afd38cf302..7f8b3697032 100644 --- a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c +++ b/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c @@ -7,7 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include +#include /** diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestPkg/UnitTestPkg.dsc index d2bc9e18c20..e18dee053f4 100644 --- a/UnitTestPkg/UnitTestPkg.dsc +++ b/UnitTestPkg/UnitTestPkg.dsc @@ -183,6 +183,8 @@ UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf + UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf From 7607174192166dd5d2d6913fc2fdb8ce539cd3c9 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 3 Sep 2019 16:52:26 -0700 Subject: [PATCH 129/384] MdeModulePkg/NvmExpressDxe: Fix wrong queue size for async IO queues REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2118 When a packet is queued/completed for the asynchronous IO queue, the logic to roll over to the front of the queue doesn't account for actual size of the IO Submission/Completion queue. This causes a device to hang due to doorbell being outside of visible queue. An example would be if an NVMe drive only supported a queue size of 128 while the driver supports 256. Cc: Jian J Wang Signed-off-by: Sean Brogan Signed-off-by: Hao A Wu Acked-by: Ray Ni --- MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c | 2 +- MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c | 6 ++++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c index 3bde96bc957..62886d5c91f 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpress.c @@ -672,7 +672,7 @@ ProcessAsyncTaskList ( } Private->CqHdbl[QueueId].Cqh++; - if (Private->CqHdbl[QueueId].Cqh > NVME_ASYNC_CCQ_SIZE) { + if (Private->CqHdbl[QueueId].Cqh > MIN (NVME_ASYNC_CCQ_SIZE, Private->Cap.Mqes)) { Private->CqHdbl[QueueId].Cqh = 0; Private->Pt[QueueId] ^= 1; } diff --git a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c index 8e721379466..e9357b1239c 100644 --- a/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c +++ b/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressPassthru.c @@ -452,6 +452,7 @@ NvmExpressPassThru ( NVME_SQ *Sq; NVME_CQ *Cq; UINT16 QueueId; + UINT16 QueueSize; UINT32 Bytes; UINT16 Offset; EFI_EVENT TimerEvent; @@ -540,6 +541,7 @@ NvmExpressPassThru ( Prp = NULL; TimerEvent = NULL; Status = EFI_SUCCESS; + QueueSize = MIN (NVME_ASYNC_CSQ_SIZE, Private->Cap.Mqes) + 1; if (Packet->QueueType == NVME_ADMIN_QUEUE) { QueueId = 0; @@ -552,7 +554,7 @@ NvmExpressPassThru ( // // Submission queue full check. // - if ((Private->SqTdbl[QueueId].Sqt + 1) % (NVME_ASYNC_CSQ_SIZE + 1) == + if ((Private->SqTdbl[QueueId].Sqt + 1) % QueueSize == Private->AsyncSqHead) { return EFI_NOT_READY; } @@ -701,7 +703,7 @@ NvmExpressPassThru ( // if ((Event != NULL) && (QueueId != 0)) { Private->SqTdbl[QueueId].Sqt = - (Private->SqTdbl[QueueId].Sqt + 1) % (NVME_ASYNC_CSQ_SIZE + 1); + (Private->SqTdbl[QueueId].Sqt + 1) % QueueSize; } else { Private->SqTdbl[QueueId].Sqt ^= 1; } From bf1ea933ec1c6447c4168c34cc1b7ea4ac8f3e4d Mon Sep 17 00:00:00 2001 From: "Fan, ZhijuX" Date: Thu, 14 Nov 2019 09:27:42 +0800 Subject: [PATCH 130/384] BaseTools:Add [packages] section in dsc file BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2270 Currently a PCD (e.g. FeaturePCD) cannot be used in a conditional statement in a DSC/FDF file without a module in the build referencing the PCD package DEC file. An example implementation that to support this is to allow a [Packages] section in the DSC file to list additional package dependencies for PCD references in the package DSC/FDF files. this patch is going to add the ability to have the [packages] section defined in the DSC file Cc: Liming Gao Cc: Bob Feng Signed-off-by: Zhiju.Fan Acked-by: Liming Gao Reviewed-by: Bob Feng --- .../Source/Python/AutoGen/ModuleAutoGen.py | 29 +++++++++++++++---- .../Source/Python/AutoGen/PlatformAutoGen.py | 1 + .../Source/Python/AutoGen/WorkspaceAutoGen.py | 1 + BaseTools/Source/Python/Common/DataType.py | 1 + .../Source/Python/Workspace/DscBuildData.py | 23 ++++++++++++++- .../Source/Python/Workspace/MetaFileParser.py | 14 +++++++++ .../Python/Workspace/WorkspaceCommon.py | 2 ++ .../Python/Workspace/WorkspaceDatabase.py | 4 +++ 8 files changed, 68 insertions(+), 7 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index f0812b6887b..e6d6c43810e 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -462,14 +462,31 @@ def MakeFileDir(self): def BuildCommand(self): return self.PlatformInfo.BuildCommand - ## Get object list of all packages the module and its dependent libraries belong to + ## Get Module package and Platform package + # + # @retval list The list of package object + # + @cached_property + def PackageList(self): + PkagList = [] + if self.Module.Packages: + PkagList.extend(self.Module.Packages) + Platform = self.BuildDatabase[self.PlatformInfo.MetaFile, self.Arch, self.BuildTarget, self.ToolChain] + for Package in Platform.Packages: + if Package in PkagList: + continue + PkagList.append(Package) + return PkagList + + ## Get object list of all packages the module and its dependent libraries belong to and the Platform depends on # # @retval list The list of package object # @cached_property def DerivedPackageList(self): PackageList = [] - for M in [self.Module] + self.DependentLibraryList: + PackageList.extend(self.PackageList) + for M in self.DependentLibraryList: for Package in M.Packages: if Package in PackageList: continue @@ -938,13 +955,13 @@ def FileTypes(self): self.Targets return self._FileTypes - ## Get the list of package object the module depends on + ## Get the list of package object the module depends on and the Platform depends on # # @retval list The package object list # @cached_property def DependentPackageList(self): - return self.Module.Packages + return self.PackageList ## Return the list of auto-generated code file # @@ -1101,7 +1118,7 @@ def IncludePathList(self): RetVal.append(self.MetaFile.Dir) RetVal.append(self.DebugDir) - for Package in self.Module.Packages: + for Package in self.PackageList: PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir) if PackageDir not in RetVal: RetVal.append(PackageDir) @@ -1125,7 +1142,7 @@ def IncludePathLength(self): @cached_property def PackageIncludePathList(self): IncludesList = [] - for Package in self.Module.Packages: + for Package in self.PackageList: PackageDir = mws.join(self.WorkspaceDir, Package.MetaFile.Dir) IncludesList = Package.Includes if Package._PrivateIncludes: diff --git a/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py b/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py index debeb46f585..4c3cdf82d57 100644 --- a/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py @@ -975,6 +975,7 @@ def PackageList(self): continue ModuleData = self.BuildDatabase[ModuleFile, self.Arch, self.BuildTarget, self.ToolChain] RetVal.update(ModuleData.Packages) + RetVal.update(self.Platform.Packages) return list(RetVal) @cached_property diff --git a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py index 9d8040905ea..fde48b4b278 100644 --- a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py @@ -420,6 +420,7 @@ def PkgSet(self): continue ModuleData = self.BuildDatabase[ModuleFile, Arch, self.BuildTarget, self.ToolChain] PkgSet.update(ModuleData.Packages) + PkgSet.update(Platform.Packages) Pkgs[Arch] = list(PkgSet) return Pkgs diff --git a/BaseTools/Source/Python/Common/DataType.py b/BaseTools/Source/Python/Common/DataType.py index 5d49afb0a92..8d80b410892 100644 --- a/BaseTools/Source/Python/Common/DataType.py +++ b/BaseTools/Source/Python/Common/DataType.py @@ -519,6 +519,7 @@ PCDS_DYNAMICEX_VPD.upper(), PCDS_DYNAMICEX_HII.upper(), TAB_BUILD_OPTIONS.upper(), + TAB_PACKAGES.upper(), TAB_INCLUDES.upper()} # diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/Source/Python/Workspace/DscBuildData.py index 9192077f906..03a15bbf3e1 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -719,6 +719,24 @@ def OverrideDuplicateModule(self): self._RawData.DisableOverrideComponent(Components[(file_guid_str,str(ModuleFile))]) Components[(file_guid_str,str(ModuleFile))] = ModuleId self._RawData._PostProcessed = False + + ## Retrieve packages this Platform depends on + @cached_property + def Packages(self): + RetVal = set() + RecordList = self._RawData[MODEL_META_DATA_PACKAGE, self._Arch] + Macros = self._Macros + for Record in RecordList: + File = PathClass(NormPath(Record[0], Macros), GlobalData.gWorkspace, Arch=self._Arch) + # check the file validation + ErrorCode, ErrorInfo = File.Validate('.dec') + if ErrorCode != 0: + LineNo = Record[-1] + EdkLogger.error('build', ErrorCode, ExtraData=ErrorInfo, File=self.MetaFile, Line=LineNo) + # parse this package now. we need it to get protocol/ppi/guid value + RetVal.add(self._Bdb[File, self._Arch, self._Target, self._Toolchain]) + return RetVal + ## Retrieve [Components] section information @property def Modules(self): @@ -896,7 +914,8 @@ def _ValidatePcd(self, PcdCName, TokenSpaceGuid, Setting, PcdType, LineNo): continue ModuleData = self._Bdb[ModuleFile, self._Arch, self._Target, self._Toolchain] PkgSet.update(ModuleData.Packages) - + if self.Packages: + PkgSet.update(self.Packages) self._DecPcds, self._GuidDict = GetDeclaredPcd(self, self._Bdb, self._Arch, self._Target, self._Toolchain, PkgSet) self._GuidDict.update(GlobalData.gPlatformPcds) @@ -3320,6 +3339,8 @@ def DecPcds(self): continue ModuleData = self._Bdb[ModuleFile, self._Arch, self._Target, self._Toolchain] PkgSet.update(ModuleData.Packages) + if self.Packages: + PkgSet.update(self.Packages) self._DecPcds, self._GuidDict = GetDeclaredPcd(self, self._Bdb, self._Arch, self._Target, self._Toolchain, PkgSet) self._GuidDict.update(GlobalData.gPlatformPcds) return self._DecPcds diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTools/Source/Python/Workspace/MetaFileParser.py index 0a131fc7698..8a665b118ec 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -160,6 +160,7 @@ def __init__(self, FilePath, FileType, Arch, Table, Owner= -1, From= -1): self.MetaFile = FilePath self._FileDir = self.MetaFile.Dir self._Defines = {} + self._Packages = [] self._FileLocalMacros = {} self._SectionsMacroDict = defaultdict(dict) @@ -352,6 +353,13 @@ def _SectionHeaderParser(self): # If the section information is needed later, it should be stored in database self._ValueList[0] = self._SectionName + ## [packages] section parser + @ParseMacro + def _PackageParser(self): + self._CurrentLine = CleanString(self._CurrentLine) + self._Packages.append(self._CurrentLine) + self._ValueList[0] = self._CurrentLine + ## [defines] section parser @ParseMacro def _DefineParser(self): @@ -849,6 +857,7 @@ class DscParser(MetaFileParser): TAB_LIBRARIES.upper() : MODEL_EFI_LIBRARY_INSTANCE, TAB_LIBRARY_CLASSES.upper() : MODEL_EFI_LIBRARY_CLASS, TAB_BUILD_OPTIONS.upper() : MODEL_META_DATA_BUILD_OPTION, + TAB_PACKAGES.upper() : MODEL_META_DATA_PACKAGE, TAB_PCDS_FIXED_AT_BUILD_NULL.upper() : MODEL_PCD_FIXED_AT_BUILD, TAB_PCDS_PATCHABLE_IN_MODULE_NULL.upper() : MODEL_PCD_PATCHABLE_IN_MODULE, TAB_PCDS_FEATURE_FLAG_NULL.upper() : MODEL_PCD_FEATURE_FLAG, @@ -1340,6 +1349,7 @@ def _PostProcess(self): MODEL_META_DATA_DEFINE : self.__ProcessDefine, MODEL_META_DATA_GLOBAL_DEFINE : self.__ProcessDefine, MODEL_META_DATA_INCLUDE : self.__ProcessDirective, + MODEL_META_DATA_PACKAGE : self.__ProcessPackages, MODEL_META_DATA_CONDITIONAL_STATEMENT_IF : self.__ProcessDirective, MODEL_META_DATA_CONDITIONAL_STATEMENT_ELSE : self.__ProcessDirective, MODEL_META_DATA_CONDITIONAL_STATEMENT_IFDEF : self.__ProcessDirective, @@ -1643,6 +1653,9 @@ def __ProcessDirective(self): self._ValueList = None self._ContentIndex -= 1 + def __ProcessPackages(self): + self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros) + def __ProcessSkuId(self): self._ValueList = [ReplaceMacro(Value, self._Macros, RaiseError=True) for Value in self._ValueList] @@ -1721,6 +1734,7 @@ def DisableOverrideComponent(self,module_id): MODEL_META_DATA_COMPONENT : _ComponentParser, MODEL_META_DATA_BUILD_OPTION : _BuildOptionParser, MODEL_UNKNOWN : MetaFileParser._Skip, + MODEL_META_DATA_PACKAGE : MetaFileParser._PackageParser, MODEL_META_DATA_USER_EXTENSION : MetaFileParser._SkipUserExtension, MODEL_META_DATA_SECTION_HEADER : MetaFileParser._SectionHeaderParser, MODEL_META_DATA_SUBSECTION_HEADER : _SubsectionHeaderParser, diff --git a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py index 0b11ec2d597..913e710fd9f 100644 --- a/BaseTools/Source/Python/Workspace/WorkspaceCommon.py +++ b/BaseTools/Source/Python/Workspace/WorkspaceCommon.py @@ -37,6 +37,8 @@ def __missing__(self, key): # def GetPackageList(Platform, BuildDatabase, Arch, Target, Toolchain): PkgSet = set() + if Platform.Packages: + PkgSet.update(Platform.Packages) for ModuleFile in Platform.Modules: Data = BuildDatabase[ModuleFile, Arch, Target, Toolchain] PkgSet.update(Data.Packages) diff --git a/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py b/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py index ab7b4506c1c..9420eaa608e 100644 --- a/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py +++ b/BaseTools/Source/Python/Workspace/WorkspaceDatabase.py @@ -186,6 +186,10 @@ def GetPackageList(self, Platform, Arch, TargetName, ToolChainTag): for Package in LibObj.Packages: if Package not in PackageList: PackageList.append(Package) + for Package in Pa.Packages: + if Package in PackageList: + continue + PackageList.append(Package) return PackageList From 54a07f8fe088d1fe3b7a6fec76d64ab25cdba656 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Thu, 14 Nov 2019 19:46:41 +0800 Subject: [PATCH 131/384] MdePkg: Update the comments of IsLanguageSupported Keep the comment style of IsLanguageSupported align with other functions. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Shenglei Zhang Reviewed-by: Liming Gao --- MdePkg/Include/Library/UefiLib.h | 19 ++++++++++--------- MdePkg/Library/UefiLib/UefiLib.c | 18 +++++++++--------- 2 files changed, 19 insertions(+), 18 deletions(-) diff --git a/MdePkg/Include/Library/UefiLib.h b/MdePkg/Include/Library/UefiLib.h index 67c6f96747c..0abb40d6ecb 100644 --- a/MdePkg/Include/Library/UefiLib.h +++ b/MdePkg/Include/Library/UefiLib.h @@ -462,15 +462,16 @@ EfiTestChildHandle ( ); /** - * This function checks the supported languages list for a target language, - * This only supports RFC 4646 Languages. - * - * @param SupportedLanguages The supported languages - * @param TargetLanguage The target language - * - * @return Returns EFI_SUCCESS if the language is supported, - * EFI_UNSUPPORTED otherwise - */ + This function checks the supported languages list for a target language, + This only supports RFC 4646 Languages. + + @param SupportedLanguages The supported languages + @param TargetLanguage The target language + + @retval Returns EFI_SUCCESS if the language is supported, + EFI_UNSUPPORTED otherwise + +**/ EFI_STATUS EFIAPI IsLanguageSupported ( diff --git a/MdePkg/Library/UefiLib/UefiLib.c b/MdePkg/Library/UefiLib/UefiLib.c index cc03be84c2d..07c45d1e91f 100644 --- a/MdePkg/Library/UefiLib/UefiLib.c +++ b/MdePkg/Library/UefiLib/UefiLib.c @@ -641,15 +641,15 @@ EfiTestChildHandle ( } /** - * This function checks the supported languages list for a target language, - * This only supports RFC 4646 Languages. - * - * @param SupportedLanguages The supported languages - * @param TargetLanguage The target language - * - * @return Returns EFI_SUCCESS if the language is supported, - * EFI_UNSUPPORTED otherwise - */ + This function checks the supported languages list for a target language, + This only supports RFC 4646 Languages. + + @param SupportedLanguages The supported languages + @param TargetLanguage The target language + + @retval Returns EFI_SUCCESS if the language is supported, + EFI_UNSUPPORTED otherwise +**/ EFI_STATUS EFIAPI IsLanguageSupported ( From 80186f9d3be67fdef1bf3fc0fabd4beea58f7d24 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 13:35:14 -0800 Subject: [PATCH 132/384] Enable the test runner plugin to propogate failures to CI process. --- .../HostBasedUnitTestRunner.py | 48 ++++++++++--------- 1 file changed, 26 insertions(+), 22 deletions(-) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index 2acc9ffdec3..b437bae6e48 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -17,6 +17,27 @@ class HostBasedUnitTestRunner(IUefiBuildPlugin): + def do_pre_build(self, thebuilder): + ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') + if ci_type != 'host_unit_test': + return 0 + + shell_env = shell_environment.GetEnvironment() + # Use the tools lib to determine the correct values for the vars that interest us. + interesting_keys = ["ExtensionSdkDir", "INCLUDE", "LIB", "LIBPATH", "UniversalCRTSdkDir", + "UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath", "WindowsSdkDir", "WindowsSdkVerBinPath", + "WindowsSDKVersion", "VCToolsInstallDir"] + vs_vars = locate_tools.QueryVcVariables(interesting_keys, "amd64") + for (k, v) in vs_vars.items(): + if k.upper() == "PATH": + shell_env.append_path(v) + else: + shell_env.set_shell_var(k, v) + + # Set up the reporting type for Cmocka. + shell_env.set_shell_var('CMOCKA_MESSAGE_OUTPUT', 'xml') + return 0 + def do_post_build(self, thebuilder): ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') if ci_type != 'host_unit_test': @@ -26,6 +47,9 @@ def do_post_build(self, thebuilder): logging.log(edk2_logging.get_section_level(), "Run Host based Unit Tests") path = thebuilder.env.GetValue("BUILD_OUTPUT_BASE") + + failure_count = 0 + for arch in thebuilder.env.GetValue("TARGET_ARCH").split(): logging.log(edk2_logging.get_subsection_level(), "Testing for architecture: " + arch) @@ -63,26 +87,6 @@ def do_post_build(self, thebuilder): "%s Test Failed" % os.path.basename(test)) logging.warning( " %s - %s" % (case.attrib['name'], result.text)) + failure_count += 1 - return 0 - - def do_pre_build(self, thebuilder): - ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') - if ci_type != 'host_unit_test': - return 0 - - shell_env = shell_environment.GetEnvironment() - # Use the tools lib to determine the correct values for the vars that interest us. - interesting_keys = ["ExtensionSdkDir", "INCLUDE", "LIB", "LIBPATH", "UniversalCRTSdkDir", - "UCRTVersion", "WindowsLibPath", "WindowsSdkBinPath", "WindowsSdkDir", "WindowsSdkVerBinPath", - "WindowsSDKVersion", "VCToolsInstallDir"] - vs_vars = locate_tools.QueryVcVariables(interesting_keys, "amd64") - for (k, v) in vs_vars.items(): - if k.upper() == "PATH": - shell_env.append_path(v) - else: - shell_env.set_shell_var(k, v) - - # Set up the reporting type for Cmocka. - shell_env.set_shell_var('CMOCKA_MESSAGE_OUTPUT', 'xml') - return 0 + return failure_count From 3f11e2694a55973c6866fcad4a0699bb237d90dd Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 13:43:10 -0800 Subject: [PATCH 133/384] Make the HostUnitTestCompilerPlugin as close as possible to the CompilerPlugin. Also add additional documentation to align with existing examples. --- .../Plugin/CompilerPlugin/CompilerPlugin.py | 4 ++-- .../HostUnitTestCompilerPlugin.py | 18 ++++++++++-------- .../HostUnitTestCompilerPlugin/Readme.md | 18 ++++++++++++++++++ 3 files changed, 30 insertions(+), 10 deletions(-) create mode 100644 .pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md diff --git a/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py index 3b6f7c76988..e8657940d71 100644 --- a/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py +++ b/.pytool/Plugin/CompilerPlugin/CompilerPlugin.py @@ -1,4 +1,4 @@ -# @file HostUnitTestCompiler_plugin.py +# @file CompilerPlugin.py ## # Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -42,7 +42,7 @@ def RunsOnTargetList(self): return ["DEBUG", "RELEASE"] ## - # External function of plugin. This function is used to perform the task of the MuBuild Plugin + # External function of plugin. This function is used to perform the task of the ICiBuildPlugin Plugin # # - package is the edk2 path to package. This means workspace/packagepath relative. # - edk2path object configured with workspace and packages path diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py index d61073820a0..389088a7605 100644 --- a/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/HostUnitTestCompilerPlugin.py @@ -1,6 +1,6 @@ # @file HostUnitTestCompilerPlugin.py -# -# Copyright (c) Microsoft Corporation. All rights reserved. +## +# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -8,17 +8,18 @@ import os import re from edk2toollib.uefi.edk2.parsers.dsc_parser import DscParser -from edk2toolext.environment.var_dict import VarDict from edk2toolext.environment.plugintypes.ci_build_plugin import ICiBuildPlugin from edk2toolext.environment.uefi_build import UefiBuilder from edk2toolext import edk2_logging +from edk2toolext.environment.var_dict import VarDict from edk2toollib.utility_functions import GetHostInfo class HostUnitTestCompilerPlugin(ICiBuildPlugin): """ - A CiBuildPlugin that compiles the dsc for host based unit - test apps, runs them, and collects their results. + A CiBuildPlugin that compiles the dsc for host based unit test apps. + An IUefiBuildPlugin may be attached to this plugin that will run the + unit tests and collect the results after successful compilation. Configuration options: "HostUnitTestCompilerPlugin": { @@ -35,7 +36,7 @@ def GetTestName(self, packagename: str, environment: VarDict) -> tuple: packagename: string containing name of package to build environment: The VarDict for the test to run in Returns: - a tuple containing the testcase name and the classname + a tuple containing the testcase name and the classname (testcasename, classname) """ num,types = self.__GetHostUnitTestArch(environment) @@ -85,14 +86,15 @@ def __GetHostUnitTestArch(self, environment): def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, PLMHelper, tc, output_stream=None): self._env = environment environment.SetValue("CI_BUILD_TYPE", "host_unit_test", "Set in HostUnitTestCompilerPlugin") - AP = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) # Parse the config for required DscPath element if "DscPath" not in pkgconfig: tc.SetSkipped() tc.LogStdError("DscPath not found in config file. Nothing to compile for HostBasedUnitTests.") return -1 - + + AP = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + APDSC = os.path.join(AP, pkgconfig["DscPath"].strip()) AP_Path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(APDSC) if AP is None or AP_Path is None or not os.path.isfile(APDSC): diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md b/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md new file mode 100644 index 00000000000..dac7c4fb858 --- /dev/null +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md @@ -0,0 +1,18 @@ +# Host UnitTest Compiler Plugin + +A CiBuildPlugin that compiles the dsc for host based unit test apps. +An IUefiBuildPlugin may be attached to this plugin that will run the unit tests and collect the results after successful compilation. + +## Configuration + +The package relative path of the DSC file to build. + +``` yaml +"HostUnitTestCompilerPlugin": { + "DscPath": "" +} +``` + +### DscPath + +Package relative path to the DSC file to build. From ea7e31adeea9fc936edfefcdfd2ff63fbc21b063 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 14:22:51 -0800 Subject: [PATCH 134/384] Update some copyrights. --- .../HostBasedUnitTestRunner/HostBasedUnitTestRunner.py | 3 ++- UnitTestPkg/ReadMe.md | 10 ++-------- 2 files changed, 4 insertions(+), 9 deletions(-) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index b437bae6e48..2fd34813321 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -1,7 +1,8 @@ # @file HostBasedUnitTestRunner.py # Plugin to located any host-based unit tests in the output directory and execute them. ## -# Copyright (c) Microsoft Corporation +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent # ## import os diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md index 9bb4f6484d9..7a5aaf23837 100644 --- a/UnitTestPkg/ReadMe.md +++ b/UnitTestPkg/ReadMe.md @@ -62,12 +62,6 @@ many of the features of the framework. This sample can be found in the SampleUn ## Copyright -Copyright (c) 2017, Microsoft Corporation - -All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent \ No newline at end of file From 48685afc29e9401ce50b2e3c1f90fa26abe7226a Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 15:06:44 -0800 Subject: [PATCH 135/384] Update the primary readme with everything but the walkthrough. --- UnitTestPkg/ReadMe.md | 74 ++++++++++++++++++++----------------------- 1 file changed, 34 insertions(+), 40 deletions(-) diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md index 7a5aaf23837..2192ad2a8c8 100644 --- a/UnitTestPkg/ReadMe.md +++ b/UnitTestPkg/ReadMe.md @@ -1,67 +1,61 @@ -# Unit Test Support Package +# Unit Test Framework Package ## About -This package adds a unit test framework targeted at the UEFI shell environment. -It allows for unit test development to focus on the tests and leave, error logging, result formatting, -context persistance, and test running to the framework. The unit test framework works well for low -level unit tests as well as system level tests and fits easily in automation frameworks. +This package adds a unit test framework capable of building tests for multiple contexts including +the UEFI shell environment and host-based environments. It allows for unit test development to focus +on the tests and leave error logging, result formatting, context persistance, and test running to the framework. +The unit test framework works well for low level unit tests as well as system level tests and +fits easily in automation frameworks. -The code is designed for a unit test application to leverage the framework which is made -up of a number of libraries which allow for easy customization of the different elements. -A few different instances are created to both show how easy some behaviors can be customized as -well as provide different implementations that support different use cases. +The code is designed for a unit test application to leverage the framework which is made +up of a number of libraries which allow for easy customization of the different elements. +A few different instances are created to both show how easy some behaviors can be customized as +well as provide different implementations that support different use cases. ### UnitTestLib -The main "framework" library. This provides the framework init, suite init, and add test case -functionality. It also supports the running of the suites and logging/reporting of results. +The main "framework" library. This provides the framework init, suite init, and add test case +functionality. It also supports the running of the suites and logging/reporting of results. ### UnitTestAssetLib -The UnitTestAssetLib provides helper macros and functions for checking test conditions and -reporting errors. Status and error info will be logged into the test context. There are a number -of Assert macros that make the unit test code friendly to view and easy to understand. +The UnitTestAssetLib provides helper macros and functions for checking test conditions and +reporting errors. Status and error info will be logged into the test context. There are a number +of Assert macros that make the unit test code friendly to view and easy to understand. +### UnitTestLogLib -### UnitTestBootLib - -One of the unique features of the unit test framework is to be able to save text context -and reboot the system. Since unit tests are generally run from a bootable usb key the framework -has library calls to set boot next for usb. There is numerous ways this could be done on a given -platform / BDS implementation and therefore this simple library allows customization if needed. -This package supplies two instances: - -* UsbClass Lib: This uses the Usb Class boot option as defined in the UEFI spec and leveraged -by industry standard USB applications. -* UsbMicrosoft Lib: This uses a private boot option found in Microsoft UEFI to boot to usb +Library to support logging information during the test execution. This data is logged to the test +context and will be available in the test reporting phase. This should be used for logging test +details and helpful messages to resolve test failures. -### UnitTestLogLib +### UnitTestPersistenceLib -Library to support logging information during the test execution. This data is logged to the test -context and will be available in the test reporting phase. This should be used for logging test -details and helpful messages to resolve test failures. +Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests +that require exiting the active process and then resuming state can be maintained. This is critical +in supporting a system reboot in the middle of a test run. ### UnitTestResultReportLib -Library provides function to run at the end of a framework test run and handles formatting the report. This is a common customization point and allows the unit test framework to fit -its output reports into other test infrastructure. In this package a simple library instances has -been supplied to output test results to the console as plain text. +Library provides function to run at the end of a framework test run and handles formatting the report. +This is a common customization point and allows the unit test framework to fit its output reports into +other test infrastructure. In this package a simple library instances has been supplied to output test +results to the console as plain text. -### UnitTestPersistenceLib +### UnitTestTerminationLib -Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests -that require exiting the active process and then resuming state can be maintained. This is critical -in supporting a system reboot in the middle of a test run. +Sometimes a given test case will need to exit the test in progress to allow system state to change and +will check for that state change on re-entry. This is most common when a Dxe- or Shell-based test wants to +reboot the system and check for a different system state after reboot. Since the method of exiting rebooting +may vary depending on context (PEI, SMM, DXE, Shell, etc.), this functionality is abstracted. ## Samples -There is a sample unit test provided as both an example of how to write a unit test and leverage -many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. - +There is a sample unit test provided as both an example of how to write a unit test and leverage +many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. ## Copyright Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent - \ No newline at end of file From a68a84b357bffad751cec285ae2f01fbb4cf8f1e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 15:27:24 -0800 Subject: [PATCH 136/384] Update the documentation for the HostBasedRunner plugin. --- .../HostBasedUnitTestRunner.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py index 2fd34813321..a4f89818394 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner.py @@ -19,6 +19,18 @@ class HostBasedUnitTestRunner(IUefiBuildPlugin): def do_pre_build(self, thebuilder): + ''' + Works with the compiler (either the HostBasedCompilerPlugin or an other Builder) to set + up the environment that will be needed to build host-based unit tests. + + EXPECTS: + - Build Var 'CI_BUILD_TYPE' - If not set to 'host_unit_test', will not do anything. + + UPDATES: + - Shell Var (Several) - Updates the shell with all vars listed in interesting_keys. + - Shell Path - Updated from QueryVcVariables() + - Shell Var 'CMOCKA_MESSAGE_OUTPUT' + ''' ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') if ci_type != 'host_unit_test': return 0 @@ -40,6 +52,16 @@ def do_pre_build(self, thebuilder): return 0 def do_post_build(self, thebuilder): + ''' + After a build, will automatically locate and run all host-based unit tests. Logs any + failures with Warning severity and will return a count of the failures as the return code. + + EXPECTS: + - Build Var 'CI_BUILD_TYPE' - If not set to 'host_unit_test', will not do anything. + + UPDATES: + - Shell Var 'CMOCKA_XML_FILE' + ''' ci_type = thebuilder.env.GetValue('CI_BUILD_TYPE') if ci_type != 'host_unit_test': return 0 From d24b0663df41bd65c3a95afaf956812519266a82 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 17:59:02 -0800 Subject: [PATCH 137/384] Mostly through documentation. Progress checkpoint. --- UnitTestPkg/ReadMe.md | 107 +++++++++++++++++++++++++++++++++++++++++- 1 file changed, 106 insertions(+), 1 deletion(-) diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md index 2192ad2a8c8..f9225192f11 100644 --- a/UnitTestPkg/ReadMe.md +++ b/UnitTestPkg/ReadMe.md @@ -55,7 +55,112 @@ may vary depending on context (PEI, SMM, DXE, Shell, etc.), this functionality i There is a sample unit test provided as both an example of how to write a unit test and leverage many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. +## Usage + +This section is built a lot like a "Getting Started". We'll go through some of the components that are needed +when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe +how to check for expected conditions in test cases and a bit of the logging characteristics. + +Most of these examples will refer to the SampleUnitTestApp found in this package. + +### Requirements - INF + +In our INF file, we'll need to bring in some libraries. At a bare minimum, we'll need an instance of `UnitTestLib`, +however, since Test Assertions are implemented in their own lib in order to allow for framework flexibility, we +will also have to bring in `UnitTestAssertLib` as well. + +See this example in 'SampleUnitTestApp.inf'... + +``` +[LibraryClasses] + BaseLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib +``` + +And in order to bring in the headers we'll need, go ahead and add 'UnitTestPkg/UnitTestPkg.dec' to your +`Packages` list as well. + +### Requirements - Code + +Not to state the obvious, but let's make sure we have the following includes before getting too far along... + +```c +#include +#include +``` + +Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). + +### Configuring the Framework + +Everything in the UnitTestPkg framework is built around an object called -- conveniently -- the Framework. +This Framework object will contain all the information about our test, the test suites and test cases associated +with it, the current location within the test pass, and any results that have been recorded so far. + +To get started with a test, we must first create a Framework instance. The function for this is +`InitUnitTestFramework`. It takes in `CHAR16` strings for the long name, short name, and test version. +The long name and version strings are just for user presentation and relatively flexible. The short name +will be used to name any cache files and/or test results, so should be a name that makes sense in that context. +These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. + +In the 'SampleUnitTestApp', the module name is used as the short name, so the init looks like this. + +```c +CHAR16 ShortName[100]; +ShortName[0] = L'\0'; + +UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); +DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + +// +// Start setting up the test framework for running the tests. +// +Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, ShortName, UNIT_TEST_APP_VERSION ); +``` + +The `&Fw` returned here is the handle to the Framework. If it's successfully returned, we can start adding +test suites and test cases. + +Test suites exist purely to help organize test cases and to differentiate the results in reports. If you're writing +a small unit test, you can conceivably put all test cases into a single suite. However, if you end up with 20+ test +cases, it may be beneficial to organize them according to purpose. You _must_ have at least one test suite, even if +it's just a catch-all. The function to create a test suite is `CreateUnitTestSuite`. It takes in a handle to +the Framework object, a `CHAR16` string for the suite title and package name, and optional function pointers for +a setup function and a teardown function. + +The suite title is for user presentation. The package name is for xUnit type reporting and uses a '.'-separated +hierarchical format (see 'SampleUnitTestApp' for example). If provided, the setup and teardown functions will be +called once at the start of the suite (before _any_ tests have run) and once at the end of the suite (after _all_ +tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are +`UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`. + +Looking at 'SampleUnitTestApp', you can see that the first test suite is created as below... + +```c +// +// Populate the SimpleMathTests Unit Test Suite. +// +Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); +``` + +This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and +will be used when adding test cases. + +Alrighty! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test +to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; +a `CHAR16` string for the description and class name; a function pointer for the test case itself; additional, optional +function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. + +Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in +usage to the suite title and package name strings in the test suites. The former is for user presentation and the +latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the +prototype should be `UNIT_TEST_FUNCTION`. + ## Copyright -Copyright (c) Microsoft Corporation. +Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent From 19fbb7b1d814a5c4f5f96710aef89391ae68a96a Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 23:15:04 -0800 Subject: [PATCH 138/384] Finish the documentation. --- UnitTestPkg/ReadMe.md | 68 ++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 67 insertions(+), 1 deletion(-) diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md index f9225192f11..0c6d327bd5f 100644 --- a/UnitTestPkg/ReadMe.md +++ b/UnitTestPkg/ReadMe.md @@ -158,7 +158,73 @@ function pointers for prerequisite check and cleanup routines; and and optional Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in usage to the suite title and package name strings in the test suites. The former is for user presentation and the latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the -prototype should be `UNIT_TEST_FUNCTION`. +prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining. + +The prerequisite check function has a prototype of `UNIT_TEST_PREREQ` and -- if provided -- will be called +immediately before the test case. If this function returns any error, the test case will not be run and will be +recorded as `UNIT_TEST_ERROR_PREREQ_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called +immediately after the test case to provide an opportunity to reset any global state that may have been changed in the +test case. In the event of a prerequisite failure, the cleanup function will also be skipped. If either of these +functions is not needed, pass `NULL`. + +The context pointer is entirely case-specific. It will be passed to the test case upon execution. One of the purposes +of the context pointer is to allow test case reuse with different input data. (Another use is for testing that wraps +around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context +pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`. + +In 'SampleUnitTestApp', the first test case is added using the code below... + +```c +AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); +``` + +This test case calls the function `OnePlusOneShouldEqualTwo` and has no prerequisite, cleanup, or context. + +Once all the suites and cases are added, it's time to run the Framework. + +```c +// +// Execute the tests. +// +Status = RunAllTestSuites( Fw ); +``` + +### A Simple Test Case + +We'll take a look at the below test case from 'SampleUnitTestApp'... + +```c +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() +``` + +The prototype for this function matches the `UNIT_TEST_FUNCTION` prototype. It takes in a handle to the Framework +itself and the context pointer. The context pointer could be cast and interpreted as anything within this test case, +which is why it's important to configure contexts carefully. The test case returns a value of `UNIT_TEST_STATUS`, which +will be recorded in the Framework and reported at the end of all suites. + +In this test case, the `UT_ASSERT_EQUAL` assertion is being used to establish that the business logic has functioned +correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your +intended test criterium as possible, because the logging is specific to the macro and more specific macros have more +detailed logs. When in doubt, there are always `UT_ASSERT_TRUE` and `UT_ASSERT_FALSE`. Assertion macros that fail their +test criterium will immediately return from the test case with `UNIT_TEST_ERROR_TEST_FAILED` and log an error string. +_Note_ that this early return can have implications for memory leakage. + +At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. ## Copyright From 9749008aaa06b7856fc97266818e3bf05cb6c57a Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 21 Nov 2019 23:25:45 -0800 Subject: [PATCH 139/384] TEMP: Workaround edk2toolext problem. --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 6a41a95ec59..352ae75473d 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -13,4 +13,4 @@ ## edk2-pytool-library==0.10.* -edk2-pytool-extensions==0.12.* +edk2-pytool-extensions==0.12.0 From e0f8261ad02217fa8ed57c95c379c2fc8fd67210 Mon Sep 17 00:00:00 2001 From: "Fan, ZhijuX" Date: Fri, 22 Nov 2019 18:54:39 +0800 Subject: [PATCH 140/384] BaseTools:fix regression issue for platform .map file BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2363 This patch is to fix a build tool regression issue which was introduced by commit b8ac0b7f28.This issue caused map file lost the line of IMAGE=***. For example,in Ovmf.map, there is no line of (IMAGE= ) under each of modules item. The path to the efi file generated by each module is written on this line The purpose of this line is add the debug image full path. there is no information about the module in the map file other than FVName, it allows us to quickly know which module this part corresponds to. In commit b8ac0b7f28,add a line ("self.BuildModules = []") in function, but it's used to calculate the variable ModuleList in the following code. Signed-off-by: Zhiju.Fan Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- BaseTools/Source/Python/build/build.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 6c8798ef93f..4b31356a425 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -2267,6 +2267,10 @@ def _MultiThreadBuildPlatform(self): self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: self.UpdateBuildCache() + # + # Get Module List + # + ModuleList = {ma.Guid.upper(): ma for ma in self.BuildModules} self.BuildModules = [] self.MakeTime += int(round((time.time() - MakeContiue))) # @@ -2285,10 +2289,6 @@ def _MultiThreadBuildPlatform(self): # if (Arch == 'IA32' or Arch == 'ARM') and self.LoadFixAddress != 0xFFFFFFFFFFFFFFFF and self.LoadFixAddress >= 0x100000000: EdkLogger.error("build", PARAMETER_INVALID, "FIX_LOAD_TOP_MEMORY_ADDRESS can't be set to larger than or equal to 4G for the platorm with IA32 or ARM arch modules") - # - # Get Module List - # - ModuleList = {ma.Guid.upper():ma for ma in self.BuildModules} # # Rebase module to the preferred memory address before GenFds From 290a485d6043a049b611aab30f450c74b8591f35 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Mon, 25 Nov 2019 17:06:04 +0800 Subject: [PATCH 141/384] StandaloneMmPkg: Fix build failure - Bug 2253 The StandaloneMmPkg currently has code for supporting Arm architecture only. Support for X64 and IA32 is currently under development on a separate branch. However, StandaloneMmPkg/StandaloneMmPkg.dsc is indicating that support for X64 and IA32 is available which is causing build failures. This has been reported in https://bugzilla.tianocore.org/show_bug.cgi?id=2253 This issue has been discussed earlier on the list: (1) https://edk2.groups.io/g/devel/message/47276 (2) https://edk2.groups.io/g/devel/message/47283 In light of the above, this patch removes IA32 and X64 from SUPPORTED_ARCHITECTURES, until support for the respective architectures is merged into StandaloneMmPkg. Cc: Achin Gupta Cc: Jiewen Yao Cc: Supreeth Venkatesh Cc: Laszlo Ersek Signed-off-by: Sami Mujawar Reviewed-by: Laszlo Ersek Reviewed-by: Jiewen Yao --- StandaloneMmPkg/StandaloneMmPkg.dsc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/StandaloneMmPkg/StandaloneMmPkg.dsc b/StandaloneMmPkg/StandaloneMmPkg.dsc index 8a68d397469..f9546e182e2 100644 --- a/StandaloneMmPkg/StandaloneMmPkg.dsc +++ b/StandaloneMmPkg/StandaloneMmPkg.dsc @@ -2,7 +2,7 @@ # Standalone MM Platform. # # Copyright (c) 2015, Intel Corporation. All rights reserved.
-# Copyright (c) 2016 - 2018, ARM Limited. All rights reserved.
+# Copyright (c) 2016 - 2019, ARM Limited. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -19,7 +19,7 @@ PLATFORM_VERSION = 1.0 DSC_SPECIFICATION = 0x00010011 OUTPUT_DIRECTORY = Build/StandaloneMm - SUPPORTED_ARCHITECTURES = IA32|X64|AARCH64 + SUPPORTED_ARCHITECTURES = AARCH64 BUILD_TARGETS = DEBUG|RELEASE SKUID_IDENTIFIER = DEFAULT From bbb5b0d648d918c83f2f99b02e3446787dbe474f Mon Sep 17 00:00:00 2001 From: "Kubacki, Michael A" Date: Fri, 22 Nov 2019 07:02:35 +0800 Subject: [PATCH 142/384] MdeModulePkg/Variable: Initialize local variable "Variable" REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2364 Fixes a new build warning in VS2012 introduced in f8ff4cca7c. This patch initializes the local variable "Variable" in VariableServiceGetNextVariableInternal (). This ensures the pointers in the structure are initialized in the case no variable stores exist in the list of variable stores. Cc: Liming Gao Cc: Michael D Kinney Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Jian J Wang --- MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c index d458f1c608f..f6d187543d0 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableParsing.c @@ -551,6 +551,8 @@ VariableServiceGetNextVariableInternal ( return EFI_INVALID_PARAMETER; } + ZeroMem (&Variable, sizeof (Variable)); + // Check if the variable exists in the given variable store list for (StoreType = (VARIABLE_STORE_TYPE) 0; StoreType < VariableStoreTypeMax; StoreType++) { if (VariableStoreList[StoreType] == NULL) { From bd85bf54c268204c7a698a96f3ccd96cd77952cd Mon Sep 17 00:00:00 2001 From: "Kubacki, Michael A" Date: Fri, 22 Nov 2019 07:02:36 +0800 Subject: [PATCH 143/384] MdeModulePkg/Variable: Initialize local variable "RtPtrTrack" REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2364 Fixes a new build warning in VS2012 introduced in f8ff4cca7c. This patch initializes the local variable "RtPtrTrack" in FindVariableInRuntimeCache (). This ensures the pointers in the structure are initialized in the case no variable stores exist in the list of variable stores. Cc: Liming Gao Cc: Michael D Kinney Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Jian J Wang --- .../Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c index d525998ae30..2cf0ed32ae5 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c @@ -590,6 +590,8 @@ FindVariableInRuntimeCache ( return EFI_INVALID_PARAMETER; } + ZeroMem (&RtPtrTrack, sizeof (RtPtrTrack)); + // // The UEFI specification restricts Runtime Services callers from invoking the same or certain other Runtime Service // functions prior to completion and return from a previous Runtime Service call. These restrictions prevent From fe6142f04c4f742f5f1159d50161da8c0ede338c Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 21 Nov 2019 08:31:24 +0100 Subject: [PATCH 144/384] MdeModulePkg/VariableSmmRuntimeDxe.inf: list local header "Variable.h" Commit aab3b9b9a1e5 ("MdeModulePkg/Variable: Add RT GetVariable() cache support", 2019-11-05) added "VariableParsing.h" to "VariableSmmRuntimeDxe.inf". "VariableParsing.h" includes "Variable.h", so the "build" utility is right to warn us that "Variable.h" should be listed in [Sources] too. Cc: Hao A Wu Cc: Jian J Wang Cc: Leif Lindholm Cc: Liming Gao Cc: Michael Kubacki Fixes: aab3b9b9a1e5e1f3fa966fb1667fc3e6c47e7706 Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Jian J Wang Reviewed-by: Leif Lindholm --- .../Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf | 1 + 1 file changed, 1 insertion(+) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf index a250533a534..59286277339 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf @@ -41,6 +41,7 @@ Measurement.c VariableParsing.c VariableParsing.h + Variable.h [Packages] MdePkg/MdePkg.dec From b49a6c8f80d970cf7ab25c28a079c0db225f3ad2 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 21 Nov 2019 08:46:10 +0100 Subject: [PATCH 145/384] CryptoPkg/OpensslLib: improve INF file consistency When diffing "OpensslLib.inf" against "OpensslLibCrypto.inf", the *only* differences should be: - BASE_NAME, MODULE_UNI_FILE, and FILE_GUID are expected to differ, in [Defines]; - "OpensslLib.inf" is expected to list "$(OPENSSL_PATH)/ssl/..." source files in the auto-generated part of the [Sources] section. Commit 8906f076de35 ("CryptoPkg/OpensslLib: Add missing header files in INF file", 2019-08-16) broke that invariant, by adding "buildinf.h" and "rand_pool_noise.h" in different order to both INF files. Fix that order in "OpensslLib.inf" now. (Note that this does not re-establish full consistency between both INF files -- it just highlights another problem, which we'll fix in the next patch.) Cc: Jian J Wang Cc: Leif Lindholm Cc: Shenglei Zhang Cc: Xiaoyu Lu Fixes: 8906f076de35b222a7d62bcf6ed1a4a2498a5791 Signed-off-by: Laszlo Ersek Reviewed-by: Jian J Wang Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Leif Lindholm --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 44e050f08d4..58202f83118 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -22,8 +22,6 @@ # [Sources] - buildinf.h - rand_pool_noise.h $(OPENSSL_PATH)/e_os.h # Autogenerated files list starts here $(OPENSSL_PATH)/crypto/aes/aes_cbc.c @@ -598,7 +596,8 @@ $(OPENSSL_PATH)/ssl/record/record.h $(OPENSSL_PATH)/ssl/record/record_locl.h # Autogenerated files list ends here - + buildinf.h + rand_pool_noise.h ossl_store.c rand_pool.c From 4d613feee57ebd4680f3c23398a9b33723f29fd6 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 21 Nov 2019 09:01:10 +0100 Subject: [PATCH 146/384] CryptoPkg/OpensslLib.inf: list OpenSSL local header "ms/uplink.h" Commit 8906f076de35 ("CryptoPkg/OpensslLib: Add missing header files in INF file", 2019-08-16) incorrectly placed "ms/uplink.h" in the auto-generated part of [Sources], in "OpensslLib.inf". ("ms/uplink.h" was added in the right spot in "OpensslLibCrypto.inf".) Subsequently, when commit 9f4fbd56d430 ("CryptoPkg/OpensslLib: Update process_files.pl to generate .h files", 2019-10-30) re-generated that part of "OpensslLib.inf", the "ms/uplink.h" file reference was lost. This triggers a warning from the "build" utility now. Name the header file in the right spot in [Sources]. This change makes "OpensslLib.inf" consistent with "OpensslLibCrypto.inf". Cc: Jian J Wang Cc: Leif Lindholm Cc: Shenglei Zhang Cc: Xiaoyu Lu Fixes: 8906f076de35b222a7d62bcf6ed1a4a2498a5791 Signed-off-by: Laszlo Ersek Reviewed-by: Jian J Wang Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Leif Lindholm --- CryptoPkg/Library/OpensslLib/OpensslLib.inf | 1 + 1 file changed, 1 insertion(+) diff --git a/CryptoPkg/Library/OpensslLib/OpensslLib.inf b/CryptoPkg/Library/OpensslLib/OpensslLib.inf index 58202f83118..3fa52f55432 100644 --- a/CryptoPkg/Library/OpensslLib/OpensslLib.inf +++ b/CryptoPkg/Library/OpensslLib/OpensslLib.inf @@ -23,6 +23,7 @@ [Sources] $(OPENSSL_PATH)/e_os.h + $(OPENSSL_PATH)/ms/uplink.h # Autogenerated files list starts here $(OPENSSL_PATH)/crypto/aes/aes_cbc.c $(OPENSSL_PATH)/crypto/aes/aes_cfb.c From 4f47eaf9456e1a4f22553fe0c97587c2124e2fba Mon Sep 17 00:00:00 2001 From: Maciej Rabeda Date: Thu, 28 Nov 2019 15:46:06 +0100 Subject: [PATCH 147/384] NetworkPkg: Fixes to static code analysis hits Introducing fixes to memory leak issues identified by static code analysis tool. Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Maciej Rabeda Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Siyuan Fu Reviewed-by: Jiaxin Wu --- NetworkPkg/Dhcp6Dxe/Dhcp6Io.c | 1 + NetworkPkg/Ip4Dxe/Ip4If.c | 6 +++++- NetworkPkg/TcpDxe/TcpDispatcher.c | 1 + 3 files changed, 7 insertions(+), 1 deletion(-) diff --git a/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c b/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c index 4f8393cb36c..613b42149cc 100644 --- a/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c +++ b/NetworkPkg/Dhcp6Dxe/Dhcp6Io.c @@ -203,6 +203,7 @@ Dhcp6EnqueueRetry ( // // Unexpected message type. // + FreePool(TxCb); return EFI_DEVICE_ERROR; } diff --git a/NetworkPkg/Ip4Dxe/Ip4If.c b/NetworkPkg/Ip4Dxe/Ip4If.c index 53a333037f9..348f2e076ae 100644 --- a/NetworkPkg/Ip4Dxe/Ip4If.c +++ b/NetworkPkg/Ip4Dxe/Ip4If.c @@ -491,9 +491,13 @@ Ip4CreateInterface ( IP4_INTERFACE *Interface; EFI_SIMPLE_NETWORK_MODE SnpMode; + if (Mnp == NULL) { + return NULL; + } + Interface = AllocatePool (sizeof (IP4_INTERFACE)); - if ((Interface == NULL) || (Mnp == NULL)) { + if (Interface == NULL) { return NULL; } diff --git a/NetworkPkg/TcpDxe/TcpDispatcher.c b/NetworkPkg/TcpDxe/TcpDispatcher.c index 86beaf8cc51..9ae08ccc1c5 100644 --- a/NetworkPkg/TcpDxe/TcpDispatcher.c +++ b/NetworkPkg/TcpDxe/TcpDispatcher.c @@ -390,6 +390,7 @@ TcpAttachPcb ( ); if (EFI_ERROR (Status)) { IpIoRemoveIp (IpIo, Tcb->IpInfo); + FreePool (Tcb); return Status; } From 46f6752834abf1a6264b351170bd65f2e4e7c0d9 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Wed, 13 Nov 2019 10:00:34 +0530 Subject: [PATCH 148/384] MdeModulePkg/MdeModulePkg.uni: Add missing strings for PCD Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Shenglei Zhang Reviewed-by: Jian J Wang --- MdeModulePkg/MdeModulePkg.uni | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/MdeModulePkg/MdeModulePkg.uni b/MdeModulePkg/MdeModulePkg.uni index a2c7a7ded3e..d9c7b1ac6cf 100644 --- a/MdeModulePkg/MdeModulePkg.uni +++ b/MdeModulePkg/MdeModulePkg.uni @@ -660,6 +660,18 @@ "TRUE - Device Path From Text Protocol will be produced.
\n" "FALSE - Device Path From Text Protocol will not be produced.
" +#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdEnableVariableRuntimeCache_PROMPT #language en-US "Enable the UEFI variable runtime cache." + +#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdEnableVariableRuntimeCache_HELP #language en-US "Indicates if the UEFI variable runtime cache should be enabled.

\n" + "This setting only applies if SMM variables are enabled. When enabled, all variable
\n" + "data for Runtime Service GetVariable () and GetNextVariableName () calls is retrieved
\n" + "from a runtime data buffer referred to as the "runtime cache". An SMI is not triggered
\n" + "at all for these requests. Variables writes still trigger an SMI. This can greatly
\n" + "reduce overall system SMM usage as most boots tend to issue far more variable reads
\n" + "than writes.
\n" + "TRUE - The UEFI variable runtime cache is enabled.
\n" + "FALSE - The UEFI variable runtime cache is disabled.
" + #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdVariableCollectStatistics_PROMPT #language en-US "Enable variable statistics collection" #string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdVariableCollectStatistics_HELP #language en-US "Indicates if the statistics about variable usage will be collected. This information is stored as a vendor configuration table into the EFI system table. Set this PCD to TRUE to use VariableInfo application in MdeModulePkg\Application directory to get variable usage info. VariableInfo application will not output information if not set to TRUE.

\n" From 0844a16a07ebb6cad0297905e743048c9c2b747f Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Thu, 14 Nov 2019 16:13:14 +0530 Subject: [PATCH 149/384] NetworkPkg/NetworkPkg.uni: Add missing strings for PCD Cc: Jiaxin Wu Cc: Siyuan Fu Cc: Maciej Rabeda Signed-off-by: Shenglei Zhang Reviewed-by: Jiaxin Wu --- NetworkPkg/NetworkPkg.uni | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/NetworkPkg/NetworkPkg.uni b/NetworkPkg/NetworkPkg.uni index 19e57a4a60d..328d8cb54a6 100644 --- a/NetworkPkg/NetworkPkg.uni +++ b/NetworkPkg/NetworkPkg.uni @@ -61,6 +61,13 @@ "TRUE - Certificate Authentication feature is enabled.
\n" "FALSE - Does not support Certificate Authentication.
" +#string STR_gEfiNetworkPkgTokenSpaceGuid_PcdSnpCreateExitBootServicesEvent_PROMPT #language en-US "Indicates whether SnpDxe creates event for ExitBootServices() call." + +#string STR_gEfiNetworkPkgTokenSpaceGuid_PcdSnpCreateExitBootServicesEvent_HELP #language en-US "Indicates whether SnpDxe driver will create an event that will be notified

\n" + "upon gBS->ExitBootServices() call.
\n" + "TRUE - Event being triggered upon ExitBootServices call will be created
\n" + "FALSE - Event being triggered upon ExitBootServices call will NOT be created
" + #string STR_gEfiNetworkPkgTokenSpaceGuid_PcdDhcp6UidType_PROMPT #language en-US "Type Value of Dhcp6 Unique Identifier (DUID)." #string STR_gEfiNetworkPkgTokenSpaceGuid_PcdDhcp6UidType_HELP #language en-US "IPv6 DHCP Unique Identifier (DUID) Type configuration (From RFCs 3315 and 6355).\n" From 0a58c9a39167c0788e5a4fa8a0038f5c46154ccf Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Thu, 14 Nov 2019 16:16:59 +0530 Subject: [PATCH 150/384] UefiCpuPkg/UefiCpuPkg.uni: Add missing strings for PCD Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Signed-off-by: Shenglei Zhang Reviewed-by: Eric Dong --- UefiCpuPkg/UefiCpuPkg.uni | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/UefiCpuPkg/UefiCpuPkg.uni b/UefiCpuPkg/UefiCpuPkg.uni index a7e279c5cb1..bfd696f48c3 100644 --- a/UefiCpuPkg/UefiCpuPkg.uni +++ b/UefiCpuPkg/UefiCpuPkg.uni @@ -195,6 +195,22 @@ #string STR_gUefiCpuPkgTokenSpaceGuid_PcdIsPowerOnReset_HELP #language en-US "Indicates if the current boot is a power-on reset." +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuSmmRestrictedMemoryAccess_PROMPT #language en-US "Access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock." + +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuSmmRestrictedMemoryAccess_HELP #language en-US "Indicate access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock.

\n" + "MMIO access is always allowed regardless of the value of this PCD.
\n" + "Loose of such restriction is only required by RAS components in X64 platforms.
\n" + "The PCD value is considered as constantly TRUE in IA32 platforms.
\n" + "When the PCD value is TRUE, page table is initialized to cover all memory spaces
\n" + "and the memory occupied by page table is protected by page table itself as read-only.
\n" + "In X64 build, it cannot be enabled at the same time with SMM profile feature (PcdCpuSmmProfileEnable).
\n" + "In X64 build, it could not be enabled also at the same time with heap guard feature for SMM
\n" + "(PcdHeapGuardPropertyMask in MdeModulePkg).
\n" + "In IA32 build, page table memory is not marked as read-only when either SMM profile feature (PcdCpuSmmProfileEnable)
\n" + "or heap guard feature for SMM (PcdHeapGuardPropertyMask in MdeModulePkg) is enabled.
\n" + "TRUE - Access to non-SMRAM memory is restricted to reserved, runtime and ACPI NVS type after SmmReadyToLock.
\n" + "FALSE - Access to any type of non-SMRAM memory after SmmReadyToLock is allowed.
" + #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuFeaturesCapability_PROMPT #language en-US "Processor feature capabilities." #string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuFeaturesCapability_HELP #language en-US "Indicates processor feature capabilities, each bit corresponding to a specific feature." From 9c33f16f8cecba845e877295e8b9be805dd2fbb8 Mon Sep 17 00:00:00 2001 From: Shenglei Zhang Date: Thu, 14 Nov 2019 16:30:10 +0530 Subject: [PATCH 151/384] UefiCpuPkg: Update the coding styles In MpLib.c, remove the white space on a new line. In PageTbl.c and PiSmmCpuDxeSmm.h, update the comment style. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Signed-off-by: Shenglei Zhang Reviewed-by: Eric Dong Reviewed-by: Laszlo Ersek --- UefiCpuPkg/Library/MpInitLib/MpLib.c | 2 +- UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c | 2 +- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 2 +- UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index 49be5d5385d..d32adf0780b 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -475,7 +475,7 @@ CollectProcessorCount ( CpuPause (); } - + // // Enable x2APIC mode if // 1. Number of CPU is greater than 255; or diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c index f891a811126..2483f2ea849 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/Ia32/PageTbl.c @@ -342,7 +342,7 @@ RestoreCr2 ( @retval TRUE Access to non-SMRAM is restricted. @retval FALSE Access to non-SMRAM is not restricted. -*/ +**/ BOOLEAN IsRestrictedMemoryAccess ( VOID diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index daf977f654b..7e7c73f27f7 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -1455,7 +1455,7 @@ InitializeDataForMmMp ( @retval TRUE Access to non-SMRAM is restricted. @retval FALSE Access to non-SMRAM is not restricted. -*/ +**/ BOOLEAN IsRestrictedMemoryAccess ( VOID diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c index e5c4788c13d..810985df20a 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/X64/PageTbl.c @@ -1275,7 +1275,7 @@ RestoreCr2 ( @retval TRUE Access to non-SMRAM is restricted. @retval FALSE Access to non-SMRAM is not restricted. -*/ +**/ BOOLEAN IsRestrictedMemoryAccess ( VOID From c8ff8e05afb6a20b1ae66aa80bb8636b664be0b2 Mon Sep 17 00:00:00 2001 From: "Fan, ZhijuX" Date: Tue, 3 Dec 2019 17:04:25 +0800 Subject: [PATCH 152/384] BaseTools:Enhance the way to handling included dsc file BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2400 In Dsc Parser, included dsc file is parsed always no matter if its condition is False gUefiOvmfPkgTokenSpaceGuid.test1|FALSE !if gUefiOvmfPkgTokenSpaceGuid.test1 == FALSE !include OvmfPkg/test1.dsc !else !include OvmfPkg/test2.dsc !endif The patch avoids processing redundant dsc files and improves the way Tool handles them. In the above case, since the conditional result is FALSE, "test2.dsc" is not parsed. Signed-off-by: Zhiju.Fan Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- .../Source/Python/Workspace/MetaFileParser.py | 79 ++++++++++--------- 1 file changed, 40 insertions(+), 39 deletions(-) diff --git a/BaseTools/Source/Python/Workspace/MetaFileParser.py b/BaseTools/Source/Python/Workspace/MetaFileParser.py index 8a665b118ec..a3b6edbd15e 100644 --- a/BaseTools/Source/Python/Workspace/MetaFileParser.py +++ b/BaseTools/Source/Python/Workspace/MetaFileParser.py @@ -1612,46 +1612,47 @@ def __ProcessDirective(self): # First search the include file under the same directory as DSC file # IncludedFile1 = PathClass(IncludedFile, self.MetaFile.Dir) - ErrorCode, ErrorInfo1 = IncludedFile1.Validate() - if ErrorCode != 0: - # - # Also search file under the WORKSPACE directory - # - IncludedFile1 = PathClass(IncludedFile, GlobalData.gWorkspace) - ErrorCode, ErrorInfo2 = IncludedFile1.Validate() + if self._Enabled: + ErrorCode, ErrorInfo1 = IncludedFile1.Validate() if ErrorCode != 0: - EdkLogger.error('parser', ErrorCode, File=self._FileWithError, - Line=self._LineIndex + 1, ExtraData=ErrorInfo1 + "\n" + ErrorInfo2) - - self._FileWithError = IncludedFile1 - - FromItem = self._Content[self._ContentIndex - 1][0] - if self._InSubsection: - Owner = self._Content[self._ContentIndex - 1][8] - else: - Owner = self._Content[self._ContentIndex - 1][0] - IncludedFileTable = MetaFileStorage(self._RawTable.DB, IncludedFile1, MODEL_FILE_DSC, False, FromItem=FromItem) - Parser = DscParser(IncludedFile1, self._FileType, self._Arch, IncludedFileTable, - Owner=Owner, From=FromItem) - - self.IncludedFiles.add (IncludedFile1) - - # set the parser status with current status - Parser._SectionName = self._SectionName - Parser._SubsectionType = self._SubsectionType - Parser._InSubsection = self._InSubsection - Parser._SectionType = self._SectionType - Parser._Scope = self._Scope - Parser._Enabled = self._Enabled - # Parse the included file - Parser.StartParse() - # Insert all records in the table for the included file into dsc file table - Records = IncludedFileTable.GetAll() - if Records: - self._Content[self._ContentIndex:self._ContentIndex] = Records - self._Content.pop(self._ContentIndex - 1) - self._ValueList = None - self._ContentIndex -= 1 + # + # Also search file under the WORKSPACE directory + # + IncludedFile1 = PathClass(IncludedFile, GlobalData.gWorkspace) + ErrorCode, ErrorInfo2 = IncludedFile1.Validate() + if ErrorCode != 0: + EdkLogger.error('parser', ErrorCode, File=self._FileWithError, + Line=self._LineIndex + 1, ExtraData=ErrorInfo1 + "\n" + ErrorInfo2) + + self._FileWithError = IncludedFile1 + + FromItem = self._Content[self._ContentIndex - 1][0] + if self._InSubsection: + Owner = self._Content[self._ContentIndex - 1][8] + else: + Owner = self._Content[self._ContentIndex - 1][0] + IncludedFileTable = MetaFileStorage(self._RawTable.DB, IncludedFile1, MODEL_FILE_DSC, False, FromItem=FromItem) + Parser = DscParser(IncludedFile1, self._FileType, self._Arch, IncludedFileTable, + Owner=Owner, From=FromItem) + + self.IncludedFiles.add (IncludedFile1) + + # set the parser status with current status + Parser._SectionName = self._SectionName + Parser._SubsectionType = self._SubsectionType + Parser._InSubsection = self._InSubsection + Parser._SectionType = self._SectionType + Parser._Scope = self._Scope + Parser._Enabled = self._Enabled + # Parse the included file + Parser.StartParse() + # Insert all records in the table for the included file into dsc file table + Records = IncludedFileTable.GetAll() + if Records: + self._Content[self._ContentIndex:self._ContentIndex] = Records + self._Content.pop(self._ContentIndex - 1) + self._ValueList = None + self._ContentIndex -= 1 def __ProcessPackages(self): self._ValueList[0] = ReplaceMacro(self._ValueList[0], self._Macros) From 6cc63aee53264d4375c2245cd098addc27c08a5a Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Wed, 4 Dec 2019 08:43:24 +0800 Subject: [PATCH 153/384] MdeModulePkg: LzmaCustomDecompressLib.inf don't support EBC anymore After unifying the definition of size_t, EBC compiler has failure. So don't compile this inf file for EBC REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2398 Cc: Liming Gao Cc: Jian J Wang Cc: Hao A Wu Cc: Leif Lindholm Cc: Philippe Mathieu-Daude Reviewed-by: Liming Gao Reviewed-by: Philippe Mathieu-Daude Signed-off-by: Zhiguang Liu --- .../Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf | 2 +- MdeModulePkg/MdeModulePkg.dsc | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf index 42b741c64bc..e8061f54f9d 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf @@ -25,7 +25,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] diff --git a/MdeModulePkg/MdeModulePkg.dsc b/MdeModulePkg/MdeModulePkg.dsc index 4320839abfb..f7dbb27ce25 100644 --- a/MdeModulePkg/MdeModulePkg.dsc +++ b/MdeModulePkg/MdeModulePkg.dsc @@ -299,7 +299,6 @@ MdeModulePkg/Library/PeiDebugPrintHobLib/PeiDebugPrintHobLib.inf MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf MdeModulePkg/Library/PlatformHookLibSerialPortPpi/PlatformHookLibSerialPortPpi.inf - MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf MdeModulePkg/Library/PeiDebugLibDebugPpi/PeiDebugLibDebugPpi.inf MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf @@ -433,6 +432,7 @@ [Components.IA32, Components.X64, Components.ARM, Components.AARCH64] MdeModulePkg/Library/BrotliCustomDecompressLib/BrotliCustomDecompressLib.inf + MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf MdeModulePkg/Library/VarCheckUefiLib/VarCheckUefiLib.inf MdeModulePkg/Core/Dxe/DxeMain.inf { From c9416efeef0d4a0554db01f3fd1cdaede14856d7 Mon Sep 17 00:00:00 2001 From: Zhiguang Liu Date: Wed, 4 Dec 2019 08:45:35 +0800 Subject: [PATCH 154/384] MdeModulePkg: Add ARM/Aarch64 support which were missing REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2382 Add ARM/Aarch64 which were missing to VALID_ARCHITECTURES in LzmaCustomDecompressLib.inf Cc: Liming Gao Cc: Jian J Wang Cc: Hao A Wu Cc: Leif Lindholm Reviewed-by: Liming Gao Reviewed-by: Philippe Mathieu-Daude Signed-off-by: Zhiguang Liu --- .../Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf index e8061f54f9d..4ed1d83a404 100644 --- a/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf +++ b/MdeModulePkg/Library/LzmaCustomDecompressLib/LzmaCustomDecompressLib.inf @@ -25,7 +25,7 @@ # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 +# VALID_ARCHITECTURES = IA32 X64 AARCH64 ARM # [Sources] From d5cf0fba204d967c0df2c5404a472331656308e2 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Fri, 22 Nov 2019 19:31:45 +0800 Subject: [PATCH 155/384] ShellPkg: acpiview: Add support for parsing FACS Add support for parsing the ACPI FACS table. The FADT parser has also been updated as it links the FACS table using the FIRMWARE_CTRL or X_FIRMWARE_CTRL fields. Since the FACS table does not follow the standard ACPI header, the FADT parser extracts the FACS signature, length and version fields before invoking the FACS parser. Cc: Ray Ni Cc: Zhichao Gao Reviewed-by: Zhichao Gao Signed-off-by: Sami Mujawar --- .../UefiShellAcpiViewCommandLib/AcpiParser.h | 21 +++++ .../Parsers/Facs/FacsParser.c | 71 +++++++++++++++ .../Parsers/Fadt/FadtParser.c | 90 +++++++++++++++++-- .../UefiShellAcpiViewCommandLib.c | 1 + .../UefiShellAcpiViewCommandLib.inf | 1 + 5 files changed, 179 insertions(+), 5 deletions(-) create mode 100644 ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Facs/FacsParser.c diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h index 20ca358bddf..f374f8ebfe3 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h @@ -528,6 +528,27 @@ ParseAcpiDsdt ( IN UINT8 AcpiTableRevision ); +/** + This function parses the ACPI FACS table. + When trace is enabled this function parses the FACS table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiFacs ( + IN BOOLEAN Trace, + IN UINT8* Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ); + /** This function parses the ACPI FADT table. This function parses the FADT table and optionally traces the ACPI diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Facs/FacsParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Facs/FacsParser.c new file mode 100644 index 00000000000..d6bea86bdba --- /dev/null +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Facs/FacsParser.c @@ -0,0 +1,71 @@ +/** @file + FACS table parser + + Copyright (c) 2019, ARM Limited. All rights reserved. + SPDX-License-Identifier: BSD-2-Clause-Patent + + @par Reference(s): + - ACPI 6.3 Specification - January 2019 +**/ + +#include +#include +#include "AcpiParser.h" +#include "AcpiTableParser.h" + +/** + An ACPI_PARSER array describing the ACPI FACS Table. +**/ +STATIC CONST ACPI_PARSER FacsParser[] = { + {L"Signature", 4, 0, L"%c%c%c%c", Dump4Chars, NULL, NULL, NULL}, + {L"Length", 4, 4, L"%d", NULL, NULL, NULL, NULL}, + {L"Hardware Signature", 4, 8, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Firmware Waking Vector", 4, 12, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Global Lock", 4, 16, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Flags", 4, 20, L"0x%x", NULL, NULL, NULL, NULL}, + {L"X Firmware Walking Vector", 8, 24, L"0x%lx", NULL, NULL, NULL, NULL}, + {L"Version", 1, 32, L"%d", NULL, NULL, NULL, NULL}, + {L"Reserved", 3, 33, L"%x %x %x", Dump3Chars, NULL, NULL, NULL}, + {L"OSPM Flags", 4, 36, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Reserved", 8, 40, L"%x %x %x %x %x %x %x %x", Dump8Chars, NULL, NULL, + NULL}, + {L"Reserved", 8, 48, L"%x %x %x %x %x %x %x %x", Dump8Chars, NULL, NULL, + NULL}, + {L"Reserved", 8, 56, L"%x %x %x %x %x %x %x %x", Dump8Chars, NULL, NULL, + NULL} +}; + +/** + This function parses the ACPI FACS table. + When trace is enabled this function parses the FACS table and + traces the ACPI table fields. + + This function also performs validation of the ACPI table fields. + + @param [in] Trace If TRUE, trace the ACPI fields. + @param [in] Ptr Pointer to the start of the buffer. + @param [in] AcpiTableLength Length of the ACPI table. + @param [in] AcpiTableRevision Revision of the ACPI table. +**/ +VOID +EFIAPI +ParseAcpiFacs ( + IN BOOLEAN Trace, + IN UINT8* Ptr, + IN UINT32 AcpiTableLength, + IN UINT8 AcpiTableRevision + ) +{ + if (!Trace) { + return; + } + + ParseAcpi ( + Trace, + 0, + "FACS", + Ptr, + AcpiTableLength, + PARSER_PARAMS (FacsParser) + ); +} diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Fadt/FadtParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Fadt/FadtParser.c index e40c9ef8ee4..5b8cc174f16 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Fadt/FadtParser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Fadt/FadtParser.c @@ -5,17 +5,21 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): - - ACPI 6.2 Specification - Errata A, September 2017 + - ACPI 6.3 Specification - January 2019 **/ #include #include #include "AcpiParser.h" #include "AcpiTableParser.h" +#include "AcpiView.h" // Local variables STATIC CONST UINT32* DsdtAddress; STATIC CONST UINT64* X_DsdtAddress; +STATIC CONST UINT32* Flags; +STATIC CONST UINT32* FirmwareCtrl; +STATIC CONST UINT64* X_FirmwareCtrl; STATIC CONST UINT8* FadtMinorRevision; STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; @@ -24,6 +28,21 @@ STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; **/ #define HW_REDUCED_ACPI BIT20 +/** + Offset to the FACS signature from the start of the FACS. +**/ +#define FACS_SIGNATURE_OFFSET 0 + +/** + Offset to the FACS revision from the start of the FACS. +**/ +#define FACS_VERSION_OFFSET 32 + +/** + Offset to the FACS length from the start of the FACS. +**/ +#define FACS_LENGTH_OFFSET 4 + /** Get the ACPI XSDT header info. **/ @@ -113,7 +132,8 @@ ValidateFlags ( **/ STATIC CONST ACPI_PARSER FadtParser[] = { PARSE_ACPI_HEADER (&AcpiHdrInfo), - {L"FIRMWARE_CTRL", 4, 36, L"0x%x", NULL, NULL, ValidateFirmwareCtrl, NULL}, + {L"FIRMWARE_CTRL", 4, 36, L"0x%x", NULL, (VOID**)&FirmwareCtrl, + ValidateFirmwareCtrl, NULL}, {L"DSDT", 4, 40, L"0x%x", NULL, (VOID**)&DsdtAddress, NULL, NULL}, {L"Reserved", 1, 44, L"%x", NULL, NULL, NULL, NULL}, {L"Preferred_PM_Profile", 1, 45, L"0x%x", NULL, NULL, NULL, NULL}, @@ -150,13 +170,13 @@ STATIC CONST ACPI_PARSER FadtParser[] = { {L"CENTURY", 1, 108, L"0x%x", NULL, NULL, NULL, NULL}, {L"IAPC_BOOT_ARCH", 2, 109, L"0x%x", NULL, NULL, NULL, NULL}, {L"Reserved", 1, 111, L"0x%x", NULL, NULL, NULL, NULL}, - {L"Flags", 4, 112, L"0x%x", NULL, NULL, ValidateFlags, NULL}, + {L"Flags", 4, 112, L"0x%x", NULL, (VOID**)&Flags, ValidateFlags, NULL}, {L"RESET_REG", 12, 116, NULL, DumpGas, NULL, NULL, NULL}, {L"RESET_VALUE", 1, 128, L"0x%x", NULL, NULL, NULL, NULL}, {L"ARM_BOOT_ARCH", 2, 129, L"0x%x", NULL, NULL, NULL, NULL}, {L"FADT Minor Version", 1, 131, L"0x%x", NULL, (VOID**)&FadtMinorRevision, NULL, NULL}, - {L"X_FIRMWARE_CTRL", 8, 132, L"0x%lx", NULL, NULL, + {L"X_FIRMWARE_CTRL", 8, 132, L"0x%lx", NULL, (VOID**)&X_FirmwareCtrl, ValidateXFirmwareCtrl, NULL}, {L"X_DSDT", 8, 140, L"0x%lx", NULL, (VOID**)&X_DsdtAddress, NULL, NULL}, {L"X_PM1a_EVT_BLK", 12, 148, NULL, DumpGas, NULL, NULL, NULL}, @@ -192,7 +212,13 @@ ParseAcpiFadt ( IN UINT8 AcpiTableRevision ) { - UINT8* DsdtPtr; + EFI_STATUS Status; + UINT8* DsdtPtr; + UINT8* FirmwareCtrlPtr; + UINT32 FacsSignature; + UINT32 FacsLength; + UINT8 FacsRevision; + PARSE_ACPI_TABLE_PROC FacsParserProc; ParseAcpi ( Trace, @@ -214,6 +240,60 @@ ParseAcpiFadt ( } } + // If X_FIRMWARE_CTRL is not zero then use X_FIRMWARE_CTRL and ignore + // FIRMWARE_CTRL, else use FIRMWARE_CTRL. + if ((X_FirmwareCtrl != NULL) && (*X_FirmwareCtrl != 0)) { + FirmwareCtrlPtr = (UINT8*)(UINTN)(*X_FirmwareCtrl); + } else if ((FirmwareCtrl != NULL) && (*FirmwareCtrl != 0)) { + FirmwareCtrlPtr = (UINT8*)(UINTN)(*FirmwareCtrl); + } else { + FirmwareCtrlPtr = NULL; + // if HW_REDUCED_ACPI flag is not set, both FIRMWARE_CTRL and + // X_FIRMWARE_CTRL cannot be zero, and the FACS Table must be + // present. + if ((Trace) && + (Flags != NULL) && + ((*Flags & EFI_ACPI_6_3_HW_REDUCED_ACPI) != 0)) { + IncrementErrorCount (); + Print (L"ERROR: No FACS table found, " + L"both X_FIRMWARE_CTRL and FIRMWARE_CTRL are zero.\n"); + } + } + + if (FirmwareCtrlPtr != NULL) { + // The FACS table does not have a standard ACPI table header. Therefore, + // the signature, length and version needs to be initially parsed. + // The FACS signature is 4 bytes starting at offset 0. + FacsSignature = *(UINT32*)(FirmwareCtrlPtr + FACS_SIGNATURE_OFFSET); + + // The FACS length is 4 bytes starting at offset 4. + FacsLength = *(UINT32*)(FirmwareCtrlPtr + FACS_LENGTH_OFFSET); + + // The FACS version is 1 byte starting at offset 32. + FacsRevision = *(UINT8*)(FirmwareCtrlPtr + FACS_VERSION_OFFSET); + + Trace = ProcessTableReportOptions ( + FacsSignature, + FirmwareCtrlPtr, + FacsLength + ); + + Status = GetParser (FacsSignature, &FacsParserProc); + if (EFI_ERROR (Status)) { + Print ( + L"ERROR: No registered parser found for FACS.\n" + ); + return; + } + + FacsParserProc ( + Trace, + FirmwareCtrlPtr, + FacsLength, + FacsRevision + ); + } + // If X_DSDT is not zero then use X_DSDT and ignore DSDT, // else use DSDT. if (*X_DsdtAddress != 0) { diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c index 3ee0f0fe421..e0d5a810855 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.c @@ -29,6 +29,7 @@ ACPI_TABLE_PARSER ParserList[] = { {EFI_ACPI_6_2_DEBUG_PORT_2_TABLE_SIGNATURE, ParseAcpiDbg2}, {EFI_ACPI_6_2_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiDsdt}, + {EFI_ACPI_6_3_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE, ParseAcpiFacs}, {EFI_ACPI_6_2_FIXED_ACPI_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiFadt}, {EFI_ACPI_6_2_GENERIC_TIMER_DESCRIPTION_TABLE_SIGNATURE, ParseAcpiGtdt}, {EFI_ACPI_6_2_IO_REMAPPING_TABLE_SIGNATURE, ParseAcpiIort}, diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf index 1e2fa52b00a..ea504c934ae 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/UefiShellAcpiViewCommandLib.inf @@ -31,6 +31,7 @@ Parsers/Bgrt/BgrtParser.c Parsers/Dbg2/Dbg2Parser.c Parsers/Dsdt/DsdtParser.c + Parsers/Facs/FacsParser.c Parsers/Fadt/FadtParser.c Parsers/Gtdt/GtdtParser.c Parsers/Iort/IortParser.c From 965dbf97abec6b999b2dddb75ef746deed354019 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Mon, 25 Nov 2019 17:18:13 +0800 Subject: [PATCH 156/384] ShellPkg: acpiview: IORT Spec Rev D updates Updated IORT parser to conform to the IO Remapping Table, Platform Design Document, Revision D, March 2018. The following structure parsers have been updated: 1. SMMUv3 - added proximity domain and device Id mapping index. 2. RootComplex - added memory address size limit. 2. PMCG - added page 1 support. Cc: Ray Ni Cc: Zhichao Gao Reviewed-by: Zhichao Gao Signed-off-by: Sami Mujawar --- .../Parsers/Iort/IortParser.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Iort/IortParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Iort/IortParser.c index f1cdb9ac01d..72289c7680b 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Iort/IortParser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Iort/IortParser.c @@ -5,7 +5,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): - - IO Remapping Table, Platform Design Document, Revision C, 15 May 2017 + - IO Remapping Table, Platform Design Document, Revision D, March 2018 **/ #include @@ -193,7 +193,9 @@ STATIC CONST ACPI_PARSER IortNodeSmmuV3Parser[] = { {L"Event", 4, 44, L"0x%x", NULL, NULL, NULL, NULL}, {L"PRI", 4, 48, L"0x%x", NULL, NULL, NULL, NULL}, {L"GERR", 4, 52, L"0x%x", NULL, NULL, NULL, NULL}, - {L"Sync", 4, 56, L"0x%x", NULL, NULL, NULL, NULL} + {L"Sync", 4, 56, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Proximity domain", 4, 60, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Device ID mapping index", 4, 64, L"%d", NULL, NULL, NULL, NULL} }; /** @@ -231,7 +233,9 @@ STATIC CONST ACPI_PARSER IortNodeRootComplexParser[] = { PARSE_IORT_NODE_HEADER (NULL, NULL), {L"Memory access properties", 8, 16, L"0x%lx", NULL, NULL, NULL, NULL}, {L"ATS Attribute", 4, 24, L"0x%x", NULL, NULL, NULL, NULL}, - {L"PCI Segment number", 4, 28, L"0x%x", NULL, NULL, NULL, NULL} + {L"PCI Segment number", 4, 28, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Memory access size limit", 1, 32, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Reserved", 3, 33, L"%x %x %x", Dump3Chars, NULL, NULL, NULL} }; /** @@ -239,9 +243,10 @@ STATIC CONST ACPI_PARSER IortNodeRootComplexParser[] = { **/ STATIC CONST ACPI_PARSER IortNodePmcgParser[] = { PARSE_IORT_NODE_HEADER (ValidatePmcgIdMappingCount, NULL), - {L"Base Address", 8, 16, L"0x%lx", NULL, NULL, NULL, NULL}, + {L"Page 0 Base Address", 8, 16, L"0x%lx", NULL, NULL, NULL, NULL}, {L"Overflow interrupt GSIV", 4, 24, L"0x%x", NULL, NULL, NULL, NULL}, {L"Node reference", 4, 28, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Page 1 Base Address", 8, 32, L"0x%lx", NULL, NULL, NULL, NULL} }; /** From 2926498f01e6d8b77dff933e3e9c87eb56c709b4 Mon Sep 17 00:00:00 2001 From: Heinrich Schuchardt Date: Sun, 24 Nov 2019 18:33:20 +0800 Subject: [PATCH 157/384] ShellPkg/edit: typo "%d Lines Wrote" REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2379 When a file is saved in the edit command a status message L"%d Lines Wrote" is displayed. The hexedit command suffers from the same typo. Change the message to L"%d Lines Written". Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Zhichao Gao Signed-off-by: Heinrich Schuchardt --- ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/FileBuffer.c | 2 +- ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/FileBuffer.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/FileBuffer.c index fd324cc4a86..c9814e400c1 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/FileBuffer.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/Edit/FileBuffer.c @@ -1602,7 +1602,7 @@ FileBufferSave ( // // set status string // - Str = CatSPrint (NULL, L"%d Lines Wrote", NumLines); + Str = CatSPrint (NULL, L"%d Lines Written", NumLines); if (Str == NULL) { return EFI_OUT_OF_RESOURCES; } diff --git a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c index b393f2a4233..bb324ceafcc 100644 --- a/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c +++ b/ShellPkg/Library/UefiShellDebug1CommandsLib/HexEdit/FileImage.c @@ -368,7 +368,7 @@ HFileImageSave ( // // set status string // - Str = CatSPrint(NULL, L"%d Lines Wrote", NumLines); + Str = CatSPrint(NULL, L"%d Lines Written", NumLines); StatusBarSetStatusString (Str); FreePool (Str); From 94d4efb54ec4ca894287276ce22d29b6261dbc0b Mon Sep 17 00:00:00 2001 From: Zhichao Gao Date: Mon, 15 Jul 2019 14:23:21 +0800 Subject: [PATCH 158/384] ShellPkg/UefiHandleParsingLib: Fix error allocate pool REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1965 For function InsertNewGuidNameMapping, it rellocate the mGuidList with new size "mGuidListCount+1 * sizeof(GUID_INFO_BLOCK)". That isn't its purpose and would cause a overflow operation in "mGuidList[mGuidListCount - 1].xxx = xxx". Its purpose is to increase 1 block size of mGuidList. Change it to "(mGuidListCount + 1) * sizeof (GUID_INFO_BLOCK)". Adjust the coding style of this function. Cc: Jaben Carsey Cc: Ray Ni Cc: Andrew Fish Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- .../UefiHandleParsingLib/UefiHandleParsingLib.c | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c index f62d30ef677..500a95a89a8 100644 --- a/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c +++ b/ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.c @@ -2462,17 +2462,21 @@ InsertNewGuidNameMapping( IN CONST DUMP_PROTOCOL_INFO DumpFunc OPTIONAL ) { - ASSERT(Guid != NULL); - ASSERT(NameID != 0); + ASSERT (Guid != NULL); + ASSERT (NameID != 0); - mGuidList = ReallocatePool(mGuidListCount * sizeof(GUID_INFO_BLOCK), mGuidListCount+1 * sizeof(GUID_INFO_BLOCK), mGuidList); + mGuidList = ReallocatePool ( + mGuidListCount * sizeof (GUID_INFO_BLOCK), + (mGuidListCount + 1) * sizeof (GUID_INFO_BLOCK), + mGuidList + ); if (mGuidList == NULL) { mGuidListCount = 0; return (EFI_OUT_OF_RESOURCES); } mGuidListCount++; - mGuidList[mGuidListCount - 1].GuidId = AllocateCopyPool(sizeof(EFI_GUID), Guid); + mGuidList[mGuidListCount - 1].GuidId = AllocateCopyPool (sizeof (EFI_GUID), Guid); mGuidList[mGuidListCount - 1].StringId = NameID; mGuidList[mGuidListCount - 1].DumpInfo = DumpFunc; From 0f9395d7c5cc6ae2beaa2d87008fe158d04a8069 Mon Sep 17 00:00:00 2001 From: Sami Mujawar Date: Thu, 11 Apr 2019 11:41:36 -0700 Subject: [PATCH 159/384] ArmPkg: Dispatch deferred images after EndOfDxe Third party driver images loaded from Option ROM get queued for execution after EndOfDxe. These queued images need to be dispatched from the PlatformBootManagerLib. Since the queued images were not dispatched, the PCI Option ROM drivers were not getting loaded on Juno. Therefore, add call to EfiBootManagerDispatchDeferredImages() for dispatching deferred images from PlatformBootManagerLib. Signed-off-by: Sami Mujawar Reviewed-by: Ard Biesheuvel --- ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c b/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c index 39b892a4b29..e6e788e0f10 100644 --- a/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c +++ b/ArmPkg/Library/PlatformBootManagerLib/PlatformBm.c @@ -2,7 +2,7 @@ Implementation for PlatformBootManagerLib library class interfaces. Copyright (C) 2015-2016, Red Hat, Inc. - Copyright (c) 2014, ARM Ltd. All rights reserved.
+ Copyright (c) 2014 - 2019, ARM Ltd. All rights reserved.
Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
Copyright (c) 2016, Linaro Ltd. All rights reserved.
@@ -549,6 +549,11 @@ PlatformBootManagerBeforeConsole ( // EfiEventGroupSignal (&gEfiEndOfDxeEventGroupGuid); + // + // Dispatch deferred images after EndOfDxe event. + // + EfiBootManagerDispatchDeferredImages (); + // // Locate the PCI root bridges and make the PCI bus driver connect each, // non-recursively. This will produce a number of child handles with PciIo on From e8b9296c67dffaddd26dce06d8daaca6206fa620 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 5 Dec 2019 19:19:42 +0800 Subject: [PATCH 160/384] .pytool: Avoid "is" with a literal Python 3.8 warnings in CI plugins REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2304 To avoid SyntaxWarning with Python 3.8, change the 'is' operator by the conventional '==' comparator. Cc: Sean Brogan Cc: Bret Barkelew Cc: Michael D Kinney Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- .pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py | 2 +- .pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py index e2485f57084..9af4f72c8de 100644 --- a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py @@ -61,7 +61,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) - if abs_dsc_path is None or wsr_dsc_path is "" or not os.path.isfile(abs_dsc_path): + if abs_dsc_path is None or wsr_dsc_path == "" or not os.path.isfile(abs_dsc_path): tc.SetSkipped() tc.LogStdError("Package Dsc not found") return 0 diff --git a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py index 5dafcbc13f8..a62a7e912b1 100644 --- a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py +++ b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py @@ -67,7 +67,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, abs_dec_path = self.__GetPkgDec(abs_pkg_path) wsr_dec_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dec_path) - if abs_dec_path is None or wsr_dec_path is "" or not os.path.isfile(abs_dec_path): + if abs_dec_path is None or wsr_dec_path == "" or not os.path.isfile(abs_dec_path): tc.SetSkipped() tc.LogStdError("No DEC file {0} in package {1}".format(abs_dec_path, abs_pkg_path)) return -1 From 490a62beb7e1d084f14a93b895f9c89a49e4a51d Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 5 Dec 2019 19:19:41 +0800 Subject: [PATCH 161/384] BaseTools: Avoid "is" with a literal Python 3.8 warnings REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2304 The following statement produces a SyntaxWarning with Python 3.8: if str(FdRegion.RegionType) is 'FILE' and self.Platform.VpdToolGuid in \ str(FdRegion.RegionDataList): BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py:168: SyntaxWarning: \ "is" with a literal. Did you mean "=="? Change the 'is' operator by the conventional '==' comparator. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py index fde48b4b278..ec0c25bd148 100644 --- a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py @@ -165,7 +165,7 @@ def FdfProfile(self): if Fdf.CurrentFdName and Fdf.CurrentFdName in Fdf.Profile.FdDict: FdDict = Fdf.Profile.FdDict[Fdf.CurrentFdName] for FdRegion in FdDict.RegionList: - if str(FdRegion.RegionType) is 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList): + if str(FdRegion.RegionType) == 'FILE' and self.Platform.VpdToolGuid in str(FdRegion.RegionDataList): if int(FdRegion.Offset) % 8 != 0: EdkLogger.error("build", FORMAT_INVALID, 'The VPD Base Address %s must be 8-byte aligned.' % (FdRegion.Offset)) FdfProfile = Fdf.Profile From 9caaa79dd7e078ebb4012dde3b3d3a5d451df609 Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Fri, 6 Dec 2019 11:36:35 +0800 Subject: [PATCH 162/384] UefiCpuPkg/PiSmmCpuDxeSmm: Avoid allocate Token every time REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2388 Token is new introduced by MM MP Protocol. Current logic allocate Token every time when need to use it. The logic caused SMI latency raised to very high. Update logic to allocate Token buffer at driver's entry point. Later use the token from the allocated token buffer. Only when all the buffer have been used, then need to allocate new buffer. Reviewed-by: Ray Ni Signed-off-by: Eric Dong Acked-by: Laszlo Ersek --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 67 ++++++++++++++++++-- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 15 +++++ UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf | 3 + UefiCpuPkg/UefiCpuPkg.dec | 4 ++ UefiCpuPkg/UefiCpuPkg.uni | 3 + 5 files changed, 88 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 0685637c2b5..757f1056f78 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -492,6 +492,24 @@ FreeTokens ( { LIST_ENTRY *Link; PROCEDURE_TOKEN *ProcToken; + TOKEN_BUFFER *TokenBuf; + + // + // Only free the token buffer recorded in the OldTOkenBufList + // upon exiting SMI. Current token buffer stays allocated so + // next SMI doesn't need to re-allocate. + // + gSmmCpuPrivate->UsedTokenNum = 0; + + Link = GetFirstNode (&gSmmCpuPrivate->OldTokenBufList); + while (!IsNull (&gSmmCpuPrivate->OldTokenBufList, Link)) { + TokenBuf = TOKEN_BUFFER_FROM_LINK (Link); + + Link = RemoveEntryList (&TokenBuf->Link); + + FreePool (TokenBuf->Buffer); + FreePool (TokenBuf); + } while (!IsListEmpty (&gSmmCpuPrivate->TokenList)) { Link = GetFirstNode (&gSmmCpuPrivate->TokenList); @@ -499,7 +517,6 @@ FreeTokens ( RemoveEntryList (&ProcToken->Link); - FreePool ((VOID *)ProcToken->ProcedureToken); FreePool (ProcToken); } } @@ -1115,13 +1132,37 @@ CreateToken ( VOID ) { - PROCEDURE_TOKEN *ProcToken; + PROCEDURE_TOKEN *ProcToken; SPIN_LOCK *CpuToken; UINTN SpinLockSize; + TOKEN_BUFFER *TokenBuf; + UINT32 TokenCountPerChunk; SpinLockSize = GetSpinLockProperties (); - CpuToken = AllocatePool (SpinLockSize); - ASSERT (CpuToken != NULL); + TokenCountPerChunk = FixedPcdGet32 (PcdCpuSmmMpTokenCountPerChunk); + + if (gSmmCpuPrivate->UsedTokenNum == TokenCountPerChunk) { + DEBUG ((DEBUG_VERBOSE, "CpuSmm: No free token buffer, allocate new buffer!\n")); + + // + // Record current token buffer for later free action usage. + // Current used token buffer not in this list. + // + TokenBuf = AllocatePool (sizeof (TOKEN_BUFFER)); + ASSERT (TokenBuf != NULL); + TokenBuf->Signature = TOKEN_BUFFER_SIGNATURE; + TokenBuf->Buffer = gSmmCpuPrivate->CurrentTokenBuf; + + InsertTailList (&gSmmCpuPrivate->OldTokenBufList, &TokenBuf->Link); + + gSmmCpuPrivate->CurrentTokenBuf = AllocatePool (SpinLockSize * TokenCountPerChunk); + ASSERT (gSmmCpuPrivate->CurrentTokenBuf != NULL); + gSmmCpuPrivate->UsedTokenNum = 0; + } + + CpuToken = (SPIN_LOCK *)(gSmmCpuPrivate->CurrentTokenBuf + SpinLockSize * gSmmCpuPrivate->UsedTokenNum); + gSmmCpuPrivate->UsedTokenNum++; + InitializeSpinLock (CpuToken); AcquireSpinLock (CpuToken); @@ -1732,10 +1773,28 @@ InitializeDataForMmMp ( VOID ) { + UINTN SpinLockSize; + UINT32 TokenCountPerChunk; + + SpinLockSize = GetSpinLockProperties (); + TokenCountPerChunk = FixedPcdGet32 (PcdCpuSmmMpTokenCountPerChunk); + ASSERT (TokenCountPerChunk != 0); + if (TokenCountPerChunk == 0) { + DEBUG ((DEBUG_ERROR, "PcdCpuSmmMpTokenCountPerChunk should not be Zero!\n")); + CpuDeadLoop (); + } + DEBUG ((DEBUG_INFO, "CpuSmm: SpinLock Size = 0x%x, PcdCpuSmmMpTokenCountPerChunk = 0x%x\n", SpinLockSize, TokenCountPerChunk)); + + gSmmCpuPrivate->CurrentTokenBuf = AllocatePool (SpinLockSize * TokenCountPerChunk); + ASSERT (gSmmCpuPrivate->CurrentTokenBuf != NULL); + + gSmmCpuPrivate->UsedTokenNum = 0; + gSmmCpuPrivate->ApWrapperFunc = AllocatePool (sizeof (PROCEDURE_WRAPPER) * gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus); ASSERT (gSmmCpuPrivate->ApWrapperFunc != NULL); InitializeListHead (&gSmmCpuPrivate->TokenList); + InitializeListHead (&gSmmCpuPrivate->OldTokenBufList); } /** diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 7e7c73f27f7..5c1a01e42bf 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -217,6 +217,17 @@ typedef struct { #define PROCEDURE_TOKEN_FROM_LINK(a) CR (a, PROCEDURE_TOKEN, Link, PROCEDURE_TOKEN_SIGNATURE) +#define TOKEN_BUFFER_SIGNATURE SIGNATURE_32 ('T', 'K', 'B', 'S') + +typedef struct { + UINTN Signature; + LIST_ENTRY Link; + + UINT8 *Buffer; +} TOKEN_BUFFER; + +#define TOKEN_BUFFER_FROM_LINK(a) CR (a, TOKEN_BUFFER, Link, TOKEN_BUFFER_SIGNATURE) + // // Private structure for the SMM CPU module that is stored in DXE Runtime memory // Contains the SMM Configuration Protocols that is produced. @@ -243,6 +254,10 @@ typedef struct { PROCEDURE_WRAPPER *ApWrapperFunc; LIST_ENTRY TokenList; + LIST_ENTRY OldTokenBufList; + + UINT8 *CurrentTokenBuf; + UINT32 UsedTokenNum; // Only record tokens used in CurrentTokenBuf. } SMM_CPU_PRIVATE_DATA; extern SMM_CPU_PRIVATE_DATA *gSmmCpuPrivate; diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf index b12b2691f8c..76b14629967 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.inf @@ -140,6 +140,9 @@ gEfiMdeModulePkgTokenSpaceGuid.PcdHeapGuardPropertyMask ## CONSUMES gEfiMdePkgTokenSpaceGuid.PcdControlFlowEnforcementPropertyMask ## CONSUMES +[FixedPcd] + gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmMpTokenCountPerChunk ## CONSUMES + [Pcd.X64] gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmRestrictedMemoryAccess ## CONSUMES diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 12f4413ea5b..797f9486315 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -148,6 +148,10 @@ # @Prompt Specify size of good stack of exception which need switching stack. gUefiCpuPkgTokenSpaceGuid.PcdCpuKnownGoodStackSize|2048|UINT32|0x30002001 + ## Count of pre allocated SMM MP tokens per chunk. + # @Prompt Specify the count of pre allocated SMM MP tokens per chunk. + gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmMpTokenCountPerChunk|64|UINT32|0x30002002 + [PcdsFixedAtBuild, PcdsPatchableInModule] ## This value is the CPU Local APIC base address, which aligns the address on a 4-KByte boundary. # @Prompt Configure base address of CPU Local APIC diff --git a/UefiCpuPkg/UefiCpuPkg.uni b/UefiCpuPkg/UefiCpuPkg.uni index bfd696f48c3..c0d6ed51367 100644 --- a/UefiCpuPkg/UefiCpuPkg.uni +++ b/UefiCpuPkg/UefiCpuPkg.uni @@ -272,3 +272,6 @@ "24000000 - 6th and 7th generation Intel Core processors and Intel Xeon W Processor Family(24MHz).
\n" "19200000 - Intel Atom processors based on Goldmont Microarchitecture with CPUID signature 06_5CH(19.2MHz).
\n" +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuSmmMpTokenCountPerChunk_PROMPT #language en-US "Specify the count of pre allocated SMM MP tokens per chunk.\n" + +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuSmmMpTokenCountPerChunk_HELP #language en-US "This value used to specify the count of pre allocated SMM MP tokens per chunk.\n" From 62a75650e4f918a7aed8e325b8beed37247e4513 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 21 Nov 2019 09:32:26 +0100 Subject: [PATCH 163/384] EmbeddedPkg/NonCoherentDmaLib: implement support for DMA range limits Implement support for driving peripherals with limited DMA ranges to NonCoherentDmaLib, by adding a device address limit, and taking it, along with the device offset, into account when allocating or mapping DMA buffers. Signed-off-by: Ard Biesheuvel Tested-by: Pete Batard Acked-by: Philippe Mathieu-Daude Acked-by: Leif Lindholm --- EmbeddedPkg/EmbeddedPkg.dec | 6 + .../NonCoherentDmaLib/NonCoherentDmaLib.c | 165 ++++++++++++++++-- .../NonCoherentDmaLib/NonCoherentDmaLib.inf | 1 + 3 files changed, 160 insertions(+), 12 deletions(-) diff --git a/EmbeddedPkg/EmbeddedPkg.dec b/EmbeddedPkg/EmbeddedPkg.dec index 8812a6db7c3..69922802f47 100644 --- a/EmbeddedPkg/EmbeddedPkg.dec +++ b/EmbeddedPkg/EmbeddedPkg.dec @@ -186,6 +186,12 @@ # gEmbeddedTokenSpaceGuid.PcdDmaDeviceOffset|0x0|UINT64|0x0000058 + # + # Highest address value supported by the device for DMA addressing. Note + # that this value should be strictly greater than PcdDmaDeviceOffset. + # + gEmbeddedTokenSpaceGuid.PcdDmaDeviceLimit|0xFFFFFFFFFFFFFFFF|UINT64|0x000005A + # # Selection between DT and ACPI as a default # diff --git a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c index 78220f6358a..11534576543 100644 --- a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c +++ b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.c @@ -40,6 +40,8 @@ typedef struct { STATIC EFI_CPU_ARCH_PROTOCOL *mCpu; STATIC LIST_ENTRY UncachedAllocationList; +STATIC PHYSICAL_ADDRESS mDmaHostAddressLimit; + STATIC PHYSICAL_ADDRESS HostToDeviceAddress ( @@ -49,6 +51,102 @@ HostToDeviceAddress ( return (PHYSICAL_ADDRESS)(UINTN)Address + PcdGet64 (PcdDmaDeviceOffset); } +/** + Allocates one or more 4KB pages of a certain memory type at a specified + alignment. + + Allocates the number of 4KB pages specified by Pages of a certain memory type + with an alignment specified by Alignment. The allocated buffer is returned. + If Pages is 0, then NULL is returned. If there is not enough memory at the + specified alignment remaining to satisfy the request, then NULL is returned. + If Alignment is not a power of two and Alignment is not zero, then ASSERT(). + If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). + + @param MemoryType The type of memory to allocate. + @param Pages The number of 4 KB pages to allocate. + @param Alignment The requested alignment of the allocation. + Must be a power of two. + If Alignment is zero, then byte alignment is + used. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ +STATIC +VOID * +InternalAllocateAlignedPages ( + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + IN UINTN Alignment + ) +{ + EFI_STATUS Status; + EFI_PHYSICAL_ADDRESS Memory; + UINTN AlignedMemory; + UINTN AlignmentMask; + UINTN UnalignedPages; + UINTN RealPages; + + // + // Alignment must be a power of two or zero. + // + ASSERT ((Alignment & (Alignment - 1)) == 0); + + if (Pages == 0) { + return NULL; + } + if (Alignment > EFI_PAGE_SIZE) { + // + // Calculate the total number of pages since alignment is larger than page + // size. + // + AlignmentMask = Alignment - 1; + RealPages = Pages + EFI_SIZE_TO_PAGES (Alignment); + // + // Make sure that Pages plus EFI_SIZE_TO_PAGES (Alignment) does not + // overflow. + // + ASSERT (RealPages > Pages); + + Memory = mDmaHostAddressLimit; + Status = gBS->AllocatePages (AllocateMaxAddress, MemoryType, RealPages, + &Memory); + if (EFI_ERROR (Status)) { + return NULL; + } + AlignedMemory = ((UINTN)Memory + AlignmentMask) & ~AlignmentMask; + UnalignedPages = EFI_SIZE_TO_PAGES (AlignedMemory - (UINTN)Memory); + if (UnalignedPages > 0) { + // + // Free first unaligned page(s). + // + Status = gBS->FreePages (Memory, UnalignedPages); + ASSERT_EFI_ERROR (Status); + } + Memory = AlignedMemory + EFI_PAGES_TO_SIZE (Pages); + UnalignedPages = RealPages - Pages - UnalignedPages; + if (UnalignedPages > 0) { + // + // Free last unaligned page(s). + // + Status = gBS->FreePages (Memory, UnalignedPages); + ASSERT_EFI_ERROR (Status); + } + } else { + // + // Do not over-allocate pages in this case. + // + Memory = mDmaHostAddressLimit; + Status = gBS->AllocatePages (AllocateMaxAddress, MemoryType, Pages, + &Memory); + if (EFI_ERROR (Status)) { + return NULL; + } + AlignedMemory = (UINTN)Memory; + } + return (VOID *)AlignedMemory; +} + /** Provides the DMA controller-specific addresses needed to access system memory. @@ -111,7 +209,30 @@ DmaMap ( return EFI_OUT_OF_RESOURCES; } - if (Operation != MapOperationBusMasterRead && + if (((UINTN)HostAddress + *NumberOfBytes) > mDmaHostAddressLimit) { + + if (Operation == MapOperationBusMasterCommonBuffer) { + goto CommonBufferError; + } + + AllocSize = ALIGN_VALUE (*NumberOfBytes, mCpu->DmaBufferAlignment); + Map->BufferAddress = InternalAllocateAlignedPages (EfiBootServicesData, + EFI_SIZE_TO_PAGES (AllocSize), + mCpu->DmaBufferAlignment); + if (Map->BufferAddress == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto FreeMapInfo; + } + + if (Map->Operation == MapOperationBusMasterRead) { + CopyMem (Map->BufferAddress, (VOID *)(UINTN)Map->HostAddress, + *NumberOfBytes); + } + mCpu->FlushDataCache (mCpu, (UINTN)Map->BufferAddress, AllocSize, + EfiCpuFlushTypeWriteBack); + + *DeviceAddress = HostToDeviceAddress (Map->BufferAddress); + } else if (Operation != MapOperationBusMasterRead && ((((UINTN)HostAddress & (mCpu->DmaBufferAlignment - 1)) != 0) || ((*NumberOfBytes & (mCpu->DmaBufferAlignment - 1)) != 0))) { @@ -128,12 +249,7 @@ DmaMap ( // on uncached buffers. // if (Operation == MapOperationBusMasterCommonBuffer) { - DEBUG ((DEBUG_ERROR, - "%a: Operation type 'MapOperationBusMasterCommonBuffer' is only " - "supported\non memory regions that were allocated using " - "DmaAllocateBuffer ()\n", __FUNCTION__)); - Status = EFI_UNSUPPORTED; - goto FreeMapInfo; + goto CommonBufferError; } // @@ -199,6 +315,12 @@ DmaMap ( return EFI_SUCCESS; +CommonBufferError: + DEBUG ((DEBUG_ERROR, + "%a: Operation type 'MapOperationBusMasterCommonBuffer' is only " + "supported\non memory regions that were allocated using " + "DmaAllocateBuffer ()\n", __FUNCTION__)); + Status = EFI_UNSUPPORTED; FreeMapInfo: FreePool (Map); @@ -229,6 +351,7 @@ DmaUnmap ( MAP_INFO_INSTANCE *Map; EFI_STATUS Status; VOID *Buffer; + UINTN AllocSize; if (Mapping == NULL) { ASSERT (FALSE); @@ -238,7 +361,17 @@ DmaUnmap ( Map = (MAP_INFO_INSTANCE *)Mapping; Status = EFI_SUCCESS; - if (Map->DoubleBuffer) { + if (((UINTN)Map->HostAddress + Map->NumberOfBytes) > mDmaHostAddressLimit) { + AllocSize = ALIGN_VALUE (Map->NumberOfBytes, mCpu->DmaBufferAlignment); + if (Map->Operation == MapOperationBusMasterWrite) { + mCpu->FlushDataCache (mCpu, (UINTN)Map->BufferAddress, AllocSize, + EfiCpuFlushTypeInvalidate); + CopyMem ((VOID *)(UINTN)Map->HostAddress, Map->BufferAddress, + Map->NumberOfBytes); + } + FreePages (Map->BufferAddress, EFI_SIZE_TO_PAGES (AllocSize)); + } else if (Map->DoubleBuffer) { + ASSERT (Map->Operation == MapOperationBusMasterWrite); if (Map->Operation != MapOperationBusMasterWrite) { @@ -335,10 +468,9 @@ DmaAllocateAlignedBuffer ( return EFI_INVALID_PARAMETER; } - if (MemoryType == EfiBootServicesData) { - Allocation = AllocateAlignedPages (Pages, Alignment); - } else if (MemoryType == EfiRuntimeServicesData) { - Allocation = AllocateAlignedRuntimePages (Pages, Alignment); + if (MemoryType == EfiBootServicesData || + MemoryType == EfiRuntimeServicesData) { + Allocation = InternalAllocateAlignedPages (MemoryType, Pages, Alignment); } else { return EFI_INVALID_PARAMETER; } @@ -479,6 +611,15 @@ NonCoherentDmaLibConstructor ( { InitializeListHead (&UncachedAllocationList); + // + // Ensure that the combination of DMA addressing offset and limit produces + // a sane value. + // + ASSERT (PcdGet64 (PcdDmaDeviceLimit) > PcdGet64 (PcdDmaDeviceOffset)); + + mDmaHostAddressLimit = PcdGet64 (PcdDmaDeviceLimit) - + PcdGet64 (PcdDmaDeviceOffset); + // Get the Cpu protocol for later use return gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, (VOID **)&mCpu); } diff --git a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.inf b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.inf index 2db751afee9..1a21cfe4ff2 100644 --- a/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.inf +++ b/EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.inf @@ -38,6 +38,7 @@ [Pcd] gEmbeddedTokenSpaceGuid.PcdDmaDeviceOffset + gEmbeddedTokenSpaceGuid.PcdDmaDeviceLimit [Depex] gEfiCpuArchProtocolGuid From 49054b6bb66d35484e92c65f27584c4283a60986 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Thu, 21 Nov 2019 09:32:27 +0100 Subject: [PATCH 164/384] EmbeddedPkg: implement EDK2 IoMmu protocol wrapping DmaLib Implement a version of the EDK2 IoMmu protocol that is a simple wrapper around DmaLib. This is intended to be used to wrap NonCoherentDmaLib so that the generic PCI infrastructure can be used to implement support for non cache-coherent DMA. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm Reviewed-by: Philippe Mathieu-Daude Tested-by: Pete Batard --- .../NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.c | 257 ++++++++++++++++++ .../NonCoherentIoMmuDxe.inf | 43 +++ EmbeddedPkg/EmbeddedPkg.dsc | 5 + 3 files changed, 305 insertions(+) create mode 100644 EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.c create mode 100644 EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.inf diff --git a/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.c b/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.c new file mode 100644 index 00000000000..4b0afe47de4 --- /dev/null +++ b/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.c @@ -0,0 +1,257 @@ +/** @file + + Copyright (c) 2019, Linaro, Ltd. All rights reserved.
+ + This program and the accompanying materials are licensed and made available + under the terms and conditions of the BSD License which accompanies this + distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +**/ + +#include +#include +#include +#include +#include +#include + +/** + Set IOMMU attribute for a system memory. + + If the IOMMU protocol exists, the system memory cannot be used + for DMA by default. + + When a device requests a DMA access for a system memory, + the device driver need use SetAttribute() to update the IOMMU + attribute to request DMA access (read and/or write). + + The DeviceHandle is used to identify which device submits the request. + The IOMMU implementation need translate the device path to an IOMMU device + ID, and set IOMMU hardware register accordingly. + 1) DeviceHandle can be a standard PCI device. + The memory for BusMasterRead need set EDKII_IOMMU_ACCESS_READ. + The memory for BusMasterWrite need set EDKII_IOMMU_ACCESS_WRITE. + The memory for BusMasterCommonBuffer need set + EDKII_IOMMU_ACCESS_READ|EDKII_IOMMU_ACCESS_WRITE. + After the memory is used, the memory need set 0 to keep it being + protected. + 2) DeviceHandle can be an ACPI device (ISA, I2C, SPI, etc). + The memory for DMA access need set EDKII_IOMMU_ACCESS_READ and/or + EDKII_IOMMU_ACCESS_WRITE. + + @param[in] This The protocol instance pointer. + @param[in] DeviceHandle The device who initiates the DMA access + request. + @param[in] Mapping The mapping value returned from Map(). + @param[in] IoMmuAccess The IOMMU access. + + @retval EFI_SUCCESS The IoMmuAccess is set for the memory range + specified by DeviceAddress and Length. + @retval EFI_INVALID_PARAMETER DeviceHandle is an invalid handle. + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by + Map(). + @retval EFI_INVALID_PARAMETER IoMmuAccess specified an illegal combination + of access. + @retval EFI_UNSUPPORTED DeviceHandle is unknown by the IOMMU. + @retval EFI_UNSUPPORTED The bit mask of IoMmuAccess is not supported + by the IOMMU. + @retval EFI_UNSUPPORTED The IOMMU does not support the memory range + specified by Mapping. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + modify the IOMMU access. + @retval EFI_DEVICE_ERROR The IOMMU device reported an error while + attempting the operation. + +**/ +STATIC +EFI_STATUS +EFIAPI +NonCoherentIoMmuSetAttribute ( + IN EDKII_IOMMU_PROTOCOL *This, + IN EFI_HANDLE DeviceHandle, + IN VOID *Mapping, + IN UINT64 IoMmuAccess + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Provides the controller-specific addresses required to access system memory + from a DMA bus master. On SEV guest, the DMA operations must be performed on + shared buffer hence we allocate a bounce buffer to map the HostAddress to a + DeviceAddress. The Encryption attribute is removed from the DeviceAddress + buffer. + + @param This The protocol instance pointer. + @param Operation Indicates if the bus master is going to read or + write to system memory. + @param HostAddress The system memory address to map to the PCI + controller. + @param NumberOfBytes On input the number of bytes to map. On output + the number of bytes that were mapped. + @param DeviceAddress The resulting map address for the bus master + PCI controller to use to access the hosts + HostAddress. + @param Mapping A resulting value to pass to Unmap(). + + @retval EFI_SUCCESS The range was mapped for the returned + NumberOfBytes. + @retval EFI_UNSUPPORTED The HostAddress cannot be mapped as a common + buffer. + @retval EFI_INVALID_PARAMETER One or more parameters are invalid. + @retval EFI_OUT_OF_RESOURCES The request could not be completed due to a + lack of resources. + @retval EFI_DEVICE_ERROR The system hardware could not map the requested + address. + +**/ +STATIC +EFI_STATUS +EFIAPI +NonCoherentIoMmuMap ( + IN EDKII_IOMMU_PROTOCOL *This, + IN EDKII_IOMMU_OPERATION Operation, + IN VOID *HostAddress, + IN OUT UINTN *NumberOfBytes, + OUT EFI_PHYSICAL_ADDRESS *DeviceAddress, + OUT VOID **Mapping + ) +{ + DMA_MAP_OPERATION DmaOperation; + + switch (Operation) { + case EdkiiIoMmuOperationBusMasterRead: + case EdkiiIoMmuOperationBusMasterRead64: + DmaOperation = MapOperationBusMasterRead; + break; + + case EdkiiIoMmuOperationBusMasterWrite: + case EdkiiIoMmuOperationBusMasterWrite64: + DmaOperation = MapOperationBusMasterWrite; + break; + + case EdkiiIoMmuOperationBusMasterCommonBuffer: + case EdkiiIoMmuOperationBusMasterCommonBuffer64: + DmaOperation = MapOperationBusMasterCommonBuffer; + break; + + default: + ASSERT (FALSE); + return EFI_INVALID_PARAMETER; + } + + return DmaMap (DmaOperation, HostAddress, NumberOfBytes, + DeviceAddress, Mapping); +} + +/** + Completes the Map() operation and releases any corresponding resources. + + @param This The protocol instance pointer. + @param Mapping The mapping value returned from Map(). + + @retval EFI_SUCCESS The range was unmapped. + @retval EFI_INVALID_PARAMETER Mapping is not a value that was returned by + Map(). + @retval EFI_DEVICE_ERROR The data was not committed to the target system + memory. +**/ +STATIC +EFI_STATUS +EFIAPI +NonCoherentIoMmuUnmap ( + IN EDKII_IOMMU_PROTOCOL *This, + IN VOID *Mapping + ) +{ + return DmaUnmap (Mapping); +} + +/** + Allocates pages that are suitable for an OperationBusMasterCommonBuffer or + OperationBusMasterCommonBuffer64 mapping. + + @param This The protocol instance pointer. + @param Type This parameter is not used and must be ignored. + @param MemoryType The type of memory to allocate, + EfiBootServicesData or EfiRuntimeServicesData. + @param Pages The number of pages to allocate. + @param HostAddress A pointer to store the base system memory + address of the allocated range. + @param Attributes The requested bit mask of attributes for the + allocated range. + + @retval EFI_SUCCESS The requested memory pages were allocated. + @retval EFI_UNSUPPORTED Attributes is unsupported. The only legal + attribute bits are MEMORY_WRITE_COMBINE and + MEMORY_CACHED. + @retval EFI_INVALID_PARAMETER One or more parameters are invalid. + @retval EFI_OUT_OF_RESOURCES The memory pages could not be allocated. + +**/ +STATIC +EFI_STATUS +EFIAPI +NonCoherentIoMmuAllocateBuffer ( + IN EDKII_IOMMU_PROTOCOL *This, + IN EFI_ALLOCATE_TYPE Type, + IN EFI_MEMORY_TYPE MemoryType, + IN UINTN Pages, + IN OUT VOID **HostAddress, + IN UINT64 Attributes + ) +{ + return DmaAllocateBuffer (MemoryType, Pages, HostAddress); +} + +/** + Frees memory that was allocated with AllocateBuffer(). + + @param This The protocol instance pointer. + @param Pages The number of pages to free. + @param HostAddress The base system memory address of the allocated + range. + + @retval EFI_SUCCESS The requested memory pages were freed. + @retval EFI_INVALID_PARAMETER The memory range specified by HostAddress and + Pages was not allocated with AllocateBuffer(). + +**/ +STATIC +EFI_STATUS +EFIAPI +NonCoherentIoMmuFreeBuffer ( + IN EDKII_IOMMU_PROTOCOL *This, + IN UINTN Pages, + IN VOID *HostAddress + ) +{ + return DmaFreeBuffer (Pages, HostAddress); +} + +STATIC EDKII_IOMMU_PROTOCOL mNonCoherentIoMmuOps = { + EDKII_IOMMU_PROTOCOL_REVISION, + NonCoherentIoMmuSetAttribute, + NonCoherentIoMmuMap, + NonCoherentIoMmuUnmap, + NonCoherentIoMmuAllocateBuffer, + NonCoherentIoMmuFreeBuffer, +}; + + +EFI_STATUS +EFIAPI +NonCoherentIoMmuDxeEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return gBS->InstallMultipleProtocolInterfaces (&ImageHandle, + &gEdkiiIoMmuProtocolGuid, &mNonCoherentIoMmuOps, + NULL); +} diff --git a/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.inf b/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.inf new file mode 100644 index 00000000000..de70cfb4cad --- /dev/null +++ b/EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.inf @@ -0,0 +1,43 @@ +#/** @file +# +# Copyright (c) 2019, Linaro, Ltd. All rights reserved.
+# +# This program and the accompanying materials are licensed and made available +# under the terms and conditions of the BSD License which accompanies this +# distribution. The full text of the license may be found at +# http://opensource.org/licenses/bsd-license.php +# +# THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, +# WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR +# IMPLIED. +# +#**/ + +[Defines] + INF_VERSION = 1.27 + BASE_NAME = NonCoherentIoMmuDxe + FILE_GUID = 7ed510aa-9cdc-49d2-a306-6e11e359f9b3 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = NonCoherentIoMmuDxeEntryPoint + +[Sources] + NonCoherentIoMmuDxe.c + +[Packages] + EmbeddedPkg/EmbeddedPkg.dec + MdeModulePkg/MdeModulePkg.dec + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib + DmaLib + UefiBootServicesTableLib + UefiDriverEntryPoint + +[Protocols] + gEdkiiIoMmuProtocolGuid ## PRODUCES + +[Depex] + TRUE diff --git a/EmbeddedPkg/EmbeddedPkg.dsc b/EmbeddedPkg/EmbeddedPkg.dsc index a8a151eb40c..8842acc4cbf 100644 --- a/EmbeddedPkg/EmbeddedPkg.dsc +++ b/EmbeddedPkg/EmbeddedPkg.dsc @@ -238,6 +238,11 @@ EmbeddedPkg/Drivers/ConsolePrefDxe/ConsolePrefDxe.inf EmbeddedPkg/Drivers/DtPlatformDxe/DtPlatformDxe.inf + EmbeddedPkg/Drivers/NonCoherentIoMmuDxe/NonCoherentIoMmuDxe.inf { + + DmaLib|EmbeddedPkg/Library/NonCoherentDmaLib/NonCoherentDmaLib.inf + } + [Components.ARM] EmbeddedPkg/Drivers/Isp1761UsbDxe/Isp1761UsbDxe.inf From 804666c86e7b6f04fe5c5cfdb13199c19e0e99b0 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Fri, 6 Dec 2019 15:21:33 +0000 Subject: [PATCH 165/384] Maintainers: assume co-maintainership of StandaloneMmPkg Achin has indicated that he no longer has the bandwidth available to co-maintain StandaloneMmPkg, and has asked Sami and me to step in. Reviewed-by: Laszlo Ersek Reviewed-by: Leif Lindholm Reviewed-by: Sami Mujawar Reviewed-by: Jiewen Yao Reviewed-by: Achin Gupta Signed-off-by: Ard Biesheuvel --- Maintainers.txt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index 180ad35d097..d6e8d5d5c79 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -481,6 +481,7 @@ S: Maintained StandaloneMmPkg F: StandaloneMmPkg/ -M: Achin Gupta +M: Ard Biesheuvel +M: Sami Mujawar M: Jiewen Yao R: Supreeth Venkatesh From 13c5e34a1b8bfedbd10ea038cfcbae5caeab6652 Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Mon, 2 Dec 2019 16:24:19 +0800 Subject: [PATCH 166/384] BaseTools: Add build option for dependency file generation BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2311 Add /showIncludes for msvc and -MMD -MF $@.deps for GCC and CLANG Remove /MP for msvc since /MP does not work with /showIncludes Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Cc: Michael D Kinney Reviewed-by: Liming Gao --- BaseTools/Conf/tools_def.template | 181 ++++++++++++++++-------------- 1 file changed, 98 insertions(+), 83 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index ca0b122dbb6..41a6ca246e0 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -147,6 +147,9 @@ DEFINE DEFAULT_WIN_ASL_BIN = DEF(WIN_IASL_BIN) DEFINE DEFAULT_WIN_ASL_FLAGS = DEF(IASL_FLAGS) DEFINE DEFAULT_WIN_ASL_OUTFLAGS = DEF(IASL_OUTFLAGS) +# MSFT Build Flag for included header file list generation +DEFINE MSFT_DEPS_FLAGS = /showIncludes + DEFINE MSFT_ASLPP_FLAGS = /nologo /E /C /FIAutoGen.h DEFINE MSFT_ASLCC_FLAGS = /nologo /c /FIAutoGen.h /TC /Dmain=ReferenceAcpiTable DEFINE MSFT_ASLDLINK_FLAGS = /NODEFAULTLIB /ENTRY:ReferenceAcpiTable /SUBSYSTEM:CONSOLE @@ -334,12 +337,16 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc # Required to build platforms or ACPI tables: # Microsoft ASL ACPI Compiler (asl.exe) v4.0.0 from # http://download.microsoft.com/download/2/c/1/2c16c7e0-96c1-40f5-81fc-3e4bf7b65496/microsoft_asl_compiler-v4-0-0.msi +# Notes: Since this tool chain is obsolete, it doesn’t enable the compiler option for included header file list generation, +# and lose the incremental build capability. # RVCTLINUX -unix- Requires: # ARM C/C++ Compiler, 5.00 # Optional: # Required to build platforms or ACPI tables: # Intel(r) ACPI Compiler from # https://acpica.org/downloads +# Notes: Since this tool chain is obsolete, it doesn’t enable the compiler option for included header file list generation, +# and lose the incremental build capability. # * Commented out - All versions of VS2005 use the same standard install directory # #################################################################################### @@ -415,7 +422,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc *_VS2008_*_APP_FLAGS = /nologo /E /TC *_VS2008_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2008_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2008_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2008_*_ASM16_PATH = DEF(VS2008_BIN)\ml.exe ################## @@ -478,9 +485,9 @@ NOOPT_VS2008_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2008_X64_ASLPP_PATH = DEF(VS2008_BINX64)\cl.exe *_VS2008_X64_ASLDLINK_PATH = DEF(VS2008_BINX64)\link.exe - DEBUG_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2008_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2008_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2008_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -531,7 +538,7 @@ NOOPT_VS2008_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2008x86_*_APP_FLAGS = /nologo /E /TC *_VS2008x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2008x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2008x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2008x86_*_ASM16_PATH = DEF(VS2008x86_BIN)\ml.exe ################## @@ -562,9 +569,9 @@ NOOPT_VS2008_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2008x86_IA32_ASM_PATH = DEF(VS2008x86_BIN)\ml.exe *_VS2008x86_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /MP -RELEASE_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 +RELEASE_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2008x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2008x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2008x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -594,10 +601,9 @@ NOOPT_VS2008x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2008x86_X64_DLINK_PATH = DEF(VS2008x86_BINX64)\link.exe *_VS2008x86_X64_ASLDLINK_PATH = DEF(VS2008x86_BINX64)\link.exe - DEBUG_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP - + DEBUG_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2008x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2008x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2008x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd NOOPT_VS2008x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi @@ -650,7 +656,7 @@ NOOPT_VS2008x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2010_*_APP_FLAGS = /nologo /E /TC *_VS2010_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2010_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2010_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2010_*_ASM16_PATH = DEF(VS2010_BIN)\ml.exe ################## @@ -681,9 +687,9 @@ NOOPT_VS2008x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2010_IA32_ASLDLINK_PATH = DEF(VS2010_BIN)\link.exe *_VS2010_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /MP -RELEASE_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Zi /Gm /Od /MP + DEBUG_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 +RELEASE_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2010_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Zi /Gm /Od DEBUG_VS2010_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2010_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -713,9 +719,9 @@ NOOPT_VS2010_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2010_X64_ASLPP_PATH = DEF(VS2010_BINX64)\cl.exe *_VS2010_X64_ASLDLINK_PATH = DEF(VS2010_BINX64)\link.exe - DEBUG_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2010_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2010_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2010_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -766,7 +772,7 @@ NOOPT_VS2010_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2010x86_*_APP_FLAGS = /nologo /E /TC *_VS2010x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2010x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2010x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2010x86_*_ASM16_PATH = DEF(VS2010x86_BIN)\ml.exe ################## @@ -797,9 +803,9 @@ NOOPT_VS2010_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2010x86_IA32_ASM_PATH = DEF(VS2010x86_BIN)\ml.exe *_VS2010x86_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /MP -RELEASE_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 +RELEASE_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2010x86_IA32_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2010x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2010x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -829,9 +835,9 @@ NOOPT_VS2010x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2010x86_X64_DLINK_PATH = DEF(VS2010x86_BINX64)\link.exe *_VS2010x86_X64_ASLDLINK_PATH = DEF(VS2010x86_BINX64)\link.exe - DEBUG_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2010x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2010x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2010x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -884,7 +890,7 @@ NOOPT_VS2010x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2012_*_APP_FLAGS = /nologo /E /TC *_VS2012_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2012_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2012_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2012_*_ASM16_PATH = DEF(VS2012_BIN)\ml.exe ################## @@ -915,9 +921,9 @@ NOOPT_VS2010x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2012_IA32_ASLDLINK_PATH = DEF(VS2012_BIN)\link.exe *_VS2012_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /MP -RELEASE_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 +RELEASE_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2012_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2012_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2012_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -947,9 +953,9 @@ NOOPT_VS2012_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2012_X64_ASLPP_PATH = DEF(VS2012_BINX64)\cl.exe *_VS2012_X64_ASLDLINK_PATH = DEF(VS2012_BINX64)\link.exe - DEBUG_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2012_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2012_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2012_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1000,7 +1006,7 @@ NOOPT_VS2012_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2012x86_*_APP_FLAGS = /nologo /E /TC *_VS2012x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2012x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2012x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2012x86_*_ASM16_PATH = DEF(VS2012x86_BIN)\ml.exe ################## @@ -1031,9 +1037,9 @@ NOOPT_VS2012_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2012x86_IA32_ASM_PATH = DEF(VS2012x86_BIN)\ml.exe *_VS2012x86_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /MP -RELEASE_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 +RELEASE_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2012x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2012x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2012x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1063,9 +1069,9 @@ NOOPT_VS2012x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2012x86_X64_DLINK_PATH = DEF(VS2012x86_BINX64)\link.exe *_VS2012x86_X64_ASLDLINK_PATH = DEF(VS2012x86_BINX64)\link.exe - DEBUG_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /MP -RELEASE_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /MP -NOOPT_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 +RELEASE_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF +NOOPT_VS2012x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2012x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2012x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1118,7 +1124,7 @@ NOOPT_VS2012x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2013_*_APP_FLAGS = /nologo /E /TC *_VS2013_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2013_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2013_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2013_*_ASM16_PATH = DEF(VS2013_BIN)\ml.exe ################## @@ -1149,9 +1155,9 @@ NOOPT_VS2012x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2013_IA32_ASLDLINK_PATH = DEF(VS2013_BIN)\link.exe *_VS2013_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2013_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2013_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2013_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1181,9 +1187,9 @@ NOOPT_VS2013_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2013_X64_ASLPP_PATH = DEF(VS2013_BINX64)\cl.exe *_VS2013_X64_ASLDLINK_PATH = DEF(VS2013_BINX64)\link.exe - DEBUG_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2013_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2013_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2013_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1234,7 +1240,7 @@ NOOPT_VS2013_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2013x86_*_APP_FLAGS = /nologo /E /TC *_VS2013x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2013x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h - +*_VS2013x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2013x86_*_ASM16_PATH = DEF(VS2013x86_BIN)\ml.exe ################## @@ -1265,9 +1271,9 @@ NOOPT_VS2013_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2013x86_IA32_ASM_PATH = DEF(VS2013x86_BIN)\ml.exe *_VS2013x86_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2013x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2013x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2013x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1297,9 +1303,9 @@ NOOPT_VS2013x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2013x86_X64_DLINK_PATH = DEF(VS2013x86_BINX64)\link.exe *_VS2013x86_X64_ASLDLINK_PATH = DEF(VS2013x86_BINX64)\link.exe - DEBUG_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2013x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2013x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2013x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1353,7 +1359,7 @@ NOOPT_VS2013x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2015_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2015_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h *_VS2015_*_DLINK2_FLAGS = - +*_VS2015_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2015_*_ASM16_PATH = DEF(VS2015_BIN)\ml.exe ################## @@ -1384,9 +1390,9 @@ NOOPT_VS2013x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2015_IA32_ASLDLINK_PATH = DEF(VS2015_BIN)\link.exe *_VS2015_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2015_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2015_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2015_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1416,9 +1422,9 @@ NOOPT_VS2015_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2015_X64_ASLPP_PATH = DEF(VS2015_BINX64)\cl.exe *_VS2015_X64_ASLDLINK_PATH = DEF(VS2015_BINX64)\link.exe - DEBUG_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2015_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2015_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2015_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1470,7 +1476,7 @@ NOOPT_VS2015_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2015x86_*_PP_FLAGS = /nologo /E /TC /FIAutoGen.h *_VS2015x86_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h *_VS2015x86_*_DLINK2_FLAGS = - +*_VS2015x86_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) *_VS2015x86_*_ASM16_PATH = DEF(VS2015x86_BIN)\ml.exe ################## @@ -1501,9 +1507,9 @@ NOOPT_VS2015_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /OPT *_VS2015x86_IA32_ASM_PATH = DEF(VS2015x86_BIN)\ml.exe *_VS2015x86_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2015x86_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2015x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2015x86_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1533,9 +1539,9 @@ NOOPT_VS2015x86_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2015x86_X64_DLINK_PATH = DEF(VS2015x86_BINX64)\link.exe *_VS2015x86_X64_ASLDLINK_PATH = DEF(VS2015x86_BINX64)\link.exe - DEBUG_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2015x86_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2015x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2015x86_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1589,7 +1595,7 @@ NOOPT_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2017_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h *_VS2017_*_DLINK2_FLAGS = /WHOLEARCHIVE *_VS2017_*_ASM16_PATH = DEF(VS2017_BIN_IA32)\ml.exe - +*_VS2017_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) ################## # ASL definitions ################## @@ -1615,9 +1621,9 @@ NOOPT_VS2015x86_X64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2017_IA32_ASM_PATH = DEF(VS2017_BIN_IA32)\ml.exe *_VS2017_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2017_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2017_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2017_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1645,9 +1651,9 @@ NOOPT_VS2017_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /O *_VS2017_X64_DLINK_PATH = DEF(VS2017_BIN_X64)\link.exe *_VS2017_X64_ASLDLINK_PATH = DEF(VS2017_BIN_X64)\link.exe - DEBUG_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2017_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2017_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2017_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1752,7 +1758,7 @@ NOOPT_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2019_*_VFRPP_FLAGS = /nologo /E /TC /DVFRCOMPILE /FI$(MODULE_NAME)StrDefs.h *_VS2019_*_DLINK2_FLAGS = /WHOLEARCHIVE *_VS2019_*_ASM16_PATH = DEF(VS2019_BIN_IA32)\ml.exe - +*_VS2019_*_DEPS_FLAGS = DEF(MSFT_DEPS_FLAGS) ################## # ASL definitions ################## @@ -1778,9 +1784,9 @@ NOOPT_VS2017_AARCH64_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF *_VS2019_IA32_ASM_PATH = DEF(VS2019_BIN_IA32)\ml.exe *_VS2019_IA32_MAKE_FLAGS = /nologo - DEBUG_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw /MP -RELEASE_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od /MP + DEBUG_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Gw +RELEASE_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2 /GL /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2019_IA32_CC_FLAGS = /nologo /arch:IA32 /c /WX /GS- /W4 /Gs32768 /D UNICODE /FIAutoGen.h /EHs-c- /GR- /GF /Gy /Z7 /Od DEBUG_VS2019_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd /Zi RELEASE_VS2019_IA32_ASM_FLAGS = /nologo /c /WX /W3 /Cx /coff /Zd @@ -1808,9 +1814,9 @@ NOOPT_VS2019_IA32_DLINK_FLAGS = /NOLOGO /NODEFAULTLIB /IGNORE:4001 /OPT:REF /O *_VS2019_X64_DLINK_PATH = DEF(VS2019_BIN_X64)\link.exe *_VS2019_X64_ASLDLINK_PATH = DEF(VS2019_BIN_X64)\link.exe - DEBUG_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw /MP -RELEASE_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw /MP -NOOPT_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od /MP + DEBUG_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Gw +RELEASE_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /O1b2s /GL /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Gw +NOOPT_VS2019_X64_CC_FLAGS = /nologo /c /WX /GS- /W4 /Gs32768 /D UNICODE /Gy /FIAutoGen.h /EHs-c- /GR- /GF /Z7 /Od DEBUG_VS2019_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd /Zi RELEASE_VS2019_X64_ASM_FLAGS = /nologo /c /WX /W3 /Cx /Zd @@ -1941,6 +1947,9 @@ DEFINE GCC_X64_RC_FLAGS = -I binary -O elf64-x86-64 -B i386 DEFINE GCC_ARM_RC_FLAGS = -I binary -O elf32-littlearm -B arm --rename-section .data=.hii DEFINE GCC_AARCH64_RC_FLAGS = -I binary -O elf64-littleaarch64 -B aarch64 --rename-section .data=.hii +# GCC Build Flag for included header file list generation +DEFINE GCC_DEPS_FLAGS = -MMD -MF $@.deps + DEFINE GCC48_ALL_CC_FLAGS = -g -fshort-wchar -fno-builtin -fno-strict-aliasing -Wall -Werror -Wno-array-bounds -ffunction-sections -fdata-sections -include AutoGen.h -fno-common -DSTRING_ARRAY_NAME=$(BASE_NAME)Strings DEFINE GCC48_IA32_X64_DLINK_COMMON = -nostdlib -Wl,-n,-q,--gc-sections -z common-page-size=0x20 DEFINE GCC48_IA32_CC_FLAGS = DEF(GCC48_ALL_CC_FLAGS) -m32 -march=i586 -malign-double -fno-stack-protector -D EFI32 -fno-asynchronous-unwind-tables -Wno-address @@ -2030,6 +2039,7 @@ DEFINE GCC5_ASLCC_FLAGS = DEF(GCC49_ASLCC_FLAGS) -fno-lto *_GCC48_*_APP_FLAGS = *_GCC48_*_ASL_FLAGS = DEF(IASL_FLAGS) *_GCC48_*_ASL_OUTFLAGS = DEF(IASL_OUTFLAGS) +*_GCC48_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) ################## # GCC48 IA32 definitions @@ -2169,6 +2179,7 @@ RELEASE_GCC48_AARCH64_CC_FLAGS = DEF(GCC48_AARCH64_CC_FLAGS) -Wno-unused-but-s *_GCC49_*_APP_FLAGS = *_GCC49_*_ASL_FLAGS = DEF(IASL_FLAGS) *_GCC49_*_ASL_OUTFLAGS = DEF(IASL_OUTFLAGS) +*_GCC49_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) ################## # GCC49 IA32 definitions @@ -2315,6 +2326,7 @@ RELEASE_GCC49_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_GCC5_*_APP_FLAGS = *_GCC5_*_ASL_FLAGS = DEF(IASL_FLAGS) *_GCC5_*_ASL_OUTFLAGS = DEF(IASL_OUTFLAGS) +*_GCC5_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) ################## # GCC5 IA32 definitions @@ -2480,6 +2492,7 @@ RELEASE_GCC5_AARCH64_DLINK_XIPFLAGS = -z common-page-size=0x20 *_CLANG35_*_ASLPP_PATH = ENV(CLANG35_BIN)clang *_CLANG35_*_DLINK_PATH = ENV(CLANG35_BIN)clang *_CLANG35_*_ASLDLINK_PATH = ENV(CLANG35_BIN)clang +*_CLANG35_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) DEFINE CLANG35_ARM_TARGET = -target arm-linux-gnueabi DEFINE CLANG35_AARCH64_TARGET = -target aarch64-linux-gnu @@ -2547,7 +2560,7 @@ RELEASE_CLANG35_AARCH64_CC_FLAGS = DEF(CLANG35_AARCH64_CC_FLAGS) $(ARCHCC_FLAGS) *_CLANG38_*_APP_FLAGS = *_CLANG38_*_ASL_FLAGS = DEF(IASL_FLAGS) *_CLANG38_*_ASL_OUTFLAGS = DEF(IASL_OUTFLAGS) - +*_CLANG38_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) DEFINE CLANG38_IA32_PREFIX = ENV(CLANG38_BIN) DEFINE CLANG38_X64_PREFIX = ENV(CLANG38_BIN) @@ -2737,6 +2750,7 @@ RELEASE_CLANG38_AARCH64_DLINK_FLAGS = DEF(CLANG38_AARCH64_DLINK_FLAGS) -flto -Wl *_CLANGPDB_*_ASL_FLAGS = DEF(DEFAULT_WIN_ASL_FLAGS) *_CLANGPDB_*_ASL_OUTFLAGS = DEF(DEFAULT_WIN_ASL_OUTFLAGS) *_CLANGPDB_*_ASLDLINK_FLAGS = DEF(MSFT_ASLDLINK_FLAGS) +*_CLANGPDB_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) DEFINE CLANGPDB_IA32_PREFIX = ENV(CLANG_BIN) DEFINE CLANGPDB_X64_PREFIX = ENV(CLANG_BIN) @@ -2840,6 +2854,7 @@ NOOPT_CLANGPDB_X64_DLINK2_FLAGS = *_XCODE5_*_ASLDLINK_PATH = ld *_XCODE5_*_DSYMUTIL_PATH = /usr/bin/dsymutil *_XCODE5_*_MTOC_PATH = /usr/local/bin/mtoc +*_XCODE5_*_DEPS_FLAGS = DEF(GCC_DEPS_FLAGS) ################## # ASL definitions From e6edbe315fc3fbd02783cb4faa9284f8d05c410d Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Wed, 20 Nov 2019 10:58:28 +0800 Subject: [PATCH 167/384] BaseTools: Generate dependent files for ASL and ASM files BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2311 Implement the function in Trim tool to get the included file list for ASL and ASM file. Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Reviewed-by: Liming Gao --- BaseTools/Source/Python/Trim/Trim.py | 115 ++++++++++++++++++++++----- 1 file changed, 95 insertions(+), 20 deletions(-) diff --git a/BaseTools/Source/Python/Trim/Trim.py b/BaseTools/Source/Python/Trim/Trim.py index 24c3fafa76f..c5638376e41 100644 --- a/BaseTools/Source/Python/Trim/Trim.py +++ b/BaseTools/Source/Python/Trim/Trim.py @@ -56,6 +56,10 @@ gAslCIncludePattern = re.compile(r'^(\s*)#include\s*[<"]\s*([-\\/\w.]+)\s*([>"])', re.MULTILINE) ## Patterns used to convert EDK conventions to EDK2 ECP conventions +## Regular expression for finding header file inclusions +gIncludePattern = re.compile(r"^[ \t]*[%]?[ \t]*include(?:[ \t]*(?:\\(?:\r\n|\r|\n))*[ \t]*)*(?:\(?[\"<]?[ \t]*)([-\w.\\/() \t]+)(?:[ \t]*[\">]?\)?)", re.MULTILINE | re.UNICODE | re.IGNORECASE) + + ## file cache to avoid circular include in ASL file gIncludedAslFile = [] @@ -253,9 +257,10 @@ def TrimPreprocessedVfr(Source, Target): # first for the included file; otherwise, only the path specified # in the IncludePathList will be searched. # -def DoInclude(Source, Indent='', IncludePathList=[], LocalSearchPath=None): +def DoInclude(Source, Indent='', IncludePathList=[], LocalSearchPath=None, IncludeFileList = None, filetype=None): NewFileContent = [] - + if IncludeFileList is None: + IncludeFileList = [] try: # # Search LocalSearchPath first if it is specified. @@ -288,24 +293,37 @@ def DoInclude(Source, Indent='', IncludePathList=[], LocalSearchPath=None): ExtraData= "%s -> %s" % (" -> ".join(gIncludedAslFile), IncludeFile)) return [] gIncludedAslFile.append(IncludeFile) - + IncludeFileList.append(IncludeFile.strip()) for Line in F: LocalSearchPath = None - Result = gAslIncludePattern.findall(Line) - if len(Result) == 0: - Result = gAslCIncludePattern.findall(Line) - if len(Result) == 0 or os.path.splitext(Result[0][1])[1].lower() not in [".asl", ".asi"]: + if filetype == "ASL": + Result = gAslIncludePattern.findall(Line) + if len(Result) == 0: + Result = gAslCIncludePattern.findall(Line) + if len(Result) == 0 or os.path.splitext(Result[0][1])[1].lower() not in [".asl", ".asi"]: + NewFileContent.append("%s%s" % (Indent, Line)) + continue + # + # We should first search the local directory if current file are using pattern #include "XXX" + # + if Result[0][2] == '"': + LocalSearchPath = os.path.dirname(IncludeFile) + CurrentIndent = Indent + Result[0][0] + IncludedFile = Result[0][1] + NewFileContent.extend(DoInclude(IncludedFile, CurrentIndent, IncludePathList, LocalSearchPath,IncludeFileList,filetype)) + NewFileContent.append("\n") + elif filetype == "ASM": + Result = gIncludePattern.findall(Line) + if len(Result) == 0: NewFileContent.append("%s%s" % (Indent, Line)) continue - # - # We should first search the local directory if current file are using pattern #include "XXX" - # - if Result[0][2] == '"': - LocalSearchPath = os.path.dirname(IncludeFile) - CurrentIndent = Indent + Result[0][0] - IncludedFile = Result[0][1] - NewFileContent.extend(DoInclude(IncludedFile, CurrentIndent, IncludePathList, LocalSearchPath)) - NewFileContent.append("\n") + + IncludedFile = Result[0] + + IncludedFile = IncludedFile.strip() + IncludedFile = os.path.normpath(IncludedFile) + NewFileContent.extend(DoInclude(IncludedFile, '', IncludePathList, LocalSearchPath,IncludeFileList,filetype)) + NewFileContent.append("\n") gIncludedAslFile.pop() @@ -320,7 +338,7 @@ def DoInclude(Source, Indent='', IncludePathList=[], LocalSearchPath=None): # @param Target File to store the trimmed content # @param IncludePathFile The file to log the external include path # -def TrimAslFile(Source, Target, IncludePathFile): +def TrimAslFile(Source, Target, IncludePathFile,AslDeps = False): CreateDirectory(os.path.dirname(Target)) SourceDir = os.path.dirname(Source) @@ -349,8 +367,11 @@ def TrimAslFile(Source, Target, IncludePathFile): EdkLogger.warn("Trim", "Invalid include line in include list file.", IncludePathFile, LineNum) except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=IncludePathFile) - - Lines = DoInclude(Source, '', IncludePathList) + AslIncludes = [] + Lines = DoInclude(Source, '', IncludePathList,IncludeFileList=AslIncludes,filetype='ASL') + AslIncludes = [item for item in AslIncludes if item !=Source] + if AslDeps and AslIncludes: + SaveFileOnChange(os.path.join(os.path.dirname(Target),os.path.basename(Source))+".trim.deps", " \\\n".join([Source+":"] +AslIncludes),False) # # Undef MIN and MAX to avoid collision in ASL source code @@ -364,6 +385,54 @@ def TrimAslFile(Source, Target, IncludePathFile): except: EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target) +## Trim ASM file +# +# Output ASM include statement with the content the included file +# +# @param Source File to be trimmed +# @param Target File to store the trimmed content +# @param IncludePathFile The file to log the external include path +# +def TrimAsmFile(Source, Target, IncludePathFile): + CreateDirectory(os.path.dirname(Target)) + + SourceDir = os.path.dirname(Source) + if SourceDir == '': + SourceDir = '.' + + # + # Add source directory as the first search directory + # + IncludePathList = [SourceDir] + # + # If additional include path file is specified, append them all + # to the search directory list. + # + if IncludePathFile: + try: + LineNum = 0 + with open(IncludePathFile, 'r') as File: + FileLines = File.readlines() + for Line in FileLines: + LineNum += 1 + if Line.startswith("/I") or Line.startswith ("-I"): + IncludePathList.append(Line[2:].strip()) + else: + EdkLogger.warn("Trim", "Invalid include line in include list file.", IncludePathFile, LineNum) + except: + EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=IncludePathFile) + AsmIncludes = [] + Lines = DoInclude(Source, '', IncludePathList,IncludeFileList=AsmIncludes,filetype='ASM') + AsmIncludes = [item for item in AsmIncludes if item != Source] + if AsmIncludes: + SaveFileOnChange(os.path.join(os.path.dirname(Target),os.path.basename(Source))+".trim.deps", " \\\n".join([Source+":"] +AsmIncludes),False) + # save all lines trimmed + try: + with open(Target, 'w') as File: + File.writelines(Lines) + except: + EdkLogger.error("Trim", FILE_OPEN_FAILURE, ExtraData=Target) + def GenerateVfrBinSec(ModuleName, DebugDir, OutputFile): VfrNameList = [] if os.path.isdir(DebugDir): @@ -440,8 +509,12 @@ def Options(): help="The input file is preprocessed VFR file"), make_option("--Vfr-Uni-Offset", dest="FileType", const="VfrOffsetBin", action="store_const", help="The input file is EFI image"), + make_option("--asl-deps", dest="AslDeps", const="True", action="store_const", + help="Generate Asl dependent files."), make_option("-a", "--asl-file", dest="FileType", const="Asl", action="store_const", help="The input file is ASL file"), + make_option( "--asm-file", dest="FileType", const="Asm", action="store_const", + help="The input file is asm file"), make_option("-c", "--convert-hex", dest="ConvertHex", action="store_true", help="Convert standard hex format (0xabcd) to MASM format (abcdh)"), @@ -515,9 +588,11 @@ def Main(): elif CommandOptions.FileType == "Asl": if CommandOptions.OutputFile is None: CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii' - TrimAslFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile) + TrimAslFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile,CommandOptions.AslDeps) elif CommandOptions.FileType == "VfrOffsetBin": GenerateVfrBinSec(CommandOptions.ModuleName, CommandOptions.DebugDir, CommandOptions.OutputFile) + elif CommandOptions.FileType == "Asm": + TrimAsmFile(InputFile, CommandOptions.OutputFile, CommandOptions.IncludePathFile) else : if CommandOptions.OutputFile is None: CommandOptions.OutputFile = os.path.splitext(InputFile)[0] + '.iii' From cb277815d5ea92718eed2d334641451ce65b0ff5 Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Mon, 2 Dec 2019 16:25:32 +0800 Subject: [PATCH 168/384] BaseTools: Update build_rule.txt to generate dependent files. BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2311 Enable the dependent files generation function for compilers and Trim tool. Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Reviewed-by: Liming Gao --- BaseTools/Conf/build_rule.template | 96 +++++++++++++++++------------- 1 file changed, 54 insertions(+), 42 deletions(-) diff --git a/BaseTools/Conf/build_rule.template b/BaseTools/Conf/build_rule.template index 84d8426e7d8..51748bc0655 100755 --- a/BaseTools/Conf/build_rule.template +++ b/BaseTools/Conf/build_rule.template @@ -81,6 +81,8 @@ # will be generated only when this macro is used in command line. # This is intended to get over the long command line limitation. # ) +# $(DEPS_FLAGS) This is a tool flag to have c compiler generate dependent header file list for a source file. +# To enable incremental build, this flag must apply to $(CC), $(VFRPP), $(PP), $(ASLCC) and $(ASLPP). # # $(CP) copy command # $(MV) move command @@ -123,14 +125,14 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj - "$(CC)" /Fo${dst} $(CC_FLAGS) $(INC) ${src} + "$(CC)" /Fo${dst} $(DEPS_FLAGS) $(CC_FLAGS) $(INC) ${src} # For RVCTCYGWIN CC_FLAGS must be first to work around pathing issues - "$(CC)" $(CC_FLAGS) -c -o ${dst} $(INC) ${src} + "$(CC)" $(DEPS_FLAGS) $(CC_FLAGS) -c -o ${dst} $(INC) ${src} - "$(CC)" $(CC_FLAGS) -o ${dst} $(INC) ${src} + "$(CC)" $(DEPS_FLAGS) $(CC_FLAGS) -o ${dst} $(INC) ${src} [C-Code-File.BASE.AARCH64,C-Code-File.SEC.AARCH64,C-Code-File.PEI_CORE.AARCH64,C-Code-File.PEIM.AARCH64,C-Code-File.BASE.ARM,C-Code-File.SEC.ARM,C-Code-File.PEI_CORE.ARM,C-Code-File.PEIM.ARM] @@ -167,15 +169,17 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i - "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iii + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iiii ${d_path}(+)${s_base}.ii + "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iiii - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iiii ${d_path}(+)${s_base}.ii # For RVCTCYGWIN ASM_FLAGS must be first to work around pathing issues - "$(ASM)" $(ASM_FLAGS) -o ${dst} $(INC) ${d_path}(+)${s_base}.iii + "$(ASM)" $(ASM_FLAGS) -o ${dst} $(INC) ${d_path}(+)${s_base}.iiii [Assembly-Code-File.COMMON.ARM,Assembly-Code-File.COMMON.AARCH64] # Remove --convert-hex for ARM as it breaks MSFT assemblers @@ -192,20 +196,23 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i - "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iii + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iiii ${d_path}(+)${s_base}.ii + "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iiii - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code --trim-long -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i - "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iii + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code --trim-long -o ${d_path}(+)${s_base}.iiii ${d_path}(+)${s_base}.ii + "$(ASM)" /Fo${dst} $(ASM_FLAGS) /I${s_path} $(INC) ${d_path}(+)${s_base}.iiii - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iiii ${d_path}(+)${s_base}.ii # For RVCTCYGWIN ASM_FLAGS must be first to work around pathing issues - "$(ASM)" $(ASM_FLAGS) -o ${dst} $(INC) ${d_path}(+)${s_base}.iii + "$(ASM)" $(ASM_FLAGS) -o ${dst} $(INC) ${d_path}(+)${s_base}.iiii [Nasm-Assembly-Code-File.COMMON.COMMON] @@ -218,8 +225,9 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --trim-long --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii "$(NASM)" -I${s_path}(+) $(NASM_INC) $(NASM_FLAGS) -o $dst ${d_path}(+)${s_base}.iii [Device-Tree-Source-File] @@ -249,7 +257,7 @@ $(DEBUG_DIR)(+)${s_dir}(+)${s_base}.c - "$(VFRPP)" $(VFRPP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_base}.i + "$(VFRPP)" $(DEPS_FLAGS) $(VFRPP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_base}.i "$(VFR)" $(VFR_FLAGS) --string-db $(OUTPUT_DIR)(+)$(MODULE_NAME)StrDefs.hpk --output-directory ${d_path} $(OUTPUT_DIR)(+)${s_base}.i [Object-File] @@ -400,7 +408,7 @@ $(MAKE_FILE) - "$(PP)" $(APP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i + "$(PP)" $(DEPS_FLAGS) $(APP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i Trim --source-code -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i GenDepex -t $(MODULE_TYPE) -o ${dst} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii @@ -415,14 +423,14 @@ $(MAKE_FILE) - Trim --asl-file -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src} - "$(ASLPP)" $(ASLPP_FLAGS) $(INC) /I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii + Trim --asl-file --asl-deps -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(ASLPP)" $(DEPS_FLAGS) $(ASLPP_FLAGS) $(INC) /I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii "$(ASL)" $(ASL_FLAGS) $(ASL_OUTFLAGS)${dst} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii - Trim --asl-file -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src} - "$(ASLPP)" $(ASLPP_FLAGS) $(INC) -I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii + Trim --asl-file --asl-deps -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(ASLPP)" $(DEPS_FLAGS) $(ASLPP_FLAGS) $(INC) -I${s_path} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii Trim --source-code -l -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iii "$(ASL)" $(ASL_FLAGS) $(ASL_OUTFLAGS)${dst} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.iiii @@ -437,12 +445,12 @@ $(MAKE_FILE) - "$(ASLCC)" /Fo$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) /Fo$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" /OUT:$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) - "$(ASLCC)" -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) @@ -457,22 +465,22 @@ $(MAKE_FILE) - "$(ASLCC)" /Fo$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) /Fo$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" /OUT:$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) - "$(ASLCC)" -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) - "$(ASLCC)" -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) -c -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(CC_FLAGS) $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" /OUT:$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(GENFW_FLAGS) - "$(ASLCC)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(INC) ${src} + "$(ASLCC)" $(DEPS_FLAGS) -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASLCC_FLAGS) $(DEPS_FLAGS) $(INC) ${src} "$(ASLDLINK)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(ASLDLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj "$(MTOC)" -subsystem $(MODULE_TYPE) $(MTOC_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.dll $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.pecoff "$(GENFW)" -o ${dst} -c $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.pecoff $(GENFW_FLAGS) @@ -489,21 +497,24 @@ $(OUTPUT_DIR)(+)${s_base}.com - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code --convert-hex --trim-long -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii cd $(OUTPUT_DIR)(+)${s_dir} "$(ASM16)" /nologo /c /omf $(INC) /Fo$(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj ${d_path}(+)${s_base}.iii "$(ASMLINK)" $(ASMLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj,${dst},,,, - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o {d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii "$(ASM)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASM_FLAGS) $(INC) ${d_path}(+)${s_base}.iii "$(DLINK)" -o ${dst} $(DLINK_FLAGS) --start-group $(DLINK_SPATH) $(LIBS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj --end-group - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii "$(ASM)" -o $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj $(ASM_FLAGS) $(INC) ${d_path}(+)${s_base}.iii "$(SLINK)" $(SLINK_FLAGS) $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.slib $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.obj otool -t $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.slib | hex2bin.py ${dst} @@ -520,9 +531,10 @@ $(OUTPUT_DIR)(+)${s_base}.bin - "$(PP)" $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.i - Trim --source-code --convert-hex -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.i - "$(NASM)" -I${s_path}(+) -l ${d_path}(+)${s_base}.lst $(NASMB_FLAGS) -o $dst ${d_path}(+)${s_base}.iii + Trim --asm-file -o ${d_path}(+)${s_base}.i -i $(INC_LIST) ${src} + "$(PP)" $(DEPS_FLAGS) $(PP_FLAGS) $(INC) ${src} > ${d_path}(+)${s_base}.ii + Trim --source-code --convert-hex -o ${d_path}(+)${s_base}.iii ${d_path}(+)${s_base}.ii + "$(NASM)" -I${s_path}(+) -l ${d_path}(+)${s_base}.lst $(NASMB_FLAGS) $(NASM_INC) -o $dst ${d_path}(+)${s_base}.iii # copy the output file with .com postfix that be same to the output file of .asm16 $(CP) ${dst} $(OUTPUT_DIR)(+)${s_base}.com @@ -623,7 +635,7 @@ $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.hpk - "$(VFRPP)" $(VFRPP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i + "$(VFRPP)" $(DEPS_FLAGS) $(VFRPP_FLAGS) $(INC) ${src} > $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i "$(VFR)" $(VFR_FLAGS) --create-ifr-package --string-db $(OUTPUT_DIR)(+)$(MODULE_NAME)StrDefs.hpk --output-directory $(OUTPUT_DIR)(+)${s_dir} $(OUTPUT_DIR)(+)${s_dir}(+)${s_base}.i [Hii-Binary-Package.UEFI_HII] From 0c3e8e9947a6c13b4327dd11b20acb95441701cf Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Wed, 20 Nov 2019 10:58:30 +0800 Subject: [PATCH 169/384] BaseTools: Enhance Basetool for incremental build BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2311 Include dependency file in Makefile to enhance incremental build Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Reviewed-by: Liming Gao --- BaseTools/Source/Python/AutoGen/GenMake.py | 83 ++--- .../Source/Python/AutoGen/IncludesAutoGen.py | 284 ++++++++++++++++++ .../Source/Python/AutoGen/ModuleAutoGen.py | 23 ++ BaseTools/Source/Python/build/build.py | 63 +++- 4 files changed, 380 insertions(+), 73 deletions(-) create mode 100644 BaseTools/Source/Python/AutoGen/IncludesAutoGen.py diff --git a/BaseTools/Source/Python/AutoGen/GenMake.py b/BaseTools/Source/Python/AutoGen/GenMake.py index 59a01a7f243..fe94f9a4c23 100755 --- a/BaseTools/Source/Python/AutoGen/GenMake.py +++ b/BaseTools/Source/Python/AutoGen/GenMake.py @@ -185,6 +185,12 @@ def Generate(self, FileType=gMakeType): self._FileType = FileType FileContent = self._TEMPLATE_.Replace(self._TemplateDict) FileName = self._FILE_NAME_[FileType] + if not os.path.exists(os.path.join(self._AutoGenObject.MakeFileDir, "deps.txt")): + with open(os.path.join(self._AutoGenObject.MakeFileDir, "deps.txt"),"w+") as fd: + fd.write("") + if not os.path.exists(os.path.join(self._AutoGenObject.MakeFileDir, "dependency")): + with open(os.path.join(self._AutoGenObject.MakeFileDir, "dependency"),"w+") as fd: + fd.write("") return SaveFileOnChange(os.path.join(self._AutoGenObject.MakeFileDir, FileName), FileContent, False) ## Return a list of directory creation command string @@ -304,9 +310,6 @@ class ModuleMakefile(BuildFile): ${BEGIN}${file_macro} ${END} -COMMON_DEPS = ${BEGIN}${common_dependency_file} \\ - ${END} - # # Overridable Target Macro Definitions # @@ -382,6 +385,8 @@ class ModuleMakefile(BuildFile): \t@"$(MAKE)" $(MAKE_FLAGS) -f $(BUILD_DIR)${separator}${makefile_name} fds \t@cd $(MODULE_BUILD_DIR) +${INCLUDETAG} + # # Individual Object Build Targets # @@ -515,9 +520,6 @@ def _TemplateDict(self): # Remove duplicated include path, if any if Attr == "FLAGS": Value = RemoveDupOption(Value, IncPrefix, MyAgo.IncludePathList) - if self._AutoGenObject.BuildRuleFamily == TAB_COMPILER_MSFT and Tool == 'CC' and '/GM' in Value: - Value = Value.replace(' /MP', '') - MyAgo.BuildOption[Tool][Attr] = Value if Tool == "OPTROM" and PCI_COMPRESS_Flag: ValueList = Value.split() if ValueList: @@ -540,7 +542,7 @@ def _TemplateDict(self): UnexpandMacro = [] NewStr = [] for Str in StrList: - if '$' in Str: + if '$' in Str or '-MMD' in Str or '-MF' in Str: UnexpandMacro.append(Str) else: NewStr.append(Str) @@ -590,10 +592,9 @@ def _TemplateDict(self): ) FileMacroList.append(FileMacro) # Add support when compiling .nasm source files - for File in self.FileCache.keys(): - if not str(File).endswith('.nasm'): - continue - IncludePathList = [] + IncludePathList = [] + asmsource = [item for item in MyAgo.SourceFileList if item.File.upper().endswith((".NASM",".ASM",".NASMB","S"))] + if asmsource: for P in MyAgo.IncludePathList: IncludePath = self._INC_FLAG_['NASM'] + self.PlaceMacro(P, self.Macros) if IncludePath.endswith(os.sep): @@ -606,7 +607,6 @@ def _TemplateDict(self): IncludePath = os.path.join(IncludePath, '') IncludePathList.append(IncludePath) FileMacroList.append(self._FILE_MACRO_TEMPLATE.Replace({"macro_name": "NASM_INC", "source_file": IncludePathList})) - break # Generate macros used to represent files containing list of input files for ListFileMacro in self.ListFileMacros: @@ -696,6 +696,7 @@ def _TemplateDict(self): "file_macro" : FileMacroList, "file_build_target" : self.BuildTargetList, "backward_compatible_target": BcTargetList, + "INCLUDETAG" : self._INCLUDE_CMD_[self._FileType] + " " + os.path.join("$(MODULE_BUILD_DIR)","dependency") } return MakefileTemplateDict @@ -903,16 +904,10 @@ def ProcessBuildTargetList(self): if Item in SourceFileList: SourceFileList.remove(Item) - FileDependencyDict = self.GetFileDependency( - SourceFileList, - ForceIncludedFile, - self._AutoGenObject.IncludePathList + self._AutoGenObject.BuildOptionIncPathList - ) - + FileDependencyDict = {item:ForceIncludedFile for item in SourceFileList} - if FileDependencyDict: - for Dependency in FileDependencyDict.values(): - self.DependencyHeaderFileSet.update(set(Dependency)) + for Dependency in FileDependencyDict.values(): + self.DependencyHeaderFileSet.update(set(Dependency)) # Get a set of unique package includes from MetaFile parentMetaFileIncludes = set() @@ -972,42 +967,16 @@ def ProcessBuildTargetList(self): ExtraData = "Local Header: " + aFile + " not found in " + self._AutoGenObject.MetaFile.Path ) - DepSet = None for File,Dependency in FileDependencyDict.items(): if not Dependency: - FileDependencyDict[File] = ['$(FORCE_REBUILD)'] continue self._AutoGenObject.AutoGenDepSet |= set(Dependency) - # skip non-C files - if File.Ext not in [".c", ".C"] or File.Name == "AutoGen.c": - continue - elif DepSet is None: - DepSet = set(Dependency) - else: - DepSet &= set(Dependency) - # in case nothing in SourceFileList - if DepSet is None: - DepSet = set() - # - # Extract common files list in the dependency files - # - for File in DepSet: - self.CommonFileDependency.append(self.PlaceMacro(File.Path, self.Macros)) - CmdSumDict = {} CmdTargetDict = {} CmdCppDict = {} DependencyDict = FileDependencyDict.copy() - for File in FileDependencyDict: - # skip non-C files - if File.Ext not in [".c", ".C"] or File.Name == "AutoGen.c": - continue - NewDepSet = set(FileDependencyDict[File]) - NewDepSet -= DepSet - FileDependencyDict[File] = ["$(COMMON_DEPS)"] + list(NewDepSet) - DependencyDict[File] = list(NewDepSet) # Convert target description object to target string in makefile if self._AutoGenObject.BuildRuleFamily == TAB_COMPILER_MSFT and TAB_C_CODE_FILE in self._AutoGenObject.Targets: @@ -1080,17 +1049,13 @@ def ParserCCodeFile(self, T, Type, CmdSumDict, CmdTargetDict, CmdCppDict, Depend else: CmdCppDict[item.Target.SubDir] = ['$(MAKE_FILE)', Path] if CppPath.Path in DependencyDict: - if '$(FORCE_REBUILD)' in DependencyDict[CppPath.Path]: - if '$(FORCE_REBUILD)' not in (self.CommonFileDependency + CmdCppDict[item.Target.SubDir]): - CmdCppDict[item.Target.SubDir].append('$(FORCE_REBUILD)') - else: - for Temp in DependencyDict[CppPath.Path]: - try: - Path = self.PlaceMacro(Temp.Path, self.Macros) - except: - continue - if Path not in (self.CommonFileDependency + CmdCppDict[item.Target.SubDir]): - CmdCppDict[item.Target.SubDir].append(Path) + for Temp in DependencyDict[CppPath.Path]: + try: + Path = self.PlaceMacro(Temp.Path, self.Macros) + except: + continue + if Path not in (self.CommonFileDependency + CmdCppDict[item.Target.SubDir]): + CmdCppDict[item.Target.SubDir].append(Path) if T.Commands: CommandList = T.Commands[:] for Item in CommandList[:]: @@ -1109,7 +1074,7 @@ def ParserCCodeFile(self, T, Type, CmdSumDict, CmdTargetDict, CmdCppDict, Depend CommandList.pop(Index) if SingleCommandList[-1].endswith("%s%s.c" % (TAB_SLASH, CmdSumDict[CmdSign[3:].rsplit(TAB_SLASH, 1)[0]])): Cpplist = CmdCppDict[T.Target.SubDir] - Cpplist.insert(0, '$(OBJLIST_%d): $(COMMON_DEPS)' % list(self.ObjTargetDict.keys()).index(T.Target.SubDir)) + Cpplist.insert(0, '$(OBJLIST_%d): ' % list(self.ObjTargetDict.keys()).index(T.Target.SubDir)) T.Commands[Index] = '%s\n\t%s' % (' \\\n\t'.join(Cpplist), CmdTargetDict[CmdSign]) else: T.Commands.pop(Index) diff --git a/BaseTools/Source/Python/AutoGen/IncludesAutoGen.py b/BaseTools/Source/Python/AutoGen/IncludesAutoGen.py new file mode 100644 index 00000000000..bb6e883d84c --- /dev/null +++ b/BaseTools/Source/Python/AutoGen/IncludesAutoGen.py @@ -0,0 +1,284 @@ +## @file +# Build cache intermediate result and state +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +from Common.caching import cached_property +import Common.EdkLogger as EdkLogger +import Common.LongFilePathOs as os +from Common.BuildToolError import * +from Common.Misc import SaveFileOnChange, PathClass +from Common.Misc import TemplateString +import sys +gIsFileMap = {} +if sys.platform == "win32": + _INCLUDE_DEPS_TEMPLATE = TemplateString(''' +${BEGIN} +!IF EXIST(${deps_file}) +!INCLUDE ${deps_file} +!ENDIF +${END} + ''') +else: + _INCLUDE_DEPS_TEMPLATE = TemplateString(''' +${BEGIN} +-include ${deps_file} +${END} + ''') + +DEP_FILE_TAIL = "# Updated \n" + +class IncludesAutoGen(): + """ This class is to manage the dependent files witch are used in Makefile to support incremental build. + 1. C files: + 1. MSVS. + cl.exe has a build option /showIncludes to display include files on stdout. Build tool captures + that messages and generate dependency files, .deps files. + 2. CLANG and GCC + -MMD -MF build option are used to generate dependency files by compiler. Build tool updates the + .deps files. + 2. ASL files: + 1. Trim find out all the included files with asl specific include format and generate .trim.deps file. + 2. ASL PP use c preprocessor to find out all included files with #include format and generate a .deps file + 3. build tool updates the .deps file + 3. ASM files (.asm, .s or .nasm): + 1. Trim find out all the included files with asl specific include format and generate .trim.deps file. + 2. ASM PP use c preprocessor to find out all included files with #include format and generate a deps file + 3. build tool updates the .deps file + """ + def __init__(self, makefile_folder, ModuleAuto): + self.d_folder = makefile_folder + self.makefile_folder = makefile_folder + self.module_autogen = ModuleAuto + self.ToolChainFamily = ModuleAuto.ToolChainFamily + self.workspace = ModuleAuto.WorkspaceDir + + def CreateModuleDeps(self): + SaveFileOnChange(os.path.join(self.makefile_folder,"deps.txt"),"\n".join(self.DepsCollection),False) + + def CreateDepsInclude(self): + deps_file = {'deps_file':self.deps_files} + try: + deps_include_str = _INCLUDE_DEPS_TEMPLATE.Replace(deps_file) + except Exception as e: + print(e) + SaveFileOnChange(os.path.join(self.makefile_folder,"dependency"),deps_include_str,False) + + @cached_property + def deps_files(self): + """ Get all .deps file under module build folder. """ + deps_files = [] + for root, _, files in os.walk(self.d_folder, topdown=False): + for name in files: + if not name.endswith(".deps"): + continue + abspath = os.path.join(root, name) + deps_files.append(abspath) + return deps_files + + @cached_property + def DepsCollection(self): + """ Collect all the dependency files list from all .deps files under a module's build folder """ + includes = set() + targetname = [item[0].Name for item in self.TargetFileList.values()] + for abspath in self.deps_files: + try: + with open(abspath,"r") as fd: + lines = fd.readlines() + + firstlineitems = lines[0].split(": ") + dependency_file = firstlineitems[1].strip(" \\\n") + dependency_file = dependency_file.strip('''"''') + if dependency_file: + if os.path.normpath(dependency_file +".deps") == abspath: + continue + filename = os.path.basename(dependency_file).strip() + if filename not in self.SourceFileList and filename not in targetname: + includes.add(dependency_file.strip()) + + for item in lines[1:]: + if item == DEP_FILE_TAIL: + continue + dependency_file = item.strip(" \\\n") + dependency_file = dependency_file.strip('''"''') + if os.path.normpath(dependency_file +".deps") == abspath: + continue + filename = os.path.basename(dependency_file).strip() + if filename in self.SourceFileList: + continue + if filename in targetname: + continue + includes.add(dependency_file.strip()) + except Exception as e: + EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False) + continue + rt = sorted(list(set([item.strip(' " \\\n') for item in includes]))) + return rt + + @cached_property + def SourceFileList(self): + """ Get a map of module's source files name to module's source files path """ + source = {os.path.basename(item.File):item.Path for item in self.module_autogen.SourceFileList} + middle_file = {} + for afile in source: + if afile.upper().endswith(".VFR"): + middle_file.update({afile.split(".")[0]+".c":os.path.join(self.module_autogen.DebugDir,afile.split(".")[0]+".c")}) + if afile.upper().endswith((".S","ASM")): + middle_file.update({afile.split(".")[0]+".i":os.path.join(self.module_autogen.OutputDir,afile.split(".")[0]+".i")}) + if afile.upper().endswith(".ASL"): + middle_file.update({afile.split(".")[0]+".i":os.path.join(self.module_autogen.OutputDir,afile.split(".")[0]+".i")}) + source.update({"AutoGen.c":os.path.join(self.module_autogen.OutputDir,"AutoGen.c")}) + source.update(middle_file) + return source + + @cached_property + def HasNamesakeSourceFile(self): + source_base_name = set([os.path.basename(item.File) for item in self.module_autogen.SourceFileList]) + rt = len(source_base_name) != len(self.module_autogen.SourceFileList) + return rt + @cached_property + def CcPPCommandPathSet(self): + rt = set() + rt.add(self.module_autogen.BuildOption.get('CC',{}).get('PATH')) + rt.add(self.module_autogen.BuildOption.get('ASLCC',{}).get('PATH')) + rt.add(self.module_autogen.BuildOption.get('ASLPP',{}).get('PATH')) + rt.add(self.module_autogen.BuildOption.get('VFRPP',{}).get('PATH')) + rt.add(self.module_autogen.BuildOption.get('PP',{}).get('PATH')) + rt.add(self.module_autogen.BuildOption.get('APP',{}).get('PATH')) + rt.discard(None) + return rt + @cached_property + def TargetFileList(self): + """ Get a map of module's target name to a tuple of module's targets path and whose input file path """ + targets = {} + targets["AutoGen.obj"] = (PathClass(os.path.join(self.module_autogen.OutputDir,"AutoGen.obj")),PathClass(os.path.join(self.module_autogen.DebugDir,"AutoGen.c"))) + for item in self.module_autogen.Targets.values(): + for block in item: + targets[block.Target.Path] = (block.Target,block.Inputs[0]) + return targets + + def GetRealTarget(self,source_file_abs): + """ Get the final target file based on source file abspath """ + source_target_map = {item[1].Path:item[0].Path for item in self.TargetFileList.values()} + source_name_map = {item[1].File:item[0].Path for item in self.TargetFileList.values()} + target_abs = source_target_map.get(source_file_abs) + if target_abs is None: + if source_file_abs.strip().endswith(".i"): + sourcefilename = os.path.basename(source_file_abs.strip()) + for sourcefile in source_name_map: + if sourcefilename.split(".")[0] == sourcefile.split(".")[0]: + target_abs = source_name_map[sourcefile] + break + else: + target_abs = source_file_abs + else: + target_abs = source_file_abs + return target_abs + + def CreateDepsFileForMsvc(self, DepList): + """ Generate dependency files, .deps file from /showIncludes output message """ + if not DepList: + return + ModuleDepDict = {} + current_source = "" + SourceFileAbsPathMap = self.SourceFileList + for line in DepList: + line = line.strip() + if self.HasNamesakeSourceFile: + for cc_cmd in self.CcPPCommandPathSet: + if cc_cmd in line: + if '''"'''+cc_cmd+'''"''' in line: + cc_options = line[len(cc_cmd)+2:].split() + else: + cc_options = line[len(cc_cmd):].split() + SourceFileAbsPathMap = {os.path.basename(item):item for item in cc_options if not item.startswith("/") and os.path.exists(item)} + if line in SourceFileAbsPathMap: + current_source = line + if current_source not in ModuleDepDict: + ModuleDepDict[SourceFileAbsPathMap[current_source]] = [] + elif "Note: including file:" == line.lstrip()[:21]: + if not current_source: + EdkLogger.error("build",BUILD_ERROR, "Parse /showIncludes output failed. line: %s. \n" % line, RaiseError=False) + else: + ModuleDepDict[SourceFileAbsPathMap[current_source]].append(line.lstrip()[22:].strip()) + + for source_abs in ModuleDepDict: + if ModuleDepDict[source_abs]: + target_abs = self.GetRealTarget(source_abs) + dep_file_name = os.path.basename(source_abs) + ".deps" + SaveFileOnChange(os.path.join(os.path.dirname(target_abs),dep_file_name)," \\\n".join([target_abs+":"] + ['''"''' + item +'''"''' for item in ModuleDepDict[source_abs]]),False) + + def UpdateDepsFileforNonMsvc(self): + """ Update .deps files. + 1. Update target path to absolute path. + 2. Update middle target to final target. + """ + + for abspath in self.deps_files: + if abspath.endswith(".trim.deps"): + continue + try: + newcontent = [] + with open(abspath,"r") as fd: + lines = fd.readlines() + if lines[-1] == DEP_FILE_TAIL: + continue + firstlineitems = lines[0].strip().split(" ") + + if len(firstlineitems) > 2: + sourceitem = firstlineitems[1] + else: + sourceitem = lines[1].strip().split(" ")[0] + + source_abs = self.SourceFileList.get(sourceitem,sourceitem) + firstlineitems[0] = self.GetRealTarget(source_abs) + p_target = firstlineitems + if not p_target[0].strip().endswith(":"): + p_target[0] += ": " + + if len(p_target) == 2: + p_target[0] += lines[1] + newcontent.append(p_target[0]) + newcontent.extend(lines[2:]) + else: + line1 = " ".join(p_target).strip() + line1 += "\n" + newcontent.append(line1) + newcontent.extend(lines[1:]) + + newcontent.append("\n") + newcontent.append(DEP_FILE_TAIL) + with open(abspath,"w") as fw: + fw.write("".join(newcontent)) + except Exception as e: + EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False) + continue + + def UpdateDepsFileforTrim(self): + """ Update .deps file which generated by trim. """ + + for abspath in self.deps_files: + if not abspath.endswith(".trim.deps"): + continue + try: + newcontent = [] + with open(abspath,"r") as fd: + lines = fd.readlines() + if lines[-1] == DEP_FILE_TAIL: + continue + + source_abs = lines[0].strip().split(" ")[0] + targetitem = self.GetRealTarget(source_abs.strip(" :")) + + targetitem += ": " + targetitem += lines[1] + newcontent.append(targetitem) + newcontent.extend(lines[2:]) + newcontent.append("\n") + newcontent.append(DEP_FILE_TAIL) + with open(abspath,"w") as fw: + fw.write("".join(newcontent)) + except Exception as e: + EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False) + continue diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index e6d6c43810e..1111d5de25a 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -1129,8 +1129,31 @@ def IncludePathList(self): for Inc in IncludesList: if Inc not in RetVal: RetVal.append(str(Inc)) + RetVal.extend(self.IncPathFromBuildOptions) return RetVal + @cached_property + def IncPathFromBuildOptions(self): + IncPathList = [] + for tool in self.BuildOption: + if 'FLAGS' in self.BuildOption[tool]: + flags = self.BuildOption[tool]['FLAGS'] + whitespace = False + for flag in flags.split(" "): + flag = flag.strip() + if flag.startswith(("/I","-I")): + if len(flag)>2: + if os.path.exists(flag[2:]): + IncPathList.append(flag[2:]) + else: + whitespace = True + continue + if whitespace and flag: + if os.path.exists(flag): + IncPathList.append(flag) + whitespace = False + return IncPathList + @cached_property def IncludePathLength(self): return sum(len(inc)+1 for inc in self.IncludePathList) diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 4b31356a425..6fcfc7ec7ab 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -57,7 +57,7 @@ from AutoGen.DataPipe import MemoryDataPipe from AutoGen.ModuleAutoGenHelper import WorkSpaceInfo, PlatformInfo from GenFds.FdfParser import FdfParser - +from AutoGen.IncludesAutoGen import IncludesAutoGen ## standard targets of build command gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run'] @@ -175,18 +175,31 @@ def NormFile(FilePath, Workspace): # @param To The stream message put on # @param ExitFlag The flag used to indicate stopping reading # -def ReadMessage(From, To, ExitFlag): +def ReadMessage(From, To, ExitFlag,MemTo=None): while True: # read one line a time Line = From.readline() # empty string means "end" if Line is not None and Line != b"": - To(Line.rstrip().decode(encoding='utf-8', errors='ignore')) + LineStr = Line.rstrip().decode(encoding='utf-8', errors='ignore') + if MemTo is not None: + if "Note: including file:" == LineStr.lstrip()[:21]: + MemTo.append(LineStr) + else: + To(LineStr) + MemTo.append(LineStr) + else: + To(LineStr) else: break if ExitFlag.isSet(): break +class MakeSubProc(Popen): + def __init__(self,*args, **argv): + super(MakeSubProc,self).__init__(*args, **argv) + self.ProcOut = [] + ## Launch an external program # # This method will call subprocess.Popen to execute an external program with @@ -197,7 +210,7 @@ def ReadMessage(From, To, ExitFlag): # @param Command A list or string containing the call of the program # @param WorkingDir The directory in which the program will be running # -def LaunchCommand(Command, WorkingDir): +def LaunchCommand(Command, WorkingDir,ModuleAuto = None): BeginTime = time.time() # if working directory doesn't exist, Popen() will raise an exception if not os.path.isdir(WorkingDir): @@ -216,19 +229,19 @@ def LaunchCommand(Command, WorkingDir): EndOfProcedure = None try: # launch the command - Proc = Popen(Command, stdout=PIPE, stderr=PIPE, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True) + Proc = MakeSubProc(Command, stdout=PIPE, stderr=PIPE, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True) # launch two threads to read the STDOUT and STDERR EndOfProcedure = Event() EndOfProcedure.clear() if Proc.stdout: - StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure)) + StdOutThread = Thread(target=ReadMessage, args=(Proc.stdout, EdkLogger.info, EndOfProcedure,Proc.ProcOut)) StdOutThread.setName("STDOUT-Redirector") StdOutThread.setDaemon(False) StdOutThread.start() if Proc.stderr: - StdErrThread = Thread(target=ReadMessage, args=(Proc.stderr, EdkLogger.quiet, EndOfProcedure)) + StdErrThread = Thread(target=ReadMessage, args=(Proc.stderr, EdkLogger.quiet, EndOfProcedure,Proc.ProcOut)) StdErrThread.setName("STDERR-Redirector") StdErrThread.setDaemon(False) StdErrThread.start() @@ -263,6 +276,15 @@ def LaunchCommand(Command, WorkingDir): EdkLogger.info(RespContent) EdkLogger.error("build", COMMAND_FAILURE, ExtraData="%s [%s]" % (Command, WorkingDir)) + if ModuleAuto: + iau = IncludesAutoGen(WorkingDir,ModuleAuto) + if ModuleAuto.ToolChainFamily == TAB_COMPILER_MSFT: + iau.CreateDepsFileForMsvc(Proc.ProcOut) + else: + iau.UpdateDepsFileforNonMsvc() + iau.UpdateDepsFileforTrim() + iau.CreateModuleDeps() + iau.CreateDepsInclude() return "%dms" % (int(round((time.time() - BeginTime) * 1000))) ## The smallest unit that can be built in multi-thread build mode @@ -608,7 +630,7 @@ def AddDependency(self, Dependency): # def _CommandThread(self, Command, WorkingDir): try: - self.BuildItem.BuildObject.BuildTime = LaunchCommand(Command, WorkingDir) + self.BuildItem.BuildObject.BuildTime = LaunchCommand(Command, WorkingDir,self.BuildItem.BuildObject) self.CompleteFlag = True # Run hash operation post dependency, to account for libs @@ -1276,19 +1298,32 @@ def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMak # build library if Target == 'libraries': - for Lib in AutoGenObject.LibraryBuildDirectoryList: + DirList = [] + for Lib in AutoGenObject.LibraryAutoGenList: + if not Lib.IsBinaryModule: + DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib)) + for Lib, LibAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild'] - LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) + LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen) return True # build module if Target == 'modules': - for Lib in AutoGenObject.LibraryBuildDirectoryList: + DirList = [] + for Lib in AutoGenObject.LibraryAutoGenList: + if not Lib.IsBinaryModule: + DirList.append((os.path.join(AutoGenObject.BuildDir, Lib.BuildDir),Lib)) + for Lib, LibAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Lib, makefile)), 'pbuild'] - LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) - for Mod in AutoGenObject.ModuleBuildDirectoryList: + LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,LibAutoGen) + + DirList = [] + for ModuleAutoGen in AutoGenObject.ModuleAutoGenList: + if not ModuleAutoGen.IsBinaryModule: + DirList.append((os.path.join(AutoGenObject.BuildDir, ModuleAutoGen.BuildDir),ModuleAutoGen)) + for Mod,ModAutoGen in DirList: NewBuildCommand = BuildCommand + ['-f', os.path.normpath(os.path.join(Mod, makefile)), 'pbuild'] - LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir) + LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,ModAutoGen) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: self.UpdateBuildCache() From 91f6c533f8e9c49ffd098e9167724596ecfd7410 Mon Sep 17 00:00:00 2001 From: Steven Shi Date: Mon, 21 Oct 2019 14:24:57 +0800 Subject: [PATCH 170/384] BaseTools: store more complete output files in binary cache Binary cache use the OutputFile method to return the module built output files needed to store in cache, but current OutputFile implementation doesn't return complete output files. Enhance the OutputFile method to return more complete output files. Signed-off-by: Steven Shi Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- .../Source/Python/AutoGen/ModuleAutoGen.py | 20 ++++--------------- 1 file changed, 4 insertions(+), 16 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index 1111d5de25a..fce00c3ee75 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -1308,28 +1308,16 @@ def _GenOffsetBin(self): def OutputFile(self): retVal = set() - OutputDir = self.OutputDir.replace('\\', '/').strip('/') - DebugDir = self.DebugDir.replace('\\', '/').strip('/') - for Item in self.CodaTargetList: - File = Item.Target.Path.replace('\\', '/').strip('/').replace(DebugDir, '').replace(OutputDir, '').strip('/') - NewFile = path.join(self.OutputDir, File) - retVal.add(NewFile) - - Bin = self._GenOffsetBin() - if Bin: - NewFile = path.join(self.OutputDir, Bin) - retVal.add(NewFile) - - for Root, Dirs, Files in os.walk(self.OutputDir): + for Root, Dirs, Files in os.walk(self.BuildDir): for File in Files: # lib file is already added through above CodaTargetList, skip it here - if not (File.lower().endswith('.obj') or File.lower().endswith('.lib')): - NewFile = path.join(self.OutputDir, File) + if not (File.lower().endswith('.obj') or File.lower().endswith('.debug')): + NewFile = path.join(Root, File) retVal.add(NewFile) for Root, Dirs, Files in os.walk(self.FfsOutputDir): for File in Files: - NewFile = path.join(self.FfsOutputDir, File) + NewFile = path.join(Root, File) retVal.add(NewFile) return retVal From 3bfbc915074a45f4d9c61aa2b698a62f1a24124e Mon Sep 17 00:00:00 2001 From: Steven Shi Date: Mon, 21 Oct 2019 14:51:49 +0800 Subject: [PATCH 171/384] BaseTools: enhance the CacheCopyFile method arg names Enhance the CacheCopyFile method arg names to be more clear and readable Signed-off-by: Steven Shi Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- BaseTools/Source/Python/AutoGen/ModuleAutoGen.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index fce00c3ee75..eb52f40a9d0 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -1650,9 +1650,9 @@ def CreateAsBuiltInf(self): self.IsAsBuiltInfCreated = True - def CacheCopyFile(self, OriginDir, CopyDir, File): - sub_dir = os.path.relpath(File, CopyDir) - destination_file = os.path.join(OriginDir, sub_dir) + def CacheCopyFile(self, DestDir, SourceDir, File): + sub_dir = os.path.relpath(File, SourceDir) + destination_file = os.path.join(DestDir, sub_dir) destination_dir = os.path.dirname(destination_file) CreateDirectory(destination_dir) try: From fc8b8deac2d77524ff8cfe44acf95b5e1f59804e Mon Sep 17 00:00:00 2001 From: Steven Shi Date: Tue, 19 Nov 2019 16:17:00 +0800 Subject: [PATCH 172/384] BaseTools: Leverage compiler output to optimize binary cache Redesign the binary cache and bases on the compiler to output the dependency header files info for every module. The binary cache will directly consume the dependency header files info and doesn't parse the C source code by iteself. Also redesign the dependency files list format for module and try to share the common lib hash result as more as possible in local process. Remove the unnecessary share data access across multiprocessing. Signed-off-by: Steven Shi Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- .../Source/Python/AutoGen/AutoGenWorker.py | 77 +- BaseTools/Source/Python/AutoGen/DataPipe.py | 2 + .../Source/Python/AutoGen/ModuleAutoGen.py | 1082 +++++++---------- .../Source/Python/AutoGen/WorkspaceAutoGen.py | 64 +- BaseTools/Source/Python/Common/GlobalData.py | 35 +- BaseTools/Source/Python/build/build.py | 276 ++--- 6 files changed, 714 insertions(+), 822 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/AutoGenWorker.py b/BaseTools/Source/Python/AutoGen/AutoGenWorker.py index 94ea61a4870..40b448f5b2d 100755 --- a/BaseTools/Source/Python/AutoGen/AutoGenWorker.py +++ b/BaseTools/Source/Python/AutoGen/AutoGenWorker.py @@ -128,12 +128,27 @@ def clearQueue(self): clearQ(taskq) clearQ(self.feedback_q) clearQ(logq) + # Copy the cache queue itmes to parent thread before clear + cacheq = self.autogen_workers[0].cache_q + try: + cache_num = 0 + while True: + item = cacheq.get() + if item == "CacheDone": + cache_num += 1 + else: + GlobalData.gModuleAllCacheStatus.add(item) + if cache_num == len(self.autogen_workers): + break + except: + print ("cache_q error") + def TerminateWorkers(self): self.error_event.set() def kill(self): self.feedback_q.put(None) class AutoGenWorkerInProcess(mp.Process): - def __init__(self,module_queue,data_pipe_file_path,feedback_q,file_lock,cache_lock,share_data,log_q,error_event): + def __init__(self,module_queue,data_pipe_file_path,feedback_q,file_lock,cache_q,log_q,error_event): mp.Process.__init__(self) self.module_queue = module_queue self.data_pipe_file_path =data_pipe_file_path @@ -141,8 +156,7 @@ def __init__(self,module_queue,data_pipe_file_path,feedback_q,file_lock,cache_lo self.feedback_q = feedback_q self.PlatformMetaFileSet = {} self.file_lock = file_lock - self.cache_lock = cache_lock - self.share_data = share_data + self.cache_q = cache_q self.log_q = log_q self.error_event = error_event def GetPlatformMetaFile(self,filepath,root): @@ -184,12 +198,19 @@ def run(self): GlobalData.gDisableIncludePathCheck = False GlobalData.gFdfParser = self.data_pipe.Get("FdfParser") GlobalData.gDatabasePath = self.data_pipe.Get("DatabasePath") + + GlobalData.gUseHashCache = self.data_pipe.Get("UseHashCache") GlobalData.gBinCacheSource = self.data_pipe.Get("BinCacheSource") GlobalData.gBinCacheDest = self.data_pipe.Get("BinCacheDest") - GlobalData.gCacheIR = self.share_data + GlobalData.gPlatformHashFile = self.data_pipe.Get("PlatformHashFile") + GlobalData.gModulePreMakeCacheStatus = dict() + GlobalData.gModuleMakeCacheStatus = dict() + GlobalData.gHashChainStatus = dict() + GlobalData.gCMakeHashFile = dict() + GlobalData.gModuleHashFile = dict() + GlobalData.gFileHashDict = dict() GlobalData.gEnableGenfdsMultiThread = self.data_pipe.Get("EnableGenfdsMultiThread") GlobalData.file_lock = self.file_lock - GlobalData.cache_lock = self.cache_lock CommandTarget = self.data_pipe.Get("CommandTarget") pcd_from_build_option = [] for pcd_tuple in self.data_pipe.Get("BuildOptPcd"): @@ -205,10 +226,6 @@ def run(self): GlobalData.FfsCmd = FfsCmd PlatformMetaFile = self.GetPlatformMetaFile(self.data_pipe.Get("P_Info").get("ActivePlatform"), self.data_pipe.Get("P_Info").get("WorkspaceDir")) - libConstPcd = self.data_pipe.Get("LibConstPcd") - Refes = self.data_pipe.Get("REFS") - GlobalData.libConstPcd = libConstPcd - GlobalData.Refes = Refes while True: if self.module_queue.empty(): break @@ -230,27 +247,41 @@ def run(self): toolchain = self.data_pipe.Get("P_Info").get("ToolChain") Ma = ModuleAutoGen(self.Wa,module_metafile,target,toolchain,arch,PlatformMetaFile,self.data_pipe) Ma.IsLibrary = IsLib - if IsLib: - if (Ma.MetaFile.File,Ma.MetaFile.Root,Ma.Arch,Ma.MetaFile.Path) in libConstPcd: - Ma.ConstPcd = libConstPcd[(Ma.MetaFile.File,Ma.MetaFile.Root,Ma.Arch,Ma.MetaFile.Path)] - if (Ma.MetaFile.File,Ma.MetaFile.Root,Ma.Arch,Ma.MetaFile.Path) in Refes: - Ma.ReferenceModules = Refes[(Ma.MetaFile.File,Ma.MetaFile.Root,Ma.Arch,Ma.MetaFile.Path)] - if GlobalData.gBinCacheSource and CommandTarget in [None, "", "all"]: - Ma.GenModuleFilesHash(GlobalData.gCacheIR) - Ma.GenPreMakefileHash(GlobalData.gCacheIR) - if Ma.CanSkipbyPreMakefileCache(GlobalData.gCacheIR): + # SourceFileList calling sequence impact the makefile string sequence. + # Create cached SourceFileList here to unify its calling sequence for both + # CanSkipbyPreMakeCache and CreateCodeFile/CreateMakeFile. + RetVal = Ma.SourceFileList + if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and CommandTarget in [None, "", "all"]: + try: + CacheResult = Ma.CanSkipbyPreMakeCache() + except: + CacheResult = False + traceback.print_exc(file=sys.stdout) + self.feedback_q.put(taskname) + + if CacheResult: + self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "PreMakeCache", True)) continue + else: + self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "PreMakeCache", False)) Ma.CreateCodeFile(False) Ma.CreateMakeFile(False,GenFfsList=FfsCmd.get((Ma.MetaFile.Path, Ma.Arch),[])) if GlobalData.gBinCacheSource and CommandTarget in [None, "", "all"]: - Ma.GenMakeHeaderFilesHash(GlobalData.gCacheIR) - Ma.GenMakeHash(GlobalData.gCacheIR) - if Ma.CanSkipbyMakeCache(GlobalData.gCacheIR): + try: + CacheResult = Ma.CanSkipbyMakeCache() + except: + CacheResult = False + traceback.print_exc(file=sys.stdout) + self.feedback_q.put(taskname) + + if CacheResult: + self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "MakeCache", True)) continue else: - Ma.PrintFirstMakeCacheMissFile(GlobalData.gCacheIR) + self.cache_q.put((Ma.MetaFile.Path, Ma.Arch, "MakeCache", False)) + except Empty: pass except: @@ -258,6 +289,8 @@ def run(self): self.feedback_q.put(taskname) finally: self.feedback_q.put("Done") + self.cache_q.put("CacheDone") + def printStatus(self): print("Processs ID: %d Run %d modules in AutoGen " % (os.getpid(),len(AutoGen.Cache()))) print("Processs ID: %d Run %d modules in AutoGenInfo " % (os.getpid(),len(AutoGenInfo.GetCache()))) diff --git a/BaseTools/Source/Python/AutoGen/DataPipe.py b/BaseTools/Source/Python/AutoGen/DataPipe.py index 078bafecb45..50403fbfb56 100755 --- a/BaseTools/Source/Python/AutoGen/DataPipe.py +++ b/BaseTools/Source/Python/AutoGen/DataPipe.py @@ -159,6 +159,8 @@ def FillData(self,PlatformInfo): self.DataContainer = {"LogLevel": EdkLogger.GetLevel()} + self.DataContainer = {"UseHashCache":GlobalData.gUseHashCache} + self.DataContainer = {"BinCacheSource":GlobalData.gBinCacheSource} self.DataContainer = {"BinCacheDest":GlobalData.gBinCacheDest} diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index eb52f40a9d0..74662d1b52b 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -6,7 +6,7 @@ # from __future__ import absolute_import from AutoGen.AutoGen import AutoGen -from Common.LongFilePathSupport import CopyLongFilePath +from Common.LongFilePathSupport import LongFilePath, CopyLongFilePath from Common.BuildToolError import * from Common.DataType import * from Common.Misc import * @@ -26,7 +26,6 @@ from .GenPcdDb import CreatePcdDatabaseCode from Common.caching import cached_class_function from AutoGen.ModuleAutoGenHelper import PlatformInfo,WorkSpaceInfo -from AutoGen.CacheIR import ModuleBuildCacheIR import json import tempfile @@ -1651,6 +1650,9 @@ def CreateAsBuiltInf(self): self.IsAsBuiltInfCreated = True def CacheCopyFile(self, DestDir, SourceDir, File): + if os.path.isdir(File): + return + sub_dir = os.path.relpath(File, SourceDir) destination_file = os.path.join(DestDir, sub_dir) destination_dir = os.path.dirname(destination_file) @@ -1662,105 +1664,73 @@ def CacheCopyFile(self, DestDir, SourceDir, File): return def CopyModuleToCache(self): - self.GenPreMakefileHash(GlobalData.gCacheIR) - if not (self.MetaFile.Path, self.Arch) in GlobalData.gCacheIR or \ - not GlobalData.gCacheIR[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest: - EdkLogger.quiet("[cache warning]: Cannot generate PreMakefileHash for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return False + # Find the MakeHashStr and PreMakeHashStr from latest MakeHashFileList + # and PreMakeHashFileList files + MakeHashStr = None + PreMakeHashStr = None + MakeTimeStamp = 0 + PreMakeTimeStamp = 0 + Files = [f for f in os.listdir(LongFilePath(self.BuildDir)) if path.isfile(LongFilePath(path.join(self.BuildDir, f)))] + for File in Files: + if ".MakeHashFileList." in File: + #find lastest file through time stamp + FileTimeStamp = os.stat(LongFilePath(path.join(self.BuildDir, File)))[8] + if FileTimeStamp > MakeTimeStamp: + MakeTimeStamp = FileTimeStamp + MakeHashStr = File.split('.')[-1] + if len(MakeHashStr) != 32: + EdkLogger.quiet("[cache error]: wrong MakeHashFileList file:%s" % (File)) + if ".PreMakeHashFileList." in File: + FileTimeStamp = os.stat(LongFilePath(path.join(self.BuildDir, File)))[8] + if FileTimeStamp > PreMakeTimeStamp: + PreMakeTimeStamp = FileTimeStamp + PreMakeHashStr = File.split('.')[-1] + if len(PreMakeHashStr) != 32: + EdkLogger.quiet("[cache error]: wrong PreMakeHashFileList file:%s" % (File)) - self.GenMakeHash(GlobalData.gCacheIR) - if not (self.MetaFile.Path, self.Arch) in GlobalData.gCacheIR or \ - not GlobalData.gCacheIR[(self.MetaFile.Path, self.Arch)].MakeHashChain or \ - not GlobalData.gCacheIR[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest: - EdkLogger.quiet("[cache warning]: Cannot generate MakeHashChain for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return False + if not MakeHashStr: + EdkLogger.quiet("[cache error]: No MakeHashFileList file for module:%s[%s]" % (self.MetaFile.Path, self.Arch)) + return + if not PreMakeHashStr: + EdkLogger.quiet("[cache error]: No PreMakeHashFileList file for module:%s[%s]" % (self.MetaFile.Path, self.Arch)) + return - MakeHashStr = str(GlobalData.gCacheIR[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest) - FileDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName, MakeHashStr) - FfsDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name, MakeHashStr) + # Create Cache destination dirs + FileDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) + FfsDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name) + CacheFileDir = path.join(FileDir, MakeHashStr) + CacheFfsDir = path.join(FfsDir, MakeHashStr) + CreateDirectory (CacheFileDir) + CreateDirectory (CacheFfsDir) - CreateDirectory (FileDir) - self.SaveHashChainFileToCache(GlobalData.gCacheIR) - ModuleFile = path.join(self.OutputDir, self.Name + '.inf') - if os.path.exists(ModuleFile): - CopyFileOnChange(ModuleFile, FileDir) + # Create ModuleHashPair file to support multiple version cache together + ModuleHashPair = path.join(FileDir, self.Name + ".ModuleHashPair") + ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)] + if os.path.exists(ModuleHashPair): + with open(ModuleHashPair, 'r') as f: + ModuleHashPairList = json.load(f) + if not (PreMakeHashStr, MakeHashStr) in set(map(tuple, ModuleHashPairList)): + ModuleHashPairList.insert(0, (PreMakeHashStr, MakeHashStr)) + with open(ModuleHashPair, 'w') as f: + json.dump(ModuleHashPairList, f, indent=2) + + # Copy files to Cache destination dirs if not self.OutputFile: Ma = self.BuildDatabase[self.MetaFile, self.Arch, self.BuildTarget, self.ToolChain] self.OutputFile = Ma.Binaries for File in self.OutputFile: - if os.path.exists(File): - if File.startswith(os.path.abspath(self.FfsOutputDir)+os.sep): - self.CacheCopyFile(FfsDir, self.FfsOutputDir, File) + if File.startswith(os.path.abspath(self.FfsOutputDir)+os.sep): + self.CacheCopyFile(CacheFfsDir, self.FfsOutputDir, File) + else: + if self.Name + ".autogen.hash." in File or \ + self.Name + ".autogen.hashchain." in File or \ + self.Name + ".hash." in File or \ + self.Name + ".hashchain." in File or \ + self.Name + ".PreMakeHashFileList." in File or \ + self.Name + ".MakeHashFileList." in File: + self.CacheCopyFile(FileDir, self.BuildDir, File) else: - self.CacheCopyFile(FileDir, self.OutputDir, File) - - def SaveHashChainFileToCache(self, gDict): - if not GlobalData.gBinCacheDest: - return False - - self.GenPreMakefileHash(gDict) - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest: - EdkLogger.quiet("[cache warning]: Cannot generate PreMakefileHash for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return False - - self.GenMakeHash(gDict) - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].MakeHashChain or \ - not gDict[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest: - EdkLogger.quiet("[cache warning]: Cannot generate MakeHashChain for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return False - - # save the hash chain list as cache file - MakeHashStr = str(GlobalData.gCacheIR[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest) - CacheDestDir = path.join(GlobalData.gBinCacheDest, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) - CacheHashDestDir = path.join(CacheDestDir, MakeHashStr) - ModuleHashPair = path.join(CacheDestDir, self.Name + ".ModuleHashPair") - MakeHashChain = path.join(CacheHashDestDir, self.Name + ".MakeHashChain") - ModuleFilesChain = path.join(CacheHashDestDir, self.Name + ".ModuleFilesChain") - - # save the HashChainDict as json file - CreateDirectory (CacheDestDir) - CreateDirectory (CacheHashDestDir) - try: - ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)] - if os.path.exists(ModuleHashPair): - with open(ModuleHashPair, 'r') as f: - ModuleHashPairList = json.load(f) - PreMakeHash = gDict[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest - MakeHash = gDict[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest - ModuleHashPairList.append((PreMakeHash, MakeHash)) - ModuleHashPairList = list(set(map(tuple, ModuleHashPairList))) - with open(ModuleHashPair, 'w') as f: - json.dump(ModuleHashPairList, f, indent=2) - except: - EdkLogger.quiet("[cache warning]: fail to save ModuleHashPair file in cache: %s" % ModuleHashPair) - return False - - try: - with open(MakeHashChain, 'w') as f: - json.dump(gDict[(self.MetaFile.Path, self.Arch)].MakeHashChain, f, indent=2) - except: - EdkLogger.quiet("[cache warning]: fail to save MakeHashChain file in cache: %s" % MakeHashChain) - return False - - try: - with open(ModuleFilesChain, 'w') as f: - json.dump(gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesChain, f, indent=2) - except: - EdkLogger.quiet("[cache warning]: fail to save ModuleFilesChain file in cache: %s" % ModuleFilesChain) - return False - - # save the autogenfile and makefile for debug usage - CacheDebugDir = path.join(CacheHashDestDir, "CacheDebug") - CreateDirectory (CacheDebugDir) - CopyFileOnChange(gDict[(self.MetaFile.Path, self.Arch)].MakefilePath, CacheDebugDir) - if gDict[(self.MetaFile.Path, self.Arch)].AutoGenFileList: - for File in gDict[(self.MetaFile.Path, self.Arch)].AutoGenFileList: - CopyFileOnChange(str(File), CacheDebugDir) - - return True - + self.CacheCopyFile(CacheFileDir, self.BuildDir, File) ## Create makefile for the module and its dependent libraries # # @param CreateLibraryMakeFile Flag indicating if or not the makefiles of @@ -1768,10 +1738,6 @@ def SaveHashChainFileToCache(self, gDict): # @cached_class_function def CreateMakeFile(self, CreateLibraryMakeFile=True, GenFfsList = []): - gDict = GlobalData.gCacheIR - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CreateMakeFileDone: - return # nest this function inside it's only caller. def CreateTimeStamp(): @@ -1821,20 +1787,8 @@ def CreateTimeStamp(): MakefileType = Makefile._FileType MakefileName = Makefile._FILE_NAME_[MakefileType] MakefilePath = os.path.join(self.MakeFileDir, MakefileName) - - MewIR = ModuleBuildCacheIR(self.MetaFile.Path, self.Arch) - MewIR.MakefilePath = MakefilePath - MewIR.DependencyHeaderFileSet = Makefile.DependencyHeaderFileSet - MewIR.CreateMakeFileDone = True - with GlobalData.cache_lock: - try: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.MakefilePath = MakefilePath - IR.DependencyHeaderFileSet = Makefile.DependencyHeaderFileSet - IR.CreateMakeFileDone = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - except: - gDict[(self.MetaFile.Path, self.Arch)] = MewIR + FilePath = path.join(self.BuildDir, self.Name + ".makefile") + SaveFileOnChange(FilePath, MakefilePath, False) def CopyBinaryFiles(self): for File in self.Module.Binaries: @@ -1847,10 +1801,6 @@ def CopyBinaryFiles(self): # dependent libraries will be created # def CreateCodeFile(self, CreateLibraryCodeFile=True): - gDict = GlobalData.gCacheIR - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CreateCodeFileDone: - return if self.IsCodeFileCreated: return @@ -1909,15 +1859,6 @@ def CreateCodeFile(self, CreateLibraryCodeFile=True): (" ".join(AutoGenList), " ".join(IgoredAutoGenList), self.Name, self.Arch)) self.IsCodeFileCreated = True - MewIR = ModuleBuildCacheIR(self.MetaFile.Path, self.Arch) - MewIR.CreateCodeFileDone = True - with GlobalData.cache_lock: - try: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.CreateCodeFileDone = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - except: - gDict[(self.MetaFile.Path, self.Arch)] = MewIR return AutoGenList @@ -1942,618 +1883,539 @@ def LibraryAutoGenList(self): self._ApplyBuildRule(Lib.Target, TAB_UNKNOWN_FILE) return RetVal - def GenModuleHash(self): - # Initialize a dictionary for each arch type - if self.Arch not in GlobalData.gModuleHash: - GlobalData.gModuleHash[self.Arch] = {} + def GenCMakeHash(self): + # GenCMakeHash can only be called in --binary-destination + # Never called in multiprocessing and always directly save result in main process, + # so no need remote dict to share the gCMakeHashFile result with main process - # Early exit if module or library has been hashed and is in memory - if self.Name in GlobalData.gModuleHash[self.Arch]: - return GlobalData.gModuleHash[self.Arch][self.Name].encode('utf-8') + DependencyFileSet = set() + # Add AutoGen files + if self.AutoGenFileList: + for File in set(self.AutoGenFileList): + DependencyFileSet.add(File) + + # Add Makefile + abspath = path.join(self.BuildDir, self.Name + ".makefile") + try: + with open(LongFilePath(abspath),"r") as fd: + lines = fd.readlines() + except Exception as e: + EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False) + if lines: + DependencyFileSet.update(lines) + # Caculate all above dependency files hash # Initialze hash object + FileList = [] m = hashlib.md5() - - # Add Platform level hash - m.update(GlobalData.gPlatformHash.encode('utf-8')) - - # Add Package level hash - if self.DependentPackageList: - for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName): - if Pkg.PackageName in GlobalData.gPackageHash: - m.update(GlobalData.gPackageHash[Pkg.PackageName].encode('utf-8')) - - # Add Library hash - if self.LibraryAutoGenList: - for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name): - if Lib.Name not in GlobalData.gModuleHash[self.Arch]: - Lib.GenModuleHash() - m.update(GlobalData.gModuleHash[self.Arch][Lib.Name].encode('utf-8')) - - # Add Module self - with open(str(self.MetaFile), 'rb') as f: - Content = f.read() - m.update(Content) - - # Add Module's source files - if self.SourceFileList: - for File in sorted(self.SourceFileList, key=lambda x: str(x)): - f = open(str(File), 'rb') + for File in sorted(DependencyFileSet, key=lambda x: str(x)): + if not path.exists(LongFilePath(str(File))): + EdkLogger.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File, self.MetaFile.Path, self.Arch)) + continue + with open(LongFilePath(str(File)), 'rb') as f: Content = f.read() - f.close() - m.update(Content) - - GlobalData.gModuleHash[self.Arch][self.Name] = m.hexdigest() - - return GlobalData.gModuleHash[self.Arch][self.Name].encode('utf-8') + m.update(Content) + FileList.append((str(File), hashlib.md5(Content).hexdigest())) - def GenModuleFilesHash(self, gDict): - # Early exit if module or library has been hashed and is in memory - if (self.MetaFile.Path, self.Arch) in gDict: - if gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesChain: - return gDict[(self.MetaFile.Path, self.Arch)] + HashChainFile = path.join(self.BuildDir, self.Name + ".autogen.hashchain." + m.hexdigest()) + GlobalData.gCMakeHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile + try: + with open(LongFilePath(HashChainFile), 'w') as f: + json.dump(FileList, f, indent=2) + except: + EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile) + return False - # skip if the module cache already crashed - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return + def GenModuleHash(self): + # GenModuleHash only called after autogen phase + # Never called in multiprocessing and always directly save result in main process, + # so no need remote dict to share the gModuleHashFile result with main process + # + # GenPreMakefileHashList consume no dict. + # GenPreMakefileHashList produce local gModuleHashFile dict. DependencyFileSet = set() # Add Module Meta file - DependencyFileSet.add(self.MetaFile) + DependencyFileSet.add(self.MetaFile.Path) # Add Module's source files if self.SourceFileList: for File in set(self.SourceFileList): - DependencyFileSet.add(File) + DependencyFileSet.add(File.Path) # Add modules's include header files - # Search dependency file list for each source file - SourceFileList = [] - OutPutFileList = [] - for Target in self.IntroTargetList: - SourceFileList.extend(Target.Inputs) - OutPutFileList.extend(Target.Outputs) - if OutPutFileList: - for Item in OutPutFileList: - if Item in SourceFileList: - SourceFileList.remove(Item) - SearchList = [] - for file_path in self.IncludePathList + self.BuildOptionIncPathList: - # skip the folders in platform BuildDir which are not been generated yet - if file_path.startswith(os.path.abspath(self.PlatformInfo.BuildDir)+os.sep): - continue - SearchList.append(file_path) - FileDependencyDict = {} - ForceIncludedFile = [] - for F in SourceFileList: - # skip the files which are not been generated yet, because - # the SourceFileList usually contains intermediate build files, e.g. AutoGen.c - if not os.path.exists(F.Path): - continue - FileDependencyDict[F] = GenMake.GetDependencyList(self, self.FileDependCache, F, ForceIncludedFile, SearchList) + # Directly use the deps.txt file in the module BuildDir + abspath = path.join(self.BuildDir, "deps.txt") + rt = None + try: + with open(LongFilePath(abspath),"r") as fd: + lines = fd.readlines() + if lines: + rt = set([item.lstrip().strip("\n") for item in lines if item.strip("\n").endswith(".h")]) + except Exception as e: + EdkLogger.error("build",FILE_NOT_FOUND, "%s doesn't exist" % abspath, ExtraData=str(e), RaiseError=False) + + if rt: + DependencyFileSet.update(rt) - if FileDependencyDict: - for Dependency in FileDependencyDict.values(): - DependencyFileSet.update(set(Dependency)) # Caculate all above dependency files hash # Initialze hash object FileList = [] m = hashlib.md5() + BuildDirStr = path.abspath(self.BuildDir).lower() for File in sorted(DependencyFileSet, key=lambda x: str(x)): - if not os.path.exists(str(File)): + # Skip the AutoGen files in BuildDir which already been + # included in .autogen.hash. file + if BuildDirStr in path.abspath(File).lower(): + continue + if not path.exists(LongFilePath(File)): EdkLogger.quiet("[cache warning]: header file %s is missing for module: %s[%s]" % (File, self.MetaFile.Path, self.Arch)) continue - with open(str(File), 'rb') as f: + with open(LongFilePath(File), 'rb') as f: Content = f.read() m.update(Content) - FileList.append((str(File), hashlib.md5(Content).hexdigest())) - + FileList.append((File, hashlib.md5(Content).hexdigest())) - MewIR = ModuleBuildCacheIR(self.MetaFile.Path, self.Arch) - MewIR.ModuleFilesHashDigest = m.digest() - MewIR.ModuleFilesHashHexDigest = m.hexdigest() - MewIR.ModuleFilesChain = FileList - with GlobalData.cache_lock: - try: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.ModuleFilesHashDigest = m.digest() - IR.ModuleFilesHashHexDigest = m.hexdigest() - IR.ModuleFilesChain = FileList - gDict[(self.MetaFile.Path, self.Arch)] = IR - except: - gDict[(self.MetaFile.Path, self.Arch)] = MewIR - - return gDict[(self.MetaFile.Path, self.Arch)] - - def GenPreMakefileHash(self, gDict): - # Early exit if module or library has been hashed and is in memory - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest: - return gDict[(self.MetaFile.Path, self.Arch)] + HashChainFile = path.join(self.BuildDir, self.Name + ".hashchain." + m.hexdigest()) + GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile + try: + with open(LongFilePath(HashChainFile), 'w') as f: + json.dump(FileList, f, indent=2) + except: + EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile) + return False - # skip if the module cache already crashed - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return + def GenPreMakefileHashList(self): + # GenPreMakefileHashList consume below dicts: + # gPlatformHashFile + # gPackageHashFile + # gModuleHashFile + # GenPreMakefileHashList produce no dict. + # gModuleHashFile items might be produced in multiprocessing, so + # need check gModuleHashFile remote dict # skip binary module if self.IsBinaryModule: return - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest: - self.GenModuleFilesHash(gDict) - - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest: - EdkLogger.quiet("[cache warning]: Cannot generate ModuleFilesHashDigest for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - return - - # Initialze hash object + FileList = [] m = hashlib.md5() - # Add Platform level hash - if ('PlatformHash') in gDict: - m.update(gDict[('PlatformHash')].encode('utf-8')) + HashFile = GlobalData.gPlatformHashFile + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) else: - EdkLogger.quiet("[cache warning]: PlatformHash is missing") + EdkLogger.quiet("[cache warning]: No Platform HashFile: %s" % HashFile) # Add Package level hash if self.DependentPackageList: for Pkg in sorted(self.DependentPackageList, key=lambda x: x.PackageName): - if (Pkg.PackageName, 'PackageHash') in gDict: - m.update(gDict[(Pkg.PackageName, 'PackageHash')].encode('utf-8')) + if not (Pkg.PackageName, Pkg.Arch) in GlobalData.gPackageHashFile: + EdkLogger.quiet("[cache warning]:No Package %s for module %s[%s]" % (Pkg.PackageName, self.MetaFile.Path, self.Arch)) + continue + HashFile = GlobalData.gPackageHashFile[(Pkg.PackageName, Pkg.Arch)] + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) else: - EdkLogger.quiet("[cache warning]: %s PackageHash needed by %s[%s] is missing" %(Pkg.PackageName, self.MetaFile.Name, self.Arch)) - - # Add Library hash - if self.LibraryAutoGenList: - for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name): - if not (Lib.MetaFile.Path, Lib.Arch) in gDict or \ - not gDict[(Lib.MetaFile.Path, Lib.Arch)].ModuleFilesHashDigest: - Lib.GenPreMakefileHash(gDict) - m.update(gDict[(Lib.MetaFile.Path, Lib.Arch)].ModuleFilesHashDigest) + EdkLogger.quiet("[cache warning]:No Package HashFile: %s" % HashFile) # Add Module self - m.update(gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest) - - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.PreMakefileHashHexDigest = m.hexdigest() - gDict[(self.MetaFile.Path, self.Arch)] = IR - - return gDict[(self.MetaFile.Path, self.Arch)] - - def GenMakeHeaderFilesHash(self, gDict): - # Early exit if module or library has been hashed and is in memory - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashDigest: - return gDict[(self.MetaFile.Path, self.Arch)] - - # skip if the module cache already crashed - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return - - # skip binary module - if self.IsBinaryModule: - return - - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].CreateCodeFileDone: - if self.IsLibrary: - if (self.MetaFile.File,self.MetaFile.Root,self.Arch,self.MetaFile.Path) in GlobalData.libConstPcd: - self.ConstPcd = GlobalData.libConstPcd[(self.MetaFile.File,self.MetaFile.Root,self.Arch,self.MetaFile.Path)] - if (self.MetaFile.File,self.MetaFile.Root,self.Arch,self.MetaFile.Path) in GlobalData.Refes: - self.ReferenceModules = GlobalData.Refes[(self.MetaFile.File,self.MetaFile.Root,self.Arch,self.MetaFile.Path)] - self.CreateCodeFile() - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].CreateMakeFileDone: - self.CreateMakeFile(GenFfsList=GlobalData.FfsCmd.get((self.MetaFile.Path, self.Arch),[])) - - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].CreateCodeFileDone or \ - not gDict[(self.MetaFile.Path, self.Arch)].CreateMakeFileDone: - EdkLogger.quiet("[cache warning]: Cannot create CodeFile or Makefile for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - return - - DependencyFileSet = set() - # Add Makefile - if gDict[(self.MetaFile.Path, self.Arch)].MakefilePath: - DependencyFileSet.add(gDict[(self.MetaFile.Path, self.Arch)].MakefilePath) + # GenPreMakefileHashList needed in both --binary-destination + # and --hash. And --hash might save ModuleHashFile in remote dict + # during multiprocessing. + if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleHashFile: + HashFile = GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] else: - EdkLogger.quiet("[cache warning]: makefile is missing for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - - # Add header files - if gDict[(self.MetaFile.Path, self.Arch)].DependencyHeaderFileSet: - for File in gDict[(self.MetaFile.Path, self.Arch)].DependencyHeaderFileSet: - DependencyFileSet.add(File) + EdkLogger.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) else: - EdkLogger.quiet("[cache warning]: No dependency header found for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - - # Add AutoGen files - if self.AutoGenFileList: - for File in set(self.AutoGenFileList): - DependencyFileSet.add(File) - - # Caculate all above dependency files hash - # Initialze hash object - FileList = [] - m = hashlib.md5() - for File in sorted(DependencyFileSet, key=lambda x: str(x)): - if not os.path.exists(str(File)): - EdkLogger.quiet("[cache warning]: header file: %s doesn't exist for module: %s[%s]" % (File, self.MetaFile.Path, self.Arch)) - continue - f = open(str(File), 'rb') - Content = f.read() - f.close() - m.update(Content) - FileList.append((str(File), hashlib.md5(Content).hexdigest())) + EdkLogger.quiet("[cache warning]:No Module HashFile: %s" % HashFile) - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.AutoGenFileList = self.AutoGenFileList.keys() - IR.MakeHeaderFilesHashChain = FileList - IR.MakeHeaderFilesHashDigest = m.digest() - gDict[(self.MetaFile.Path, self.Arch)] = IR + # Add Library hash + if self.LibraryAutoGenList: + for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.MetaFile.Path): - return gDict[(self.MetaFile.Path, self.Arch)] + if (Lib.MetaFile.Path, Lib.Arch) in GlobalData.gModuleHashFile: + HashFile = GlobalData.gModuleHashFile[(Lib.MetaFile.Path, Lib.Arch)] + else: + EdkLogger.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib.MetaFile.Path, Lib.Arch)) + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) + else: + EdkLogger.quiet("[cache warning]:No Lib HashFile: %s" % HashFile) - def GenMakeHash(self, gDict): - # Early exit if module or library has been hashed and is in memory - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].MakeHashChain: - return gDict[(self.MetaFile.Path, self.Arch)] + # Save PreMakeHashFileList + FilePath = path.join(self.BuildDir, self.Name + ".PreMakeHashFileList." + m.hexdigest()) + try: + with open(LongFilePath(FilePath), 'w') as f: + json.dump(FileList, f, indent=0) + except: + EdkLogger.quiet("[cache warning]: fail to save PreMake HashFileList: %s" % FilePath) - # skip if the module cache already crashed - if (self.MetaFile.Path, self.Arch) in gDict and \ - gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return + def GenMakefileHashList(self): + # GenMakefileHashList only need in --binary-destination which will + # everything in local dict. So don't need check remote dict. # skip binary module if self.IsBinaryModule: return - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest: - self.GenModuleFilesHash(gDict) - if not gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashDigest: - self.GenMakeHeaderFilesHash(gDict) - - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest or \ - not gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesChain or \ - not gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashDigest or \ - not gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashChain: - EdkLogger.quiet("[cache warning]: Cannot generate ModuleFilesHash or MakeHeaderFilesHash for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - return - - # Initialze hash object + FileList = [] m = hashlib.md5() - MakeHashChain = [] + # Add AutoGen hash + HashFile = GlobalData.gCMakeHashFile[(self.MetaFile.Path, self.Arch)] + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) + else: + EdkLogger.quiet("[cache warning]:No AutoGen HashFile: %s" % HashFile) - # Add hash of makefile and dependency header files - m.update(gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashDigest) - New = list(set(gDict[(self.MetaFile.Path, self.Arch)].MakeHeaderFilesHashChain) - set(MakeHashChain)) - New.sort(key=lambda x: str(x)) - MakeHashChain += New + # Add Module self + if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleHashFile: + HashFile = GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] + else: + EdkLogger.quiet("[cache error]:No ModuleHashFile for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) + else: + EdkLogger.quiet("[cache warning]:No Module HashFile: %s" % HashFile) # Add Library hash if self.LibraryAutoGenList: - for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.Name): - if not (Lib.MetaFile.Path, Lib.Arch) in gDict or \ - not gDict[(Lib.MetaFile.Path, Lib.Arch)].MakeHashChain: - Lib.GenMakeHash(gDict) - if not gDict[(Lib.MetaFile.Path, Lib.Arch)].MakeHashDigest: - print("Cannot generate MakeHash for lib module:", Lib.MetaFile.Path, Lib.Arch) - continue - m.update(gDict[(Lib.MetaFile.Path, Lib.Arch)].MakeHashDigest) - New = list(set(gDict[(Lib.MetaFile.Path, Lib.Arch)].MakeHashChain) - set(MakeHashChain)) - New.sort(key=lambda x: str(x)) - MakeHashChain += New + for Lib in sorted(self.LibraryAutoGenList, key=lambda x: x.MetaFile.Path): + if (Lib.MetaFile.Path, Lib.Arch) in GlobalData.gModuleHashFile: + HashFile = GlobalData.gModuleHashFile[(Lib.MetaFile.Path, Lib.Arch)] + else: + EdkLogger.quiet("[cache error]:No ModuleHashFile for lib: %s[%s]" % (Lib.MetaFile.Path, Lib.Arch)) + if path.exists(LongFilePath(HashFile)): + FileList.append(HashFile) + m.update(HashFile.encode('utf-8')) + else: + EdkLogger.quiet("[cache warning]:No Lib HashFile: %s" % HashFile) - # Add Module self - m.update(gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesHashDigest) - New = list(set(gDict[(self.MetaFile.Path, self.Arch)].ModuleFilesChain) - set(MakeHashChain)) - New.sort(key=lambda x: str(x)) - MakeHashChain += New + # Save MakeHashFileList + FilePath = path.join(self.BuildDir, self.Name + ".MakeHashFileList." + m.hexdigest()) + try: + with open(LongFilePath(FilePath), 'w') as f: + json.dump(FileList, f, indent=0) + except: + EdkLogger.quiet("[cache warning]: fail to save Make HashFileList: %s" % FilePath) + + def CheckHashChainFile(self, HashChainFile): + # Assume the HashChainFile basename format is the 'x.hashchain.16BytesHexStr' + # The x is module name and the 16BytesHexStr is md5 hexdigest of + # all hashchain files content + HashStr = HashChainFile.split('.')[-1] + if len(HashStr) != 32: + EdkLogger.quiet("[cache error]: wrong format HashChainFile:%s" % (File)) + return False - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.MakeHashDigest = m.digest() - IR.MakeHashHexDigest = m.hexdigest() - IR.MakeHashChain = MakeHashChain - gDict[(self.MetaFile.Path, self.Arch)] = IR + try: + with open(LongFilePath(HashChainFile), 'r') as f: + HashChainList = json.load(f) + except: + EdkLogger.quiet("[cache error]: fail to load HashChainFile: %s" % HashChainFile) + return False - return gDict[(self.MetaFile.Path, self.Arch)] + # Print the different file info + # print(HashChainFile) + for idx, (SrcFile, SrcHash) in enumerate (HashChainList): + if SrcFile in GlobalData.gFileHashDict: + DestHash = GlobalData.gFileHashDict[SrcFile] + else: + try: + with open(LongFilePath(SrcFile), 'rb') as f: + Content = f.read() + DestHash = hashlib.md5(Content).hexdigest() + GlobalData.gFileHashDict[SrcFile] = DestHash + except IOError as X: + # cache miss if SrcFile is removed in new version code + GlobalData.gFileHashDict[SrcFile] = 0 + EdkLogger.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile, SrcFile)) + return False + if SrcHash != DestHash: + EdkLogger.quiet("[cache insight]: first cache miss file in %s is %s" % (HashChainFile, SrcFile)) + return False + + return True ## Decide whether we can skip the left autogen and make process - def CanSkipbyPreMakefileCache(self, gDict): + def CanSkipbyMakeCache(self): + # For --binary-source only + # CanSkipbyMakeCache consume below dicts: + # gModuleMakeCacheStatus + # gHashChainStatus + # GenPreMakefileHashList produce gModuleMakeCacheStatus, gModuleHashFile dict. + # all these dicts might be produced in multiprocessing, so + # need check these remote dict + if not GlobalData.gBinCacheSource: return False - if gDict[(self.MetaFile.Path, self.Arch)].PreMakeCacheHit: - return True - - if gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return False + if (self.MetaFile.Path, self.Arch) in GlobalData.gModuleMakeCacheStatus: + return GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] - # If Module is binary, do not skip by cache + # If Module is binary, which has special build rule, do not skip by cache. if self.IsBinaryModule: + print("[cache miss]: MakeCache: Skip BinaryModule:", self.MetaFile.Path, self.Arch) + GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False return False - # .inc is contains binary information so do not skip by hash as well + # see .inc as binary file, do not skip by hash for f_ext in self.SourceFileList: if '.inc' in str(f_ext): + print("[cache miss]: MakeCache: Skip '.inc' File:", self.MetaFile.Path, self.Arch) + GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False return False - # Get the module hash values from stored cache and currrent build - # then check whether cache hit based on the hash values - # if cache hit, restore all the files from cache - FileDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) + ModuleCacheDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) FfsDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name) ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)] - ModuleHashPair = path.join(FileDir, self.Name + ".ModuleHashPair") - if not os.path.exists(ModuleHashPair): - EdkLogger.quiet("[cache warning]: Cannot find ModuleHashPair file: %s" % ModuleHashPair) - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.CacheCrash = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - return False - + ModuleHashPair = path.join(ModuleCacheDir, self.Name + ".ModuleHashPair") try: - with open(ModuleHashPair, 'r') as f: + with open(LongFilePath(ModuleHashPair), 'r') as f: ModuleHashPairList = json.load(f) except: + # ModuleHashPair might not exist for new added module + GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False EdkLogger.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair) + print("[cache miss]: MakeCache:", self.MetaFile.Path, self.Arch) return False - self.GenPreMakefileHash(gDict) - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest: - EdkLogger.quiet("[cache warning]: PreMakefileHashHexDigest is missing for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - return False - - MakeHashStr = None - CurrentPreMakeHash = gDict[(self.MetaFile.Path, self.Arch)].PreMakefileHashHexDigest + # Check the PreMakeHash in ModuleHashPairList one by one for idx, (PreMakefileHash, MakeHash) in enumerate (ModuleHashPairList): - if PreMakefileHash == CurrentPreMakeHash: - MakeHashStr = str(MakeHash) + SourceHashDir = path.join(ModuleCacheDir, MakeHash) + SourceFfsHashDir = path.join(FfsDir, MakeHash) + PreMakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".PreMakeHashFileList." + PreMakefileHash) + MakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".MakeHashFileList." + MakeHash) - if not MakeHashStr: - return False + try: + with open(LongFilePath(MakeHashFileList_FilePah), 'r') as f: + MakeHashFileList = json.load(f) + except: + EdkLogger.quiet("[cache error]: fail to load MakeHashFileList file: %s" % MakeHashFileList_FilePah) + continue - TargetHashDir = path.join(FileDir, MakeHashStr) - TargetFfsHashDir = path.join(FfsDir, MakeHashStr) + HashMiss = False + for HashChainFile in MakeHashFileList: + HashChainStatus = None + if HashChainFile in GlobalData.gHashChainStatus: + HashChainStatus = GlobalData.gHashChainStatus[HashChainFile] + if HashChainStatus == False: + HashMiss = True + break + elif HashChainStatus == True: + continue + # Convert to path start with cache source dir + RelativePath = os.path.relpath(HashChainFile, self.WorkspaceDir) + NewFilePath = os.path.join(GlobalData.gBinCacheSource, RelativePath) + if self.CheckHashChainFile(NewFilePath): + GlobalData.gHashChainStatus[HashChainFile] = True + # Save the module self HashFile for GenPreMakefileHashList later usage + if self.Name + ".hashchain." in HashChainFile: + GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile + else: + GlobalData.gHashChainStatus[HashChainFile] = False + HashMiss = True + break - if not os.path.exists(TargetHashDir): - EdkLogger.quiet("[cache warning]: Cache folder is missing: %s" % TargetHashDir) - return False + if HashMiss: + continue - for root, dir, files in os.walk(TargetHashDir): - for f in files: - File = path.join(root, f) - self.CacheCopyFile(self.OutputDir, TargetHashDir, File) - if os.path.exists(TargetFfsHashDir): - for root, dir, files in os.walk(TargetFfsHashDir): + # PreMakefile cache hit, restore the module build result + for root, dir, files in os.walk(SourceHashDir): for f in files: File = path.join(root, f) - self.CacheCopyFile(self.FfsOutputDir, TargetFfsHashDir, File) - - if self.Name == "PcdPeim" or self.Name == "PcdDxe": - CreatePcdDatabaseCode(self, TemplateString(), TemplateString()) + self.CacheCopyFile(self.BuildDir, SourceHashDir, File) + if os.path.exists(SourceFfsHashDir): + for root, dir, files in os.walk(SourceFfsHashDir): + for f in files: + File = path.join(root, f) + self.CacheCopyFile(self.FfsOutputDir, SourceFfsHashDir, File) + + if self.Name == "PcdPeim" or self.Name == "PcdDxe": + CreatePcdDatabaseCode(self, TemplateString(), TemplateString()) + + print("[cache hit]: MakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True + return True - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.PreMakeCacheHit = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - print("[cache hit]: checkpoint_PreMakefile:", self.MetaFile.Path, self.Arch) - #EdkLogger.quiet("cache hit: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return True + print("[cache miss]: MakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModuleMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + return False - ## Decide whether we can skip the make process - def CanSkipbyMakeCache(self, gDict): - if not GlobalData.gBinCacheSource: + ## Decide whether we can skip the left autogen and make process + def CanSkipbyPreMakeCache(self): + # CanSkipbyPreMakeCache consume below dicts: + # gModulePreMakeCacheStatus + # gHashChainStatus + # gModuleHashFile + # GenPreMakefileHashList produce gModulePreMakeCacheStatus dict. + # all these dicts might be produced in multiprocessing, so + # need check these remote dicts + + if not GlobalData.gUseHashCache or GlobalData.gBinCacheDest: return False - if gDict[(self.MetaFile.Path, self.Arch)].MakeCacheHit: - return True - - if gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return False + if (self.MetaFile.Path, self.Arch) in GlobalData.gModulePreMakeCacheStatus: + return GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] - # If Module is binary, do not skip by cache + # If Module is binary, which has special build rule, do not skip by cache. if self.IsBinaryModule: - print("[cache miss]: checkpoint_Makefile: binary module:", self.MetaFile.Path, self.Arch) + print("[cache miss]: PreMakeCache: Skip BinaryModule:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False return False - # .inc is contains binary information so do not skip by hash as well + # see .inc as binary file, do not skip by hash for f_ext in self.SourceFileList: if '.inc' in str(f_ext): - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.MakeCacheHit = False - gDict[(self.MetaFile.Path, self.Arch)] = IR - print("[cache miss]: checkpoint_Makefile: .inc module:", self.MetaFile.Path, self.Arch) + print("[cache miss]: PreMakeCache: Skip '.inc' File:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False return False - # Get the module hash values from stored cache and currrent build - # then check whether cache hit based on the hash values - # if cache hit, restore all the files from cache - FileDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) - FfsDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name) - - ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)] - ModuleHashPair = path.join(FileDir, self.Name + ".ModuleHashPair") - if not os.path.exists(ModuleHashPair): - EdkLogger.quiet("[cache warning]: Cannot find ModuleHashPair file: %s" % ModuleHashPair) - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.CacheCrash = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - return False - - try: - with open(ModuleHashPair, 'r') as f: - ModuleHashPairList = json.load(f) - except: - EdkLogger.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair) - return False - - self.GenMakeHash(gDict) - if not (self.MetaFile.Path, self.Arch) in gDict or \ - not gDict[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest: - EdkLogger.quiet("[cache warning]: MakeHashHexDigest is missing for module %s[%s]" %(self.MetaFile.Path, self.Arch)) - return False - - MakeHashStr = None - CurrentMakeHash = gDict[(self.MetaFile.Path, self.Arch)].MakeHashHexDigest - for idx, (PreMakefileHash, MakeHash) in enumerate (ModuleHashPairList): - if MakeHash == CurrentMakeHash: - MakeHashStr = str(MakeHash) - - if not MakeHashStr: - print("[cache miss]: checkpoint_Makefile:", self.MetaFile.Path, self.Arch) - return False - - TargetHashDir = path.join(FileDir, MakeHashStr) - TargetFfsHashDir = path.join(FfsDir, MakeHashStr) - if not os.path.exists(TargetHashDir): - EdkLogger.quiet("[cache warning]: Cache folder is missing: %s" % TargetHashDir) - return False - - for root, dir, files in os.walk(TargetHashDir): - for f in files: - File = path.join(root, f) - self.CacheCopyFile(self.OutputDir, TargetHashDir, File) - - if os.path.exists(TargetFfsHashDir): - for root, dir, files in os.walk(TargetFfsHashDir): - for f in files: - File = path.join(root, f) - self.CacheCopyFile(self.FfsOutputDir, TargetFfsHashDir, File) - - if self.Name == "PcdPeim" or self.Name == "PcdDxe": - CreatePcdDatabaseCode(self, TemplateString(), TemplateString()) - with GlobalData.cache_lock: - IR = gDict[(self.MetaFile.Path, self.Arch)] - IR.MakeCacheHit = True - gDict[(self.MetaFile.Path, self.Arch)] = IR - print("[cache hit]: checkpoint_Makefile:", self.MetaFile.Path, self.Arch) - return True - - ## Show the first file name which causes cache miss - def PrintFirstMakeCacheMissFile(self, gDict): + # For --hash only in the incremental build if not GlobalData.gBinCacheSource: - return - - # skip if the module cache already crashed - if gDict[(self.MetaFile.Path, self.Arch)].CacheCrash: - return - - # skip binary module - if self.IsBinaryModule: - return + Files = [path.join(self.BuildDir, f) for f in os.listdir(self.BuildDir) if path.isfile(path.join(self.BuildDir, f))] + PreMakeHashFileList_FilePah = None + MakeTimeStamp = 0 + # Find latest PreMakeHashFileList file in self.BuildDir folder + for File in Files: + if ".PreMakeHashFileList." in File: + FileTimeStamp = os.stat(path.join(self.BuildDir, File))[8] + if FileTimeStamp > MakeTimeStamp: + MakeTimeStamp = FileTimeStamp + PreMakeHashFileList_FilePah = File + if not PreMakeHashFileList_FilePah: + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + return False - if not (self.MetaFile.Path, self.Arch) in gDict: - return + try: + with open(LongFilePath(PreMakeHashFileList_FilePah), 'r') as f: + PreMakeHashFileList = json.load(f) + except: + EdkLogger.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah) + print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + return False - # Only print cache miss file for the MakeCache not hit module - if gDict[(self.MetaFile.Path, self.Arch)].MakeCacheHit: - return + HashMiss = False + for HashChainFile in PreMakeHashFileList: + HashChainStatus = None + if HashChainFile in GlobalData.gHashChainStatus: + HashChainStatus = GlobalData.gHashChainStatus[HashChainFile] + if HashChainStatus == False: + HashMiss = True + break + elif HashChainStatus == True: + continue + if self.CheckHashChainFile(HashChainFile): + GlobalData.gHashChainStatus[HashChainFile] = True + # Save the module self HashFile for GenPreMakefileHashList later usage + if self.Name + ".hashchain." in HashChainFile: + GlobalData.gModuleHashFile[(self.MetaFile.Path, self.Arch)] = HashChainFile + else: + GlobalData.gHashChainStatus[HashChainFile] = False + HashMiss = True + break - if not gDict[(self.MetaFile.Path, self.Arch)].MakeHashChain: - EdkLogger.quiet("[cache insight]: MakeHashChain is missing for: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return + if HashMiss: + print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + return False + else: + print("[cache hit]: PreMakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True + return True - # Find the cache dir name through the .ModuleHashPair file info - FileDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) + ModuleCacheDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, self.Arch, self.SourceDir, self.MetaFile.BaseName) + FfsDir = path.join(GlobalData.gBinCacheSource, self.PlatformInfo.OutputDir, self.BuildTarget + "_" + self.ToolChain, TAB_FV_DIRECTORY, "Ffs", self.Guid + self.Name) ModuleHashPairList = [] # tuple list: [tuple(PreMakefileHash, MakeHash)] - ModuleHashPair = path.join(FileDir, self.Name + ".ModuleHashPair") - if not os.path.exists(ModuleHashPair): - EdkLogger.quiet("[cache insight]: Cannot find ModuleHashPair file for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return - + ModuleHashPair = path.join(ModuleCacheDir, self.Name + ".ModuleHashPair") try: - with open(ModuleHashPair, 'r') as f: + with open(LongFilePath(ModuleHashPair), 'r') as f: ModuleHashPairList = json.load(f) except: - EdkLogger.quiet("[cache insight]: Cannot load ModuleHashPair file for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return + # ModuleHashPair might not exist for new added module + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + EdkLogger.quiet("[cache warning]: fail to load ModuleHashPair file: %s" % ModuleHashPair) + print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch) + return False - MakeHashSet = set() + # Check the PreMakeHash in ModuleHashPairList one by one for idx, (PreMakefileHash, MakeHash) in enumerate (ModuleHashPairList): - TargetHashDir = path.join(FileDir, str(MakeHash)) - if os.path.exists(TargetHashDir): - MakeHashSet.add(MakeHash) - if not MakeHashSet: - EdkLogger.quiet("[cache insight]: Cannot find valid cache dir for module: %s[%s]" % (self.MetaFile.Path, self.Arch)) - return + SourceHashDir = path.join(ModuleCacheDir, MakeHash) + SourceFfsHashDir = path.join(FfsDir, MakeHash) + PreMakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".PreMakeHashFileList." + PreMakefileHash) + MakeHashFileList_FilePah = path.join(ModuleCacheDir, self.Name + ".MakeHashFileList." + MakeHash) - TargetHash = list(MakeHashSet)[0] - TargetHashDir = path.join(FileDir, str(TargetHash)) - if len(MakeHashSet) > 1 : - EdkLogger.quiet("[cache insight]: found multiple cache dirs for this module, random select dir '%s' to search the first cache miss file: %s[%s]" % (TargetHash, self.MetaFile.Path, self.Arch)) - - ListFile = path.join(TargetHashDir, self.Name + '.MakeHashChain') - if os.path.exists(ListFile): try: - f = open(ListFile, 'r') - CachedList = json.load(f) - f.close() + with open(LongFilePath(PreMakeHashFileList_FilePah), 'r') as f: + PreMakeHashFileList = json.load(f) except: - EdkLogger.quiet("[cache insight]: Cannot load MakeHashChain file: %s" % ListFile) - return - else: - EdkLogger.quiet("[cache insight]: Cannot find MakeHashChain file: %s" % ListFile) - return - - CurrentList = gDict[(self.MetaFile.Path, self.Arch)].MakeHashChain - for idx, (file, hash) in enumerate (CurrentList): - (filecached, hashcached) = CachedList[idx] - if file != filecached: - EdkLogger.quiet("[cache insight]: first different file in %s[%s] is %s, the cached one is %s" % (self.MetaFile.Path, self.Arch, file, filecached)) - break - if hash != hashcached: - EdkLogger.quiet("[cache insight]: first cache miss file in %s[%s] is %s" % (self.MetaFile.Path, self.Arch, file)) - break - - return True + EdkLogger.quiet("[cache error]: fail to load PreMakeHashFileList file: %s" % PreMakeHashFileList_FilePah) + continue - ## Decide whether we can skip the ModuleAutoGen process - def CanSkipbyCache(self, gDict): - # Hashing feature is off - if not GlobalData.gBinCacheSource: - return False + HashMiss = False + for HashChainFile in PreMakeHashFileList: + HashChainStatus = None + if HashChainFile in GlobalData.gHashChainStatus: + HashChainStatus = GlobalData.gHashChainStatus[HashChainFile] + if HashChainStatus == False: + HashMiss = True + break + elif HashChainStatus == True: + continue + # Convert to path start with cache source dir + RelativePath = os.path.relpath(HashChainFile, self.WorkspaceDir) + NewFilePath = os.path.join(GlobalData.gBinCacheSource, RelativePath) + if self.CheckHashChainFile(NewFilePath): + GlobalData.gHashChainStatus[HashChainFile] = True + else: + GlobalData.gHashChainStatus[HashChainFile] = False + HashMiss = True + break - if self in GlobalData.gBuildHashSkipTracking: - return GlobalData.gBuildHashSkipTracking[self] + if HashMiss: + continue - # If library or Module is binary do not skip by hash - if self.IsBinaryModule: - GlobalData.gBuildHashSkipTracking[self] = False - return False + # PreMakefile cache hit, restore the module build result + for root, dir, files in os.walk(SourceHashDir): + for f in files: + File = path.join(root, f) + self.CacheCopyFile(self.BuildDir, SourceHashDir, File) + if os.path.exists(SourceFfsHashDir): + for root, dir, files in os.walk(SourceFfsHashDir): + for f in files: + File = path.join(root, f) + self.CacheCopyFile(self.FfsOutputDir, SourceFfsHashDir, File) + + if self.Name == "PcdPeim" or self.Name == "PcdDxe": + CreatePcdDatabaseCode(self, TemplateString(), TemplateString()) + + print("[cache hit]: PreMakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = True + return True - # .inc is contains binary information so do not skip by hash as well - for f_ext in self.SourceFileList: - if '.inc' in str(f_ext): - GlobalData.gBuildHashSkipTracking[self] = False - return False + print("[cache miss]: PreMakeCache:", self.MetaFile.Path, self.Arch) + GlobalData.gModulePreMakeCacheStatus[(self.MetaFile.Path, self.Arch)] = False + return False - if not (self.MetaFile.Path, self.Arch) in gDict: + ## Decide whether we can skip the Module build + def CanSkipbyCache(self, gHitSet): + # Hashing feature is off + if not GlobalData.gBinCacheSource: return False - if gDict[(self.MetaFile.Path, self.Arch)].PreMakeCacheHit: - GlobalData.gBuildHashSkipTracking[self] = True - return True - - if gDict[(self.MetaFile.Path, self.Arch)].MakeCacheHit: - GlobalData.gBuildHashSkipTracking[self] = True + if self in gHitSet: return True return False diff --git a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py index ec0c25bd148..668126aaac4 100644 --- a/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/WorkspaceAutoGen.py @@ -23,6 +23,7 @@ from Common.BuildToolError import * from Common.DataType import * from Common.Misc import * +import json ## Regular expression for splitting Dependency Expression string into tokens gDepexTokenPattern = re.compile("(\(|\)|\w+| \S+\.inf)") @@ -127,7 +128,7 @@ def _InitWorker(self, WorkspaceDir, ActivePlatform, Target, Toolchain, ArchList, self.CreateBuildOptionsFile() self.CreatePcdTokenNumberFile() - self.CreateModuleHashInfo() + self.GeneratePlatformLevelHash() # # Merge Arch @@ -528,12 +529,12 @@ def CreatePcdTokenNumberFile(self): PcdTokenNumber += str(Pa.PcdTokenNumber[Pcd.TokenCName, Pcd.TokenSpaceGuidCName]) SaveFileOnChange(os.path.join(self.BuildDir, 'PcdTokenNumber'), PcdTokenNumber, False) - def CreateModuleHashInfo(self): + def GeneratePlatformLevelHash(self): # # Get set of workspace metafiles # AllWorkSpaceMetaFiles = self._GetMetaFiles(self.BuildTarget, self.ToolChain) - + AllWorkSpaceMetaFileList = sorted(AllWorkSpaceMetaFiles, key=lambda x: str(x)) # # Retrieve latest modified time of all metafiles # @@ -544,16 +545,35 @@ def CreateModuleHashInfo(self): self._SrcTimeStamp = SrcTimeStamp if GlobalData.gUseHashCache: + FileList = [] m = hashlib.md5() - for files in AllWorkSpaceMetaFiles: - if files.endswith('.dec'): + for file in AllWorkSpaceMetaFileList: + if file.endswith('.dec'): continue - f = open(files, 'rb') + f = open(file, 'rb') Content = f.read() f.close() m.update(Content) - SaveFileOnChange(os.path.join(self.BuildDir, 'AutoGen.hash'), m.hexdigest(), False) - GlobalData.gPlatformHash = m.hexdigest() + FileList.append((str(file), hashlib.md5(Content).hexdigest())) + + HashDir = path.join(self.BuildDir, "Hash_Platform") + HashFile = path.join(HashDir, 'Platform.hash.' + m.hexdigest()) + SaveFileOnChange(HashFile, m.hexdigest(), False) + HashChainFile = path.join(HashDir, 'Platform.hashchain.' + m.hexdigest()) + GlobalData.gPlatformHashFile = HashChainFile + try: + with open(HashChainFile, 'w') as f: + json.dump(FileList, f, indent=2) + except: + EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile) + + if GlobalData.gBinCacheDest: + # Copy platform hash files to cache destination + FileDir = path.join(GlobalData.gBinCacheDest, self.OutputDir, self.BuildTarget + "_" + self.ToolChain, "Hash_Platform") + CacheFileDir = FileDir + CreateDirectory(CacheFileDir) + CopyFileOnChange(HashFile, CacheFileDir) + CopyFileOnChange(HashChainFile, CacheFileDir) # # Write metafile list to build directory @@ -564,7 +584,7 @@ def CreateModuleHashInfo(self): if not os.path.exists(self.BuildDir): os.makedirs(self.BuildDir) with open(os.path.join(self.BuildDir, 'AutoGen'), 'w+') as file: - for f in AllWorkSpaceMetaFiles: + for f in AllWorkSpaceMetaFileList: print(f, file=file) return True @@ -572,15 +592,16 @@ def _GenPkgLevelHash(self, Pkg): if Pkg.PackageName in GlobalData.gPackageHash: return - PkgDir = os.path.join(self.BuildDir, Pkg.Arch, Pkg.PackageName) + PkgDir = os.path.join(self.BuildDir, Pkg.Arch, "Hash_Pkg", Pkg.PackageName) CreateDirectory(PkgDir) - HashFile = os.path.join(PkgDir, Pkg.PackageName + '.hash') + FileList = [] m = hashlib.md5() # Get .dec file's hash value f = open(Pkg.MetaFile.Path, 'rb') Content = f.read() f.close() m.update(Content) + FileList.append((str(Pkg.MetaFile.Path), hashlib.md5(Content).hexdigest())) # Get include files hash value if Pkg.Includes: for inc in sorted(Pkg.Includes, key=lambda x: str(x)): @@ -591,9 +612,28 @@ def _GenPkgLevelHash(self, Pkg): Content = f.read() f.close() m.update(Content) - SaveFileOnChange(HashFile, m.hexdigest(), False) + FileList.append((str(File_Path), hashlib.md5(Content).hexdigest())) GlobalData.gPackageHash[Pkg.PackageName] = m.hexdigest() + HashDir = PkgDir + HashFile = path.join(HashDir, Pkg.PackageName + '.hash.' + m.hexdigest()) + SaveFileOnChange(HashFile, m.hexdigest(), False) + HashChainFile = path.join(HashDir, Pkg.PackageName + '.hashchain.' + m.hexdigest()) + GlobalData.gPackageHashFile[(Pkg.PackageName, Pkg.Arch)] = HashChainFile + try: + with open(HashChainFile, 'w') as f: + json.dump(FileList, f, indent=2) + except: + EdkLogger.quiet("[cache warning]: fail to save hashchain file:%s" % HashChainFile) + + if GlobalData.gBinCacheDest: + # Copy Pkg hash files to cache destination dir + FileDir = path.join(GlobalData.gBinCacheDest, self.OutputDir, self.BuildTarget + "_" + self.ToolChain, Pkg.Arch, "Hash_Pkg", Pkg.PackageName) + CacheFileDir = FileDir + CreateDirectory(CacheFileDir) + CopyFileOnChange(HashFile, CacheFileDir) + CopyFileOnChange(HashChainFile, CacheFileDir) + def _GetMetaFiles(self, Target, Toolchain): AllWorkSpaceMetaFiles = set() # diff --git a/BaseTools/Source/Python/Common/GlobalData.py b/BaseTools/Source/Python/Common/GlobalData.py index 74c6d0079bb..0b3ebe035d1 100755 --- a/BaseTools/Source/Python/Common/GlobalData.py +++ b/BaseTools/Source/Python/Common/GlobalData.py @@ -104,29 +104,20 @@ gBinCacheDest = None gBinCacheSource = None gPlatformHash = None -gPackageHash = {} -gModuleHash = {} +gPlatformHashFile = None +gPackageHash = None +gPackageHashFile = None +gModuleHashFile = None +gCMakeHashFile = None +gHashChainStatus = None +gModulePreMakeCacheStatus = None +gModuleMakeCacheStatus = None +gFileHashDict = None +gModuleAllCacheStatus = None +gModuleCacheHit = None + gEnableGenfdsMultiThread = True gSikpAutoGenCache = set() - -# Dictionary for tracking Module build status as success or failure -# Top Dict: Key: Arch Type Value: Dictionary -# Second Dict: Key: AutoGen Obj Value: 'SUCCESS'\'FAIL'\'FAIL_METAFILE' -gModuleBuildTracking = dict() - -# Dictionary of booleans that dictate whether a module or -# library can be skiped -# Top Dict: Key: Arch Type Value: Dictionary -# Second Dict: Key: Module\Library Name Value: True\False -gBuildHashSkipTracking = dict() - -# Common dictionary to share module cache intermediate result and state -gCacheIR = None -# Common lock for the module cache intermediate data -cache_lock = None # Common lock for the file access in multiple process AutoGens file_lock = None -# Common dictionary to share platform libraries' constant Pcd -libConstPcd = None -# Common dictionary to share platform libraries' reference info -Refes = None + diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 6fcfc7ec7ab..8a8e32e496f 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -620,7 +620,7 @@ def IsReady(self): # def AddDependency(self, Dependency): for Dep in Dependency: - if not Dep.BuildObject.IsBinaryModule and not Dep.BuildObject.CanSkipbyCache(GlobalData.gCacheIR): + if not Dep.BuildObject.IsBinaryModule and not Dep.BuildObject.CanSkipbyCache(GlobalData.gModuleCacheHit): self.DependencyList.append(BuildTask.New(Dep)) # BuildTask list ## The thread wrapper of LaunchCommand function @@ -633,10 +633,13 @@ def _CommandThread(self, Command, WorkingDir): self.BuildItem.BuildObject.BuildTime = LaunchCommand(Command, WorkingDir,self.BuildItem.BuildObject) self.CompleteFlag = True - # Run hash operation post dependency, to account for libs - if GlobalData.gUseHashCache and self.BuildItem.BuildObject.IsLibrary: - HashFile = path.join(self.BuildItem.BuildObject.BuildDir, self.BuildItem.BuildObject.Name + ".hash") - SaveFileOnChange(HashFile, self.BuildItem.BuildObject.GenModuleHash(), True) + # Run hash operation post dependency to account for libs + # Run if --hash or --binary-destination + if GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + self.BuildItem.BuildObject.GenModuleHash() + if GlobalData.gBinCacheDest: + self.BuildItem.BuildObject.GenCMakeHash() + except: # # TRICK: hide the output of threads left running, so that the user can @@ -653,14 +656,6 @@ def _CommandThread(self, Command, WorkingDir): BuildTask._ErrorMessage = "%s broken\n %s [%s]" % \ (threading.currentThread().getName(), Command, WorkingDir) - # Set the value used by hash invalidation flow in GlobalData.gModuleBuildTracking to 'SUCCESS' - # If Module or Lib is being tracked, it did not fail header check test, and built successfully - if (self.BuildItem.BuildObject in GlobalData.gModuleBuildTracking and - GlobalData.gModuleBuildTracking[self.BuildItem.BuildObject] != 'FAIL_METAFILE' and - not BuildTask._ErrorFlag.isSet() - ): - GlobalData.gModuleBuildTracking[self.BuildItem.BuildObject] = 'SUCCESS' - # indicate there's a thread is available for another build task BuildTask._RunningQueueLock.acquire() BuildTask._RunningQueue.pop(self.BuildItem) @@ -835,11 +830,20 @@ def __init__(self, Target, WorkspaceDir, BuildOptions,log_q): self.AutoGenMgr = None EdkLogger.info("") os.chdir(self.WorkspaceDir) - GlobalData.gCacheIR = Manager().dict() self.log_q = log_q GlobalData.file_lock = mp.Lock() - GlobalData.cache_lock = mp.Lock() - def StartAutoGen(self,mqueue, DataPipe,SkipAutoGen,PcdMaList,share_data): + # Init cache data for local only + GlobalData.gPackageHashFile = dict() + GlobalData.gModulePreMakeCacheStatus = dict() + GlobalData.gModuleMakeCacheStatus = dict() + GlobalData.gHashChainStatus = dict() + GlobalData.gCMakeHashFile = dict() + GlobalData.gModuleHashFile = dict() + GlobalData.gFileHashDict = dict() + GlobalData.gModuleAllCacheStatus = set() + GlobalData.gModuleCacheHit = set() + + def StartAutoGen(self,mqueue, DataPipe,SkipAutoGen,PcdMaList,cqueue): try: if SkipAutoGen: return True,0 @@ -849,29 +853,27 @@ def StartAutoGen(self,mqueue, DataPipe,SkipAutoGen,PcdMaList,share_data): if FfsCmd is None: FfsCmd = {} GlobalData.FfsCmd = FfsCmd - GlobalData.libConstPcd = DataPipe.Get("LibConstPcd") - GlobalData.Refes = DataPipe.Get("REFS") - auto_workers = [AutoGenWorkerInProcess(mqueue,DataPipe.dump_file,feedback_q,GlobalData.file_lock,GlobalData.cache_lock,share_data,self.log_q,error_event) for _ in range(self.ThreadNumber)] + auto_workers = [AutoGenWorkerInProcess(mqueue,DataPipe.dump_file,feedback_q,GlobalData.file_lock,cqueue,self.log_q,error_event) for _ in range(self.ThreadNumber)] self.AutoGenMgr = AutoGenManager(auto_workers,feedback_q,error_event) self.AutoGenMgr.start() for w in auto_workers: w.start() if PcdMaList is not None: for PcdMa in PcdMaList: - if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: - PcdMa.GenModuleFilesHash(share_data) - PcdMa.GenPreMakefileHash(share_data) - if PcdMa.CanSkipbyPreMakefileCache(share_data): - continue + # SourceFileList calling sequence impact the makefile string sequence. + # Create cached SourceFileList here to unify its calling sequence for both + # CanSkipbyPreMakeCache and CreateCodeFile/CreateMakeFile. + RetVal = PcdMa.SourceFileList + # Force cache miss for PCD driver + if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]: + cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "PreMakeCache", False)) PcdMa.CreateCodeFile(False) PcdMa.CreateMakeFile(False,GenFfsList = DataPipe.Get("FfsCommand").get((PcdMa.MetaFile.Path, PcdMa.Arch),[])) + # Force cache miss for PCD driver if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: - PcdMa.GenMakeHeaderFilesHash(share_data) - PcdMa.GenMakeHash(share_data) - if PcdMa.CanSkipbyMakeCache(share_data): - continue + cqueue.put((PcdMa.MetaFile.Path, PcdMa.Arch, "MakeCache", False)) self.AutoGenMgr.join() rt = self.AutoGenMgr.Status @@ -1182,38 +1184,6 @@ def LaunchPostbuild(self): EdkLogger.error("Postbuild", POSTBUILD_ERROR, 'Postbuild process is not success!') EdkLogger.info("\n- Postbuild Done -\n") - ## Error handling for hash feature - # - # On BuildTask error, iterate through the Module Build tracking - # dictionary to determine wheather a module failed to build. Invalidate - # the hash associated with that module by removing it from storage. - # - # - def invalidateHash(self): - # Only for hashing feature - if not GlobalData.gUseHashCache: - return - - # GlobalData.gModuleBuildTracking contains only modules or libs that cannot be skipped by hash - for Ma in GlobalData.gModuleBuildTracking: - # Skip invalidating for Successful Module/Lib builds - if GlobalData.gModuleBuildTracking[Ma] == 'SUCCESS': - continue - - # The module failed to build, failed to start building, or failed the header check test from this point on - - # Remove .hash from build - ModuleHashFile = os.path.join(Ma.BuildDir, Ma.Name + ".hash") - if os.path.exists(ModuleHashFile): - os.remove(ModuleHashFile) - - # Remove .hash file from cache - if GlobalData.gBinCacheDest: - FileDir = os.path.join(GlobalData.gBinCacheDest, Ma.PlatformInfo.OutputDir, Ma.BuildTarget + "_" + Ma.ToolChain, Ma.Arch, Ma.SourceDir, Ma.MetaFile.BaseName) - HashFile = os.path.join(FileDir, Ma.Name + '.hash') - if os.path.exists(HashFile): - os.remove(HashFile) - ## Build a module or platform # # Create autogen code and makefile for a module or platform, and the launch @@ -1251,7 +1221,8 @@ def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMak self.Progress.Start("Generating makefile and code") data_pipe_file = os.path.join(AutoGenObject.BuildDir, "GlobalVar_%s_%s.bin" % (str(AutoGenObject.Guid),AutoGenObject.Arch)) AutoGenObject.DataPipe.dump(data_pipe_file) - autogen_rt,errorcode = self.StartAutoGen(mqueue, AutoGenObject.DataPipe, self.SkipAutoGen, PcdMaList, GlobalData.gCacheIR) + cqueue = mp.Queue() + autogen_rt,errorcode = self.StartAutoGen(mqueue, AutoGenObject.DataPipe, self.SkipAutoGen, PcdMaList, cqueue) AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt") with open(AutoGenIdFile,"w") as fw: fw.write("Arch=%s\n" % "|".join((AutoGenObject.Workspace.ArchList))) @@ -1292,7 +1263,11 @@ def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMak LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: - self.UpdateBuildCache() + self.GenDestCache() + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + # Only for --hash + # Update PreMakeCacheChain files + self.GenLocalPreMakeCache() self.BuildModules = [] return True @@ -1326,7 +1301,11 @@ def _BuildPa(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMak LaunchCommand(NewBuildCommand, AutoGenObject.MakeFileDir,ModAutoGen) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: - self.UpdateBuildCache() + self.GenDestCache() + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + # Only for --hash + # Update PreMakeCacheChain files + self.GenLocalPreMakeCache() self.BuildModules = [] return True @@ -1422,7 +1401,11 @@ def _Build(self, Target, AutoGenObject, CreateDepsCodeFile=True, CreateDepsMakeF AutoGenObject.BuildTime = LaunchCommand(BuildCommand, AutoGenObject.MakeFileDir) self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: - self.UpdateBuildCache() + self.GenDestCache() + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + # Only for --hash + # Update PreMakeCacheChain files + self.GenLocalPreMakeCache() self.BuildModules = [] return True @@ -1870,13 +1853,7 @@ def _BuildModule(self): if GlobalData.gEnableGenfdsMultiThread and self.Fdf: CmdListDict = self._GenFfsCmd(Wa.ArchList) - # Add Platform and Package level hash in share_data for module hash calculation later - if GlobalData.gBinCacheSource or GlobalData.gBinCacheDest: - GlobalData.gCacheIR[('PlatformHash')] = GlobalData.gPlatformHash - for PkgName in GlobalData.gPackageHash.keys(): - GlobalData.gCacheIR[(PkgName, 'PackageHash')] = GlobalData.gPackageHash[PkgName] GlobalData.file_lock = mp.Lock() - GlobalData.cache_lock = mp.Lock() GlobalData.FfsCmd = CmdListDict self.Progress.Stop("done!") @@ -1888,8 +1865,6 @@ def _BuildModule(self): AutoGenStart = time.time() GlobalData.gGlobalDefines['ARCH'] = Arch Pa = PlatformAutoGen(Wa, self.PlatformFile, BuildTarget, ToolChain, Arch) - GlobalData.libConstPcd = Pa.DataPipe.Get("LibConstPcd") - GlobalData.Refes = Pa.DataPipe.Get("REFS") for Module in Pa.Platform.Modules: if self.ModuleFile.Dir == Module.Dir and self.ModuleFile.Name == Module.Name: Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe) @@ -1900,13 +1875,11 @@ def _BuildModule(self): Ma.Workspace = Wa MaList.append(Ma) - if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: - Ma.GenModuleFilesHash(GlobalData.gCacheIR) - Ma.GenPreMakefileHash(GlobalData.gCacheIR) - if Ma.CanSkipbyPreMakefileCache(GlobalData.gCacheIR): - self.HashSkipModules.append(Ma) - EdkLogger.quiet("cache hit: %s[%s]" % (Ma.MetaFile.Path, Ma.Arch)) + if GlobalData.gUseHashCache and not GlobalData.gBinCacheDest and self.Target in [None, "", "all"]: + if Ma.CanSkipbyPreMakeCache(): continue + else: + self.PreMakeCacheMiss.add(Ma) # Not to auto-gen for targets 'clean', 'cleanlib', 'cleanall', 'run', 'fds' if self.Target not in ['clean', 'cleanlib', 'cleanall', 'run', 'fds']: @@ -1929,19 +1902,12 @@ def _BuildModule(self): return True if GlobalData.gBinCacheSource and self.Target in [None, "", "all"]: - Ma.GenMakeHeaderFilesHash(GlobalData.gCacheIR) - Ma.GenMakeHash(GlobalData.gCacheIR) - if Ma.CanSkipbyMakeCache(GlobalData.gCacheIR): - self.HashSkipModules.append(Ma) - EdkLogger.quiet("cache hit: %s[%s]" % (Ma.MetaFile.Path, Ma.Arch)) + if Ma.CanSkipbyMakeCache(): continue else: - EdkLogger.quiet("cache miss: %s[%s]" % (Ma.MetaFile.Path, Ma.Arch)) - Ma.PrintFirstMakeCacheMissFile(GlobalData.gCacheIR) + self.MakeCacheMiss.add(Ma) self.BuildModules.append(Ma) - # Initialize all modules in tracking to 'FAIL' - GlobalData.gModuleBuildTracking[Ma] = 'FAIL' self.AutoGenTime += int(round((time.time() - AutoGenStart))) MakeStart = time.time() for Ma in self.BuildModules: @@ -1952,7 +1918,6 @@ def _BuildModule(self): # we need a full version of makefile for platform ExitFlag.set() BuildTask.WaitForComplete() - self.invalidateHash() Pa.CreateMakeFile(False) EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Start task scheduler @@ -1962,7 +1927,6 @@ def _BuildModule(self): # in case there's an interruption. we need a full version of makefile for platform Pa.CreateMakeFile(False) if BuildTask.HasError(): - self.invalidateHash() EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.MakeTime += int(round((time.time() - MakeStart))) @@ -1971,11 +1935,14 @@ def _BuildModule(self): BuildTask.WaitForComplete() self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: - self.UpdateBuildCache() + self.GenDestCache() + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + # Only for --hash + # Update PreMakeCacheChain files + self.GenLocalPreMakeCache() self.BuildModules = [] self.MakeTime += int(round((time.time() - MakeContiue))) if BuildTask.HasError(): - self.invalidateHash() EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.BuildReport.AddPlatformReport(Wa, MaList) @@ -2028,7 +1995,6 @@ def _BuildModule(self): # Save MAP buffer into MAP file. # self._SaveMapFile (MapBuffer, Wa) - self.invalidateHash() def _GenFfsCmd(self,ArchList): # convert dictionary of Cmd:(Inf,Arch) @@ -2134,20 +2100,13 @@ def PerformAutoGen(self,BuildTarget,ToolChain): self.BuildReport.AddPlatformReport(Wa) Wa.CreateMakeFile(False) - # Add ffs build to makefile + # Add ffs build to makefile CmdListDict = {} if GlobalData.gEnableGenfdsMultiThread and self.Fdf: CmdListDict = self._GenFfsCmd(Wa.ArchList) - # Add Platform and Package level hash in share_data for module hash calculation later - if GlobalData.gBinCacheSource or GlobalData.gBinCacheDest: - GlobalData.gCacheIR[('PlatformHash')] = GlobalData.gPlatformHash - for PkgName in GlobalData.gPackageHash.keys(): - GlobalData.gCacheIR[(PkgName, 'PackageHash')] = GlobalData.gPackageHash[PkgName] - self.AutoGenTime += int(round((time.time() - WorkspaceAutoGenTime))) BuildModules = [] - TotalModules = [] for Arch in Wa.ArchList: PcdMaList = [] AutoGenStart = time.time() @@ -2158,7 +2117,7 @@ def PerformAutoGen(self,BuildTarget,ToolChain): ModuleList = [] for Inf in Pa.Platform.Modules: ModuleList.append(Inf) - # Add the INF only list in FDF + # Add the INF only list in FDF if GlobalData.gFdfParser is not None: for InfName in GlobalData.gFdfParser.Profile.InfList: Inf = PathClass(NormPath(InfName), self.WorkspaceDir, Arch) @@ -2172,58 +2131,73 @@ def PerformAutoGen(self,BuildTarget,ToolChain): Pa.DataPipe.DataContainer = {"LibraryBuildDirectoryList":Pa.LibraryBuildDirectoryList} Pa.DataPipe.DataContainer = {"ModuleBuildDirectoryList":Pa.ModuleBuildDirectoryList} Pa.DataPipe.DataContainer = {"FdsCommandDict": Wa.GenFdsCommandDict} + # Prepare the cache share data for multiprocessing + Pa.DataPipe.DataContainer = {"gPlatformHashFile":GlobalData.gPlatformHashFile} ModuleCodaFile = {} for ma in Pa.ModuleAutoGenList: ModuleCodaFile[(ma.MetaFile.File,ma.MetaFile.Root,ma.Arch,ma.MetaFile.Path)] = [item.Target for item in ma.CodaTargetList] Pa.DataPipe.DataContainer = {"ModuleCodaFile":ModuleCodaFile} + # ModuleList contains all driver modules only for Module in ModuleList: - # Get ModuleAutoGen object to generate C code file and makefile + # Get ModuleAutoGen object to generate C code file and makefile Ma = ModuleAutoGen(Wa, Module, BuildTarget, ToolChain, Arch, self.PlatformFile,Pa.DataPipe) - if Ma is None: continue if Ma.PcdIsDriver: Ma.PlatformInfo = Pa Ma.Workspace = Wa PcdMaList.append(Ma) - TotalModules.append(Ma) - # Initialize all modules in tracking to 'FAIL' - GlobalData.gModuleBuildTracking[Ma] = 'FAIL' - + self.AllDrivers.add(Ma) + self.AllModules.add(Ma) mqueue = mp.Queue() + cqueue = mp.Queue() for m in Pa.GetAllModuleInfo: mqueue.put(m) + module_file,module_root,module_path,module_basename,\ + module_originalpath,module_arch,IsLib = m + Ma = ModuleAutoGen(Wa, PathClass(module_path, Wa), BuildTarget,\ + ToolChain, Arch, self.PlatformFile,Pa.DataPipe) + self.AllModules.add(Ma) data_pipe_file = os.path.join(Pa.BuildDir, "GlobalVar_%s_%s.bin" % (str(Pa.Guid),Pa.Arch)) Pa.DataPipe.dump(data_pipe_file) - autogen_rt, errorcode = self.StartAutoGen(mqueue, Pa.DataPipe, self.SkipAutoGen, PcdMaList,GlobalData.gCacheIR) - - # Skip cache hit modules - if GlobalData.gBinCacheSource: - for Ma in TotalModules: - if (Ma.MetaFile.Path, Ma.Arch) in GlobalData.gCacheIR and \ - GlobalData.gCacheIR[(Ma.MetaFile.Path, Ma.Arch)].PreMakeCacheHit: - self.HashSkipModules.append(Ma) - continue - if (Ma.MetaFile.Path, Ma.Arch) in GlobalData.gCacheIR and \ - GlobalData.gCacheIR[(Ma.MetaFile.Path, Ma.Arch)].MakeCacheHit: - self.HashSkipModules.append(Ma) - continue - BuildModules.append(Ma) - else: - BuildModules.extend(TotalModules) + autogen_rt, errorcode = self.StartAutoGen(mqueue, Pa.DataPipe, self.SkipAutoGen, PcdMaList, cqueue) if not autogen_rt: self.AutoGenMgr.TerminateWorkers() self.AutoGenMgr.join(1) raise FatalError(errorcode) + + if GlobalData.gUseHashCache: + for item in GlobalData.gModuleAllCacheStatus: + (MetaFilePath, Arch, CacheStr, Status) = item + Ma = ModuleAutoGen(Wa, PathClass(MetaFilePath, Wa), BuildTarget,\ + ToolChain, Arch, self.PlatformFile,Pa.DataPipe) + if CacheStr == "PreMakeCache" and Status == False: + self.PreMakeCacheMiss.add(Ma) + if CacheStr == "PreMakeCache" and Status == True: + self.PreMakeCacheHit.add(Ma) + GlobalData.gModuleCacheHit.add(Ma) + if CacheStr == "MakeCache" and Status == False: + self.MakeCacheMiss.add(Ma) + if CacheStr == "MakeCache" and Status == True: + self.MakeCacheHit.add(Ma) + GlobalData.gModuleCacheHit.add(Ma) self.AutoGenTime += int(round((time.time() - AutoGenStart))) AutoGenIdFile = os.path.join(GlobalData.gConfDirectory,".AutoGenIdFile.txt") with open(AutoGenIdFile,"w") as fw: fw.write("Arch=%s\n" % "|".join((Wa.ArchList))) fw.write("BuildDir=%s\n" % Wa.BuildDir) fw.write("PlatformGuid=%s\n" % str(Wa.AutoGenObjectList[0].Guid)) + + if GlobalData.gBinCacheSource: + BuildModules.extend(self.MakeCacheMiss) + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheDest: + BuildModules.extend(self.PreMakeCacheMiss) + else: + BuildModules.extend(self.AllDrivers) + self.Progress.Stop("done!") return Wa, BuildModules @@ -2253,18 +2227,9 @@ def _MultiThreadBuildPlatform(self): GlobalData.gAutoGenPhase = False if GlobalData.gBinCacheSource: - EdkLogger.quiet("Total cache hit driver num: %s, cache miss driver num: %s" % (len(set(self.HashSkipModules)), len(set(self.BuildModules)))) - CacheHitMa = set() - CacheNotHitMa = set() - for IR in GlobalData.gCacheIR.keys(): - if 'PlatformHash' in IR or 'PackageHash' in IR: - continue - if GlobalData.gCacheIR[IR].PreMakeCacheHit or GlobalData.gCacheIR[IR].MakeCacheHit: - CacheHitMa.add(IR) - else: - # There might be binary module or module which has .inc files, not count for cache miss - CacheNotHitMa.add(IR) - EdkLogger.quiet("Total module num: %s, cache hit module num: %s" % (len(CacheHitMa)+len(CacheNotHitMa), len(CacheHitMa))) + EdkLogger.quiet("[cache Summary]: Total module num: %s" % len(self.AllModules)) + EdkLogger.quiet("[cache Summary]: PreMakecache miss num: %s " % len(self.PreMakeCacheMiss)) + EdkLogger.quiet("[cache Summary]: Makecache miss num: %s " % len(self.MakeCacheMiss)) for Arch in Wa.ArchList: MakeStart = time.time() @@ -2277,7 +2242,6 @@ def _MultiThreadBuildPlatform(self): # we need a full version of makefile for platform ExitFlag.set() BuildTask.WaitForComplete() - self.invalidateHash() Pa.CreateMakeFile(False) EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Start task scheduler @@ -2287,7 +2251,6 @@ def _MultiThreadBuildPlatform(self): # in case there's an interruption. we need a full version of makefile for platform if BuildTask.HasError(): - self.invalidateHash() EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) self.MakeTime += int(round((time.time() - MakeStart))) @@ -2301,7 +2264,11 @@ def _MultiThreadBuildPlatform(self): BuildTask.WaitForComplete() self.CreateAsBuiltInf() if GlobalData.gBinCacheDest: - self.UpdateBuildCache() + self.GenDestCache() + elif GlobalData.gUseHashCache and not GlobalData.gBinCacheSource: + # Only for --hash + # Update PreMakeCacheChain files + self.GenLocalPreMakeCache() # # Get Module List # @@ -2313,7 +2280,6 @@ def _MultiThreadBuildPlatform(self): # has been signaled. # if BuildTask.HasError(): - self.invalidateHash() EdkLogger.error("build", BUILD_ERROR, "Failed to build module", ExtraData=GlobalData.gBuildingModule) # Create MAP file when Load Fix Address is enabled. @@ -2350,7 +2316,6 @@ def _MultiThreadBuildPlatform(self): # self._SaveMapFile(MapBuffer, Wa) self.CreateGuidedSectionToolsFile(Wa) - self.invalidateHash() ## Generate GuidedSectionTools.txt in the FV directories. # def CreateGuidedSectionToolsFile(self,Wa): @@ -2406,6 +2371,12 @@ def GetFullPathOfTool (self, tool): ## Launch the module or platform build # def Launch(self): + self.AllDrivers = set() + self.AllModules = set() + self.PreMakeCacheMiss = set() + self.PreMakeCacheHit = set() + self.MakeCacheMiss = set() + self.MakeCacheHit = set() if not self.ModuleFile: if not self.SpawnMode or self.Target not in ["", "all"]: self.SpawnMode = False @@ -2423,23 +2394,16 @@ def CreateAsBuiltInf(self): for Module in self.BuildModules: Module.CreateAsBuiltInf() - def UpdateBuildCache(self): - all_lib_set = set() - all_mod_set = set() - for Module in self.BuildModules: + def GenDestCache(self): + for Module in self.AllModules: + Module.GenPreMakefileHashList() + Module.GenMakefileHashList() Module.CopyModuleToCache() - all_mod_set.add(Module) - for Module in self.HashSkipModules: - Module.CopyModuleToCache() - all_mod_set.add(Module) - for Module in all_mod_set: - for lib in Module.LibraryAutoGenList: - all_lib_set.add(lib) - for lib in all_lib_set: - lib.CopyModuleToCache() - all_lib_set.clear() - all_mod_set.clear() - self.HashSkipModules = [] + + def GenLocalPreMakeCache(self): + for Module in self.PreMakeCacheMiss: + Module.GenPreMakefileHashList() + ## Do some clean-up works when error occurred def Relinquish(self): OldLogLevel = EdkLogger.GetLevel() From a80032dc44a1071a34f4415a7c5cef5170ee6159 Mon Sep 17 00:00:00 2001 From: Steven Shi Date: Tue, 19 Nov 2019 16:22:08 +0800 Subject: [PATCH 173/384] BaseTools: Remove redundant binary cache file Redesign the binary cache and not need to save the cache intermediate result and state in memory as a ModuleBuildCacheIR class instance. So remove the CacheIR.py which define the ModuleBuildCacheIR class. Signed-off-by: Steven Shi Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- BaseTools/Source/Python/AutoGen/CacheIR.py | 29 ---------------------- 1 file changed, 29 deletions(-) delete mode 100755 BaseTools/Source/Python/AutoGen/CacheIR.py diff --git a/BaseTools/Source/Python/AutoGen/CacheIR.py b/BaseTools/Source/Python/AutoGen/CacheIR.py deleted file mode 100755 index 715be5273c1..00000000000 --- a/BaseTools/Source/Python/AutoGen/CacheIR.py +++ /dev/null @@ -1,29 +0,0 @@ -## @file -# Build cache intermediate result and state -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# - -class ModuleBuildCacheIR(): - def __init__(self, Path, Arch): - self.ModulePath = Path - self.ModuleArch = Arch - self.ModuleFilesHashDigest = None - self.ModuleFilesHashHexDigest = None - self.ModuleFilesChain = [] - self.PreMakefileHashHexDigest = None - self.CreateCodeFileDone = False - self.CreateMakeFileDone = False - self.MakefilePath = None - self.AutoGenFileList = None - self.DependencyHeaderFileSet = None - self.MakeHeaderFilesHashChain = None - self.MakeHeaderFilesHashDigest = None - self.MakeHeaderFilesHashChain = [] - self.MakeHashDigest = None - self.MakeHashHexDigest = None - self.MakeHashChain = [] - self.CacheCrash = False - self.PreMakeCacheHit = False - self.MakeCacheHit = False From 7e55cf6b48dcd43de46d008b2f12caaad2554503 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Sat, 7 Dec 2019 21:41:10 +0800 Subject: [PATCH 174/384] SecurityPkg/Tcg2Smm: Measure the table before patch. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=1940 According to TCG PFP specification: the ACPI table must be measured prior to any modification, and the measurement must be same cross every boot cycle. There is a fix 3a63c17ebc853cbb27d190729d01e27f68e65b94 for the HID data. However that is not enough. The LAML/LASA and PCD configuration change may also cause similar problem. We need measure the table before any update. Cc: Jian J Wang Cc: Chao Zhang Signed-off-by: Jiewen Yao Reviewed-by: Chao Zhang --- SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c | 57 ++++++++++++++++--------------- 1 file changed, 30 insertions(+), 27 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c index 54966c83ce8..91aebb62b8b 100644 --- a/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c +++ b/SecurityPkg/Tcg/Tcg2Smm/Tcg2Smm.c @@ -651,23 +651,11 @@ PublishAcpiTable ( ); ASSERT_EFI_ERROR (Status); - // - // Update Table version before measuring it to PCR - // - Status = UpdatePPVersion(Table, (CHAR8 *)PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer)); - ASSERT_EFI_ERROR (Status); - - DEBUG (( - DEBUG_INFO, - "Current physical presence interface version - %a\n", - (CHAR8 *) PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer) - )); - // // Measure to PCR[0] with event EV_POST_CODE ACPI DATA. - // The measurement has to be done before UpdateHID since TPM2 ACPI HID - // imply TPM Firmware Version. Otherwise, the PCR record would be - // different after TPM FW update. + // The measurement has to be done before any update. + // Otherwise, the PCR record would be different after TPM FW update + // or the PCD configuration change. // TpmMeasureAndLogData( 0, @@ -678,6 +666,18 @@ PublishAcpiTable ( TableSize ); + // + // Update Table version before measuring it to PCR + // + Status = UpdatePPVersion(Table, (CHAR8 *)PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer)); + ASSERT_EFI_ERROR (Status); + + DEBUG (( + DEBUG_INFO, + "Current physical presence interface version - %a\n", + (CHAR8 *) PcdGetPtr(PcdTcgPhysicalPresenceInterfaceVer) + )); + // // Update TPM2 HID after measuring it to PCR // @@ -753,6 +753,21 @@ PublishTpm2 ( EFI_TPM2_ACPI_CONTROL_AREA *ControlArea; TPM2_PTP_INTERFACE_TYPE InterfaceType; + // + // Measure to PCR[0] with event EV_POST_CODE ACPI DATA. + // The measurement has to be done before any update. + // Otherwise, the PCR record would be different after event log update + // or the PCD configuration change. + // + TpmMeasureAndLogData( + 0, + EV_POST_CODE, + EV_POSTCODE_INFO_ACPI_DATA, + ACPI_DATA_LEN, + &mTpm2AcpiTemplate, + mTpm2AcpiTemplate.Header.Length + ); + mTpm2AcpiTemplate.Header.Revision = PcdGet8(PcdTpm2AcpiTableRev); DEBUG((DEBUG_INFO, "Tpm2 ACPI table revision is %d\n", mTpm2AcpiTemplate.Header.Revision)); @@ -776,18 +791,6 @@ PublishTpm2 ( mTpm2AcpiTemplate.Header.Length = sizeof(EFI_TPM2_ACPI_TABLE); } - // - // Measure to PCR[0] with event EV_POST_CODE ACPI DATA - // - TpmMeasureAndLogData( - 0, - EV_POST_CODE, - EV_POSTCODE_INFO_ACPI_DATA, - ACPI_DATA_LEN, - &mTpm2AcpiTemplate, - mTpm2AcpiTemplate.Header.Length - ); - InterfaceType = PcdGet8(PcdActiveTpmInterfaceType); switch (InterfaceType) { case Tpm2PtpInterfaceCrb: From 97eedf5dfbaffde33210fd88066247cf0b7d3325 Mon Sep 17 00:00:00 2001 From: Antoine Coeur Date: Wed, 4 Dec 2019 12:14:53 +0800 Subject: [PATCH 175/384] IntelFsp2WrapperPkg: Fix various typos Fix various typos in comments and documentation. Cc: Chasel Chiu Cc: Nate DeSimone Cc: Star Zeng Reviewed-by: Philippe Mathieu-Daude Signed-off-by: Philippe Mathieu-Daude Reviewed-by: Nate DeSimone Reviewed-by: Chasel Chiu Reviewed-by: Star Zeng --- IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c | 2 +- IntelFsp2WrapperPkg/Include/Library/FspWrapperApiLib.h | 2 +- IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformLib.h | 4 ++-- .../Library/BaseFspWrapperApiLib/X64/Thunk64To32.nasm | 6 +++--- .../FspWrapperPlatformLibSample.c | 4 ++-- .../FspWrapperHobProcessLibSample.c | 4 ++-- .../SecFspWrapperPlatformSecLibSample/Ia32/SecEntry.nasm | 2 +- .../SecFspWrapperPlatformSecLibSample/Ia32/Stack.nasm | 2 +- 8 files changed, 13 insertions(+), 13 deletions(-) diff --git a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c index 0f8cd69a0e6..b20f0805a02 100644 --- a/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c +++ b/IntelFsp2WrapperPkg/FspsWrapperPeim/FspsWrapperPeim.c @@ -352,7 +352,7 @@ FspsWrapperInitApiMode ( EFI_BOOT_MODE BootMode; // - // Register MemoryDiscovered Nofity to run FspSiliconInit + // Register MemoryDiscovered Notify to run FspSiliconInit // Status = PeiServicesNotifyPpi (&mPeiMemoryDiscoveredNotifyDesc); ASSERT_EFI_ERROR (Status); diff --git a/IntelFsp2WrapperPkg/Include/Library/FspWrapperApiLib.h b/IntelFsp2WrapperPkg/Include/Library/FspWrapperApiLib.h index e39054c30d3..11a3faaad87 100644 --- a/IntelFsp2WrapperPkg/Include/Library/FspWrapperApiLib.h +++ b/IntelFsp2WrapperPkg/Include/Library/FspWrapperApiLib.h @@ -40,7 +40,7 @@ CallFspNotifyPhase ( /** Call FSP API - FspMemoryInit. - @param[in] FspmUpdDataPtr Pointer to the FSPM_UPD data sructure. + @param[in] FspmUpdDataPtr Pointer to the FSPM_UPD data structure. @param[out] HobListPtr Pointer to receive the address of the HOB list. @return EFI status returned by FspMemoryInit API. diff --git a/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformLib.h b/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformLib.h index b90f0eb7830..2aa14c92fd6 100644 --- a/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformLib.h +++ b/IntelFsp2WrapperPkg/Include/Library/FspWrapperPlatformLib.h @@ -12,7 +12,7 @@ /** This function overrides the default configurations in the FSP-M UPD data region. - @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data strcture. + @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data structure. **/ VOID @@ -24,7 +24,7 @@ UpdateFspmUpdData ( /** This function overrides the default configurations in the FSP-S UPD data region. - @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data strcture. + @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data structure. **/ VOID diff --git a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/X64/Thunk64To32.nasm b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/X64/Thunk64To32.nasm index 45c8f21255e..db8e62ebc5a 100644 --- a/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/X64/Thunk64To32.nasm +++ b/IntelFsp2WrapperPkg/Library/BaseFspWrapperApiLib/X64/Thunk64To32.nasm @@ -43,7 +43,7 @@ ASM_PFX(AsmExecute32BitCode): cli ; - ; save orignal GDTR and CS + ; save original GDTR and CS ; mov rax, ds push rax @@ -190,7 +190,7 @@ ReloadCS: pop rdi popfq ; - ; Switch to orignal GDT and CS. here rsp is pointer to the orignal GDT descriptor. + ; Switch to original GDT and CS. here rsp is pointer to the original GDT descriptor. ; lgdt [rsp] ; @@ -198,7 +198,7 @@ ReloadCS: ; add rsp, 0x10 ; - ; switch to orignal CS and GDTR + ; switch to original CS and GDTR ; pop r9 ; get CS shl r9, 32 ; rcx[32..47] <- Cs diff --git a/IntelFsp2WrapperPkg/Library/BaseFspWrapperPlatformLibSample/FspWrapperPlatformLibSample.c b/IntelFsp2WrapperPkg/Library/BaseFspWrapperPlatformLibSample/FspWrapperPlatformLibSample.c index def04b17665..dddf80b76c2 100644 --- a/IntelFsp2WrapperPkg/Library/BaseFspWrapperPlatformLibSample/FspWrapperPlatformLibSample.c +++ b/IntelFsp2WrapperPkg/Library/BaseFspWrapperPlatformLibSample/FspWrapperPlatformLibSample.c @@ -14,7 +14,7 @@ @note At this point, memory is NOT ready, PeiServices are available to use. - @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data strcture. + @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data structure. **/ VOID @@ -28,7 +28,7 @@ UpdateFspmUpdData ( /** This function overrides the default configurations in the FSP-S UPD data region. - @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data strcture. + @param[in,out] FspUpdRgnPtr A pointer to the UPD data region data structure. **/ VOID diff --git a/IntelFsp2WrapperPkg/Library/PeiFspWrapperHobProcessLibSample/FspWrapperHobProcessLibSample.c b/IntelFsp2WrapperPkg/Library/PeiFspWrapperHobProcessLibSample/FspWrapperHobProcessLibSample.c index 54cebe127c8..48f4b0295a3 100644 --- a/IntelFsp2WrapperPkg/Library/PeiFspWrapperHobProcessLibSample/FspWrapperHobProcessLibSample.c +++ b/IntelFsp2WrapperPkg/Library/PeiFspWrapperHobProcessLibSample/FspWrapperHobProcessLibSample.c @@ -29,11 +29,11 @@ #define PEI_ADDITIONAL_MEMORY_SIZE (16 * EFI_PAGE_SIZE) /** - Get the mem size in memory type infromation table. + Get the mem size in memory type information table. @param[in] PeiServices PEI Services table. - @return the mem size in memory type infromation table. + @return the mem size in memory type information table. **/ UINT64 GetMemorySizeInMemoryTypeInformation ( diff --git a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/SecEntry.nasm b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/SecEntry.nasm index d8d0582cb4f..9f190bb25b0 100644 --- a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/SecEntry.nasm +++ b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/SecEntry.nasm @@ -207,7 +207,7 @@ TempRamInitDone: cmp eax, 8000000Eh ;Check if EFI_NOT_FOUND returned. Error code for Microcode Update not found. je CallSecFspInit ;If microcode not found, don't hang, but continue. - cmp eax, 0 ;Check if EFI_SUCCESS retuned. + cmp eax, 0 ;Check if EFI_SUCCESS returned. jnz FspApiFailed ; ECX: start of range diff --git a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/Stack.nasm b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/Stack.nasm index ba989bd4412..d7394cf286c 100644 --- a/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/Stack.nasm +++ b/IntelFsp2WrapperPkg/Library/SecFspWrapperPlatformSecLibSample/Ia32/Stack.nasm @@ -5,7 +5,7 @@ ; ; Abstract: ; -; Switch the stack from temporary memory to permenent memory. +; Switch the stack from temporary memory to permanent memory. ; ;------------------------------------------------------------------------------ From d39d1260c615b716675f67f5c4e1f4f52df01dad Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 20 Nov 2019 17:10:48 -0800 Subject: [PATCH 176/384] MdeModulePkg PeiCore: Fix typos Cc: Dandan Bi Cc: Liming Gao Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Jian J Wang --- MdeModulePkg/Core/Pei/Dependency/Dependency.c | 8 +-- MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c | 48 +++++++++--------- MdeModulePkg/Core/Pei/FwVol/FwVol.c | 50 +++++++++---------- MdeModulePkg/Core/Pei/FwVol/FwVol.h | 20 ++++---- MdeModulePkg/Core/Pei/Hob/Hob.c | 4 +- MdeModulePkg/Core/Pei/Image/Image.c | 10 ++-- MdeModulePkg/Core/Pei/Memory/MemoryServices.c | 16 +++--- MdeModulePkg/Core/Pei/PeiMain.h | 40 +++++++-------- MdeModulePkg/Core/Pei/PeiMain.inf | 10 ++-- MdeModulePkg/Core/Pei/PeiMain/PeiMain.c | 2 +- MdeModulePkg/Core/Pei/Ppi/Ppi.c | 4 +- MdeModulePkg/Core/Pei/Security/Security.c | 12 ++--- 12 files changed, 112 insertions(+), 112 deletions(-) diff --git a/MdeModulePkg/Core/Pei/Dependency/Dependency.c b/MdeModulePkg/Core/Pei/Dependency/Dependency.c index 6ce610a0283..9a8353aef20 100644 --- a/MdeModulePkg/Core/Pei/Dependency/Dependency.c +++ b/MdeModulePkg/Core/Pei/Dependency/Dependency.c @@ -5,7 +5,7 @@ if a driver can be scheduled for execution. The criteria for schedulability is that the dependency expression is satisfied. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -45,7 +45,7 @@ IsPpiInstalled ( } // - // Copy the Guid into a locale variable so that there are no + // Copy the GUID into a local variable so that there are no // possibilities of alignment faults for cross-compilation // environments such as Intel?Itanium(TM). // @@ -72,7 +72,7 @@ IsPpiInstalled ( This is the POSTFIX version of the dependency evaluator. When a PUSH [PPI GUID] is encountered, a pointer to the GUID is stored on - the evaluation stack. When that entry is poped from the evaluation + the evaluation stack. When that entry is popped from the evaluation stack, the PPI is checked if it is installed. This method allows some time savings as not all PPIs must be checked for certain operation types (AND, OR). @@ -123,7 +123,7 @@ PeimDispatchReadiness ( // // Push the pointer to the PUSH opcode operator (pointer to PPI GUID) - // We will evaluate if the PPI is insalled on the POP operation. + // We will evaluate if the PPI is installed on the POP operation. // StackPtr->Operator = (VOID *) Iterator; Iterator = Iterator + sizeof (EFI_GUID); diff --git a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c index ba2fd0cae14..c9f2a912643 100644 --- a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c @@ -1,7 +1,7 @@ /** @file EFI PEI Core dispatch services -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2016 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -11,7 +11,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /** - Discover all Peims and optional Apriori file in one FV. There is at most one + Discover all PEIMs and optional Apriori file in one FV. There is at most one Apriori file in one FV. @@ -49,7 +49,7 @@ DiscoverPeimsAndOrderWithApriori ( Guid = NULL; // - // If the current Fv has been scanned, directly get its cached records. + // If the current FV has been scanned, directly get its cached records. // if (CoreFileHandle->ScanFv) { Private->CurrentFvFileHandles = CoreFileHandle->FvFileHandles; @@ -60,7 +60,7 @@ DiscoverPeimsAndOrderWithApriori ( TempFileGuid = Private->TempFileGuid; // - // Go ahead to scan this Fv, get PeimCount and cache FileHandles within it to TempFileHandles. + // Go ahead to scan this FV, get PeimCount and cache FileHandles within it to TempFileHandles. // PeimCount = 0; FileHandle = NULL; @@ -147,7 +147,7 @@ DiscoverPeimsAndOrderWithApriori ( for (Index = 0; Index < PeimCount; Index++) { // - // Make an array of file name guids that matches the FileHandle array so we can convert + // Make an array of file name GUIDs that matches the FileHandle array so we can convert // quickly from file name to file handle // Status = FvPpi->GetFileInfo (FvPpi, TempFileHandles[Index], &FileInfo); @@ -156,7 +156,7 @@ DiscoverPeimsAndOrderWithApriori ( } // - // Walk through TempFileGuid array to find out who is invalid PEIM guid in Apriori file. + // Walk through TempFileGuid array to find out who is invalid PEIM GUID in Apriori file. // Add available PEIMs in Apriori file into FvFileHandles array. // Index = 0; @@ -194,8 +194,8 @@ DiscoverPeimsAndOrderWithApriori ( } // - // The current Fv File Handles have been cached. So that we don't have to scan the Fv again. - // Instead, we can retrieve the file handles within this Fv from cached records. + // The current FV File Handles have been cached. So that we don't have to scan the FV again. + // Instead, we can retrieve the file handles within this FV from cached records. // CoreFileHandle->ScanFv = TRUE; Private->CurrentFvFileHandles = CoreFileHandle->FvFileHandles; @@ -307,7 +307,7 @@ PeiLoadFixAddressHook( DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED INFO: PcdLoadFixAddressPeiCodePageNumber= 0x%x.\n", PcdGet32(PcdLoadFixAddressPeiCodePageNumber))); DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED INFO: Total Reserved Memory Size = 0x%lx.\n", TotalReservedMemorySize)); // - // Loop through the system memory typed hob to merge the adjacent memory range + // Loop through the system memory typed HOB to merge the adjacent memory range // for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { // @@ -317,7 +317,7 @@ PeiLoadFixAddressHook( ResourceHob = Hob.ResourceDescriptor; // - // If range described in this hob is not system memory or heigher than MAX_ADDRESS, ignored. + // If range described in this HOB is not system memory or higher than MAX_ADDRESS, ignored. // if (ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY || ResourceHob->PhysicalStart + ResourceHob->ResourceLength > MAX_ADDRESS) { @@ -387,18 +387,18 @@ PeiLoadFixAddressHook( if (GET_HOB_TYPE (NextHob) == EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) { NextResourceHob = NextHob.ResourceDescriptor; // - // If range described in this hob is not system memory or heigher than MAX_ADDRESS, ignored. + // If range described in this HOB is not system memory or higher than MAX_ADDRESS, ignored. // if (NextResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY || NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength > MAX_ADDRESS) { continue; } // - // If the range describe in memory allocation HOB belongs to the memroy range described by the resource hob + // If the range describe in memory allocation HOB belongs to the memory range described by the resource HOB // if (MemoryHob->AllocDescriptor.MemoryBaseAddress >= NextResourceHob->PhysicalStart && MemoryHob->AllocDescriptor.MemoryBaseAddress + MemoryHob->AllocDescriptor.MemoryLength <= NextResourceHob->PhysicalStart + NextResourceHob->ResourceLength) { // - // Build seperate resource hob for this allocated range + // Build separate resource HOB for this allocated range // if (MemoryHob->AllocDescriptor.MemoryBaseAddress > NextResourceHob->PhysicalStart) { BuildResourceDescriptorHob ( @@ -452,7 +452,7 @@ PeiLoadFixAddressHook( ResourceHob = Hob.ResourceDescriptor; // - // See if this resource descrior HOB describes tested system memory below MAX_ADDRESS + // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS) { @@ -476,7 +476,7 @@ PeiLoadFixAddressHook( DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED ERROR:Top Address 0x%lx is invalid \n", TopLoadingAddress)); DEBUG ((EFI_D_INFO, "LOADING MODULE FIXED ERROR:The recommended Top Address for the platform is: \n")); // - // Print the recomended Top address range. + // Print the recommended Top address range. // for (Hob.Raw = PrivateData->HobList.Raw; !END_OF_HOB_LIST(Hob); Hob.Raw = GET_NEXT_HOB(Hob)) { // @@ -486,7 +486,7 @@ PeiLoadFixAddressHook( ResourceHob = Hob.ResourceDescriptor; // - // See if this resource descrior HOB describes tested system memory below MAX_ADDRESS + // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS) { @@ -524,7 +524,7 @@ PeiLoadFixAddressHook( ResourceHob = Hob.ResourceDescriptor; // - // See if this resource descrior HOB describes tested system memory below MAX_ADDRESS + // See if this resource descriptor HOB describes tested system memory below MAX_ADDRESS // if (ResourceHob->ResourceType == EFI_RESOURCE_SYSTEM_MEMORY && ResourceHob->PhysicalStart + ResourceHob->ResourceLength <= MAX_ADDRESS && @@ -554,7 +554,7 @@ PeiLoadFixAddressHook( if (CurrentResourceHob != NULL) { // - // rebuild resource HOB for PEI memmory and reserved memory + // rebuild resource HOB for PEI memory and reserved memory // BuildResourceDescriptorHob ( EFI_RESOURCE_SYSTEM_MEMORY, @@ -750,7 +750,7 @@ PeiCheckAndSwitchStack ( ASSERT (NewStackSize >= SecCoreData->StackSize); // - // Calculate stack offset and heap offset between temporary memory and new permement + // Calculate stack offset and heap offset between temporary memory and new permanent // memory seperately. // TopOfOldStack = (UINTN)SecCoreData->StackBase + SecCoreData->StackSize; @@ -1042,10 +1042,10 @@ PeiDispatcher ( // // This is the main dispatch loop. It will search known FVs for PEIMs and // attempt to dispatch them. If any PEIM gets dispatched through a single - // pass of the dispatcher, it will start over from the Bfv again to see + // pass of the dispatcher, it will start over from the BFV again to see // if any new PEIMs dependencies got satisfied. With a well ordered // FV where PEIMs are found in the order their dependencies are also - // satisfied, this dipatcher should run only once. + // satisfied, this dispatcher should run only once. // do { // @@ -1081,7 +1081,7 @@ PeiDispatcher ( } // - // Start to dispatch all modules within the current Fv. + // Start to dispatch all modules within the current FV. // for (PeimCount = Private->CurrentPeimCount; PeimCount < Private->Fv[FvCount].PeimCount; @@ -1097,7 +1097,7 @@ PeiDispatcher ( ASSERT_EFI_ERROR (Status); if (FvFileInfo.FileType == EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE) { // - // For Fv type file, Produce new FvInfo PPI and FV hob + // For FV type file, Produce new FvInfo PPI and FV HOB // Status = ProcessFvFile (Private, &Private->Fv[FvCount], PeimFileHandle); if (Status == EFI_SUCCESS) { @@ -1317,7 +1317,7 @@ DepexSatisfied ( if (PeimCount < Private->AprioriCount) { // - // If it's in the Apriori file then we set Depex to TRUE + // If it's in the Apriori file then we set DEPEX to TRUE // DEBUG ((DEBUG_DISPATCH, " RESULT = TRUE (Apriori)\n")); return TRUE; diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.c b/MdeModulePkg/Core/Pei/FwVol/FwVol.c index f4642c47c13..c21eb9c0396 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.c +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.c @@ -13,12 +13,12 @@ EFI_PEI_NOTIFY_DESCRIPTOR mNotifyOnFvInfoList[] = { { EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK, &gEfiPeiFirmwareVolumeInfoPpiGuid, - FirmwareVolmeInfoPpiNotifyCallback + FirmwareVolumeInfoPpiNotifyCallback }, { (EFI_PEI_PPI_DESCRIPTOR_NOTIFY_CALLBACK | EFI_PEI_PPI_DESCRIPTOR_TERMINATE_LIST), &gEfiPeiFirmwareVolumeInfo2PpiGuid, - FirmwareVolmeInfoPpiNotifyCallback + FirmwareVolumeInfoPpiNotifyCallback } }; @@ -447,7 +447,7 @@ FindFileEx ( } /** - Initialize PeiCore Fv List. + Initialize PeiCore FV List. @param PrivateData - Pointer to PEI_CORE_INSTANCE. @param SecCoreData - Pointer to EFI_SEC_PEI_HAND_OFF. @@ -520,7 +520,7 @@ PeiInitializeFv ( // // Post a call-back for the FvInfoPPI and FvInfo2PPI services to expose - // additional Fvs to PeiCore. + // additional FVs to PeiCore. // Status = PeiServicesNotifyPpi (mNotifyOnFvInfoList); ASSERT_EFI_ERROR (Status); @@ -528,7 +528,7 @@ PeiInitializeFv ( } /** - Process Firmware Volum Information once FvInfoPPI or FvInfo2PPI install. + Process Firmware Volume Information once FvInfoPPI or FvInfo2PPI install. The FV Info will be registered into PeiCore private data structure. And search the inside FV image, if found, the new FV INFO(2) PPI will be installed. @@ -537,12 +537,12 @@ PeiInitializeFv ( @param Ppi Address of the PPI that was installed. @retval EFI_SUCCESS The FV Info is registered into PeiCore private data structure. - @return if not EFI_SUCESS, fail to verify FV. + @return if not EFI_SUCCESS, fail to verify FV. **/ EFI_STATUS EFIAPI -FirmwareVolmeInfoPpiNotifyCallback ( +FirmwareVolumeInfoPpiNotifyCallback ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi @@ -593,7 +593,7 @@ FirmwareVolmeInfoPpiNotifyCallback ( } // - // Locate the corresponding FV_PPI according to founded FV's format guid + // Locate the corresponding FV_PPI according to founded FV's format GUID // Status = PeiServicesLocatePpi ( &FvInfo2Ppi.FvFormat, @@ -620,7 +620,7 @@ FirmwareVolmeInfoPpiNotifyCallback ( PrivateData->Fv[FvIndex].AuthenticationStatus = FvInfo2Ppi.AuthenticationStatus; DEBUG ((EFI_D_INFO, "Update AuthenticationStatus of the %dth FV to 0x%x!\n", FvIndex, FvInfo2Ppi.AuthenticationStatus)); } - DEBUG ((EFI_D_INFO, "The Fv %p has already been processed!\n", FvInfo2Ppi.FvInfo)); + DEBUG ((DEBUG_INFO, "The FV %p has already been processed!\n", FvInfo2Ppi.FvInfo)); return EFI_SUCCESS; } } @@ -661,7 +661,7 @@ FirmwareVolmeInfoPpiNotifyCallback ( PrivateData->FvCount ++; // - // Scan and process the new discoveried FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE + // Scan and process the new discovered FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE // FileHandle = NULL; do { @@ -1359,11 +1359,11 @@ GetFvUsedSize ( } /** - Get Fv image(s) from the FV type file, then install FV INFO(2) ppi, Build FV(2, 3) hob. + Get FV image(s) from the FV type file, then install FV INFO(2) PPI, Build FV(2, 3) HOB. @param PrivateData PeiCore's private data structure - @param ParentFvCoreHandle Pointer of EFI_CORE_FV_HANDLE to parent Fv image that contain this Fv image. - @param ParentFvFileHandle File handle of a Fv type file that contain this Fv image. + @param ParentFvCoreHandle Pointer of EFI_CORE_FV_HANDLE to parent FV image that contain this FV image. + @param ParentFvFileHandle File handle of a FV type file that contain this FV image. @retval EFI_NOT_FOUND FV image can't be found. @retval EFI_SUCCESS Successfully to process it. @@ -1533,7 +1533,7 @@ ProcessFvFile ( ); // - // Inform the extracted FvImage to Fv HOB consumer phase, i.e. DXE phase + // Inform the extracted FvImage to FV HOB consumer phase, i.e. DXE phase // BuildFvHob ( (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, @@ -1619,7 +1619,7 @@ PeiFfsFvPpiProcessVolume ( // // The build-in EFI_PEI_FIRMWARE_VOLUME_PPI for FFS2/FFS3 support memory-mapped - // FV image and the handle is pointed to Fv image's buffer. + // FV image and the handle is pointed to FV image's buffer. // *FvHandle = (EFI_PEI_FV_HANDLE) Buffer; @@ -1915,7 +1915,7 @@ PeiFfsFvPpiGetVolumeInfo ( CopyMem (&FwVolHeader, FvHandle, sizeof (EFI_FIRMWARE_VOLUME_HEADER)); // - // Check Fv Image Signature + // Check FV Image Signature // if (FwVolHeader.Signature != EFI_FVH_SIGNATURE) { return EFI_INVALID_PARAMETER; @@ -2089,7 +2089,7 @@ FvHandleToCoreHandle ( /** Get instance of PEI_CORE_FV_HANDLE for next volume according to given index. - This routine also will install FvInfo ppi for FV hob in PI ways. + This routine also will install FvInfo PPI for FV HOB in PI ways. @param Private Pointer of PEI_CORE_INSTANCE @param Instance The index of FV want to be searched. @@ -2185,10 +2185,10 @@ PeiReinitializeFv ( } /** - Report the information for a new discoveried FV in unknown third-party format. + Report the information for a new discovered FV in unknown third-party format. If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for third-party FV format, but - the FV in this format has been discoveried, then this FV's information will be cached into + the FV in this format has been discovered, then this FV's information will be cached into PEI_CORE_INSTANCE's UnknownFvInfo array. Also a notification would be installed for unknown third-party FV format guid, if EFI_PEI_FIRMWARE_VOLUME_PPI is installed later by platform's PEIM, the original unknown third-party FV will be processed by @@ -2242,13 +2242,13 @@ AddUnknownFormatFvInfo ( } /** - Find the FV information according to third-party FV format guid. + Find the FV information according to third-party FV format GUID. - This routine also will remove the FV information found by given FV format guid from + This routine also will remove the FV information found by given FV format GUID from PrivateData->UnknownFvInfo[]. @param PrivateData Point to instance of PEI_CORE_INSTANCE - @param Format Point to given FV format guid + @param Format Point to given FV format GUID @param FvInfo On return, the pointer of FV information buffer @param FvInfoSize On return, the size of FV information buffer. @param AuthenticationStatus On return, the authentication status of FV information buffer. @@ -2298,7 +2298,7 @@ FindUnknownFormatFvInfo ( Notification callback function for EFI_PEI_FIRMWARE_VOLUME_PPI. When a EFI_PEI_FIRMWARE_VOLUME_PPI is installed to support new FV format, this - routine is called to process all discoveried FVs in this format. + routine is called to process all discovered FVs in this format. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation @param NotifyDescriptor Address of the notification descriptor data structure. @@ -2352,7 +2352,7 @@ ThirdPartyFvPpiNotifyCallback ( IsProcessed = FALSE; for (FvIndex = 0; FvIndex < PrivateData->FvCount; FvIndex ++) { if (PrivateData->Fv[FvIndex].FvHandle == FvHandle) { - DEBUG ((EFI_D_INFO, "The Fv %p has already been processed!\n", FvInfo)); + DEBUG ((DEBUG_INFO, "The FV %p has already been processed!\n", FvInfo)); IsProcessed = TRUE; break; } @@ -2398,7 +2398,7 @@ ThirdPartyFvPpiNotifyCallback ( PrivateData->FvCount ++; // - // Scan and process the new discoveried FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE + // Scan and process the new discovered FV for EFI_FV_FILETYPE_FIRMWARE_VOLUME_IMAGE // FileHandle = NULL; do { diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.h b/MdeModulePkg/Core/Pei/FwVol/FwVol.h index ca80e84e0fc..263f0d7a560 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.h +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.h @@ -1,7 +1,7 @@ /** @file The internal header file for firmware volume related definitions. -Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -303,12 +303,12 @@ FindFileEx ( ); /** - Report the information for a new discoveried FV in unknown format. + Report the information for a new discovered FV in unknown format. - If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for specifical FV format, but - the FV in this FV format has been discoveried, then the information of this FV + If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for specific FV format, but + the FV in this FV format has been discovered, then the information of this FV will be cached into PEI_CORE_INSTANCE's UnknownFvInfo array. - Also a notification would be installed for unknown FV format guid, if EFI_PEI_FIRMWARE_VOLUME_PPI + Also a notification would be installed for unknown FV format GUID, if EFI_PEI_FIRMWARE_VOLUME_PPI is installed later by platform's PEIM, the original unknown FV will be processed by using new installed EFI_PEI_FIRMWARE_VOLUME_PPI. @@ -325,14 +325,14 @@ AddUnknownFormatFvInfo ( ); /** - Find the FV information according to FV format guid. + Find the FV information according to FV format GUID. - This routine also will remove the FV information found by given FV format guid from + This routine also will remove the FV information found by given FV format GUID from PrivateData->UnknownFvInfo[]. @param PrivateData Point to instance of PEI_CORE_INSTANCE - @param Format Point to given FV format guid - @param FvInfo On return, the pointer of FV information buffer in given FV format guid + @param Format Point to given FV format GUID + @param FvInfo On return, the pointer of FV information buffer in given FV format GUID @param FvInfoSize On return, the size of FV information buffer. @param AuthenticationStatus On return, the authentication status of FV information buffer. @@ -352,7 +352,7 @@ FindUnknownFormatFvInfo ( Notification callback function for EFI_PEI_FIRMWARE_VOLUME_PPI. When a EFI_PEI_FIRMWARE_VOLUME_PPI is installed to support new FV format, this - routine is called to process all discoveried FVs in this format. + routine is called to process all discovered FVs in this format. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation @param NotifyDescriptor Address of the notification descriptor data structure. diff --git a/MdeModulePkg/Core/Pei/Hob/Hob.c b/MdeModulePkg/Core/Pei/Hob/Hob.c index 5900f6042b6..e0e47fad25b 100644 --- a/MdeModulePkg/Core/Pei/Hob/Hob.c +++ b/MdeModulePkg/Core/Pei/Hob/Hob.c @@ -1,7 +1,7 @@ /** @file This module provide Hand-Off Block manupulation. -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -55,7 +55,7 @@ PeiGetHobList ( @param Length Length of the new HOB to allocate. @param Hob Pointer to the new HOB. - @return EFI_SUCCESS Success to create hob. + @return EFI_SUCCESS Success to create HOB. @retval EFI_INVALID_PARAMETER if Hob is NULL @retval EFI_NOT_AVAILABLE_YET if HobList is still not available. @retval EFI_OUT_OF_RESOURCES if there is no more memory to grow the Hoblist. diff --git a/MdeModulePkg/Core/Pei/Image/Image.c b/MdeModulePkg/Core/Pei/Image/Image.c index d553d9128fd..e3ee3699337 100644 --- a/MdeModulePkg/Core/Pei/Image/Image.c +++ b/MdeModulePkg/Core/Pei/Image/Image.c @@ -1,7 +1,7 @@ /** @file Pei Core Load Image Support -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -99,7 +99,7 @@ CheckAndMarkFixLoadingMemoryUsageBitMap ( } // - // Test if the memory is avalaible or not. + // Test if the memory is available or not. // MemoryUsageBitMap = Private->PeiCodeMemoryRangeUsageBitMap; BaseOffsetPageNumber = EFI_SIZE_TO_PAGES((UINT32)(ImageBase - PeiCodeBase)); @@ -290,7 +290,7 @@ LoadAndRelocatePeCoffImage ( } // - // Initilize local IsS3Boot and IsRegisterForShadow variable + // Initialize local IsS3Boot and IsRegisterForShadow variable // IsS3Boot = FALSE; if (Private->HobList.HandoffInformationTable->BootMode == BOOT_ON_S3_RESUME) { @@ -363,7 +363,7 @@ LoadAndRelocatePeCoffImage ( if (EFI_ERROR (Status)){ DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED ERROR: Failed to load module at fixed address. \n")); // - // The PEIM is not assiged valid address, try to allocate page to load it. + // The PEIM is not assigned valid address, try to allocate page to load it. // Status = PeiServicesAllocatePages (EfiBootServicesCode, EFI_SIZE_TO_PAGES ((UINT32) AlignImageSize), @@ -602,7 +602,7 @@ PeiLoadImageLoadImage ( // // Copy the PDB file name to our temporary string, and replace .pdb with .efi // The PDB file name is limited in the range of 0~511. - // If the length is bigger than 511, trim the redudant characters to avoid overflow in array boundary. + // If the length is bigger than 511, trim the redundant characters to avoid overflow in array boundary. // for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) { EfiFileName[Index] = AsciiString[Index + StartIndex]; diff --git a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c index 706837890fd..838a003baaf 100644 --- a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c +++ b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c @@ -1,7 +1,7 @@ /** @file EFI PEI Core memory services -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -17,7 +17,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent environment, such as the size and location of temporary RAM, the stack location and the BFV location. @param OldCoreData Pointer to the PEI Core data. - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. **/ VOID @@ -32,7 +32,7 @@ InitializeMemoryServices ( // // First entering PeiCore, following code will initialized some field - // in PeiCore's private data according to hand off data from sec core. + // in PeiCore's private data according to hand off data from SEC core. // if (OldCoreData == NULL) { @@ -61,7 +61,7 @@ InitializeMemoryServices ( The usage model is that the PEIM that discovers the permanent memory shall invoke this service. This routine will hold discoveried memory information into PeiCore's private data, and set SwitchStackSignal flag. After PEIM who discovery memory is dispatched, - PeiDispatcher will migrate temporary memory to permenement memory. + PeiDispatcher will migrate temporary memory to permanent memory. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. @param MemoryBegin Start of memory address. @@ -86,7 +86,7 @@ PeiInstallPeiMemory ( // // PEI_SERVICE.InstallPeiMemory should only be called one time during whole PEI phase. // If it is invoked more than one time, ASSERT information is given for developer debugging in debug tip and - // simply return EFI_SUCESS in release tip to ignore it. + // simply return EFI_SUCCESS in release tip to ignore it. // if (PrivateData->PeiMemoryInstalled) { DEBUG ((EFI_D_ERROR, "ERROR: PeiInstallPeiMemory is called more than once!\n")); @@ -758,8 +758,8 @@ PeiFreePages ( /** - Pool allocation service. Before permanent memory is discoveried, the pool will - be allocated the heap in the temporary memory. Genenrally, the size of heap in temporary + Pool allocation service. Before permanent memory is discovered, the pool will + be allocated the heap in the temporary memory. Generally, the size of heap in temporary memory does not exceed to 64K, so the biggest pool size could be allocated is 64K. @@ -790,7 +790,7 @@ PeiAllocatePool ( // // Generally, the size of heap in temporary memory does not exceed to 64K, - // HobLength is multiples of 8 bytes, so the maxmium size of pool is 0xFFF8 - sizeof (EFI_HOB_MEMORY_POOL) + // HobLength is multiples of 8 bytes, so the maximum size of pool is 0xFFF8 - sizeof (EFI_HOB_MEMORY_POOL) // if (Size > (0xFFF8 - sizeof (EFI_HOB_MEMORY_POOL))) { return EFI_OUT_OF_RESOURCES; diff --git a/MdeModulePkg/Core/Pei/PeiMain.h b/MdeModulePkg/Core/Pei/PeiMain.h index f2aa97c6640..3f61247a0f7 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.h +++ b/MdeModulePkg/Core/Pei/PeiMain.h @@ -47,7 +47,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// /// It is an FFS type extension used for PeiFindFileEx. It indicates current -/// Ffs searching is for all PEIMs can be dispatched by PeiCore. +/// FFS searching is for all PEIMs can be dispatched by PeiCore. /// #define PEI_CORE_INTERNAL_FFS_FILE_DISPATCH_TYPE 0xff @@ -116,7 +116,7 @@ typedef struct { } PEI_PPI_DATABASE; // -// PEI_CORE_FV_HANDE.PeimState +// PEI_CORE_FV_HANDLE.PeimState // Do not change these values as there is code doing math to change states. // Look for Private->Fv[FvCount].PeimState[PeimCount]++; // @@ -136,11 +136,11 @@ typedef struct { EFI_PEI_FV_HANDLE FvHandle; UINTN PeimCount; // - // Ponter to the buffer with the PeimCount number of Entries. + // Pointer to the buffer with the PeimCount number of Entries. // UINT8 *PeimState; // - // Ponter to the buffer with the PeimCount number of Entries. + // Pointer to the buffer with the PeimCount number of Entries. // EFI_PEI_FILE_HANDLE *FvFileHandles; BOOLEAN ScanFv; @@ -277,7 +277,7 @@ struct _PEI_CORE_INSTANCE { // // For Loading modules at fixed address feature to cache the top address below which the // Runtime code, boot time code and PEI memory will be placed. Please note that the offset between this field - // and Ps should not be changed since maybe user could get this top address by using the offet to Ps. + // and Ps should not be changed since maybe user could get this top address by using the offset to Ps. // EFI_PHYSICAL_ADDRESS LoadModuleAtFixAddressTopAddress; // @@ -372,7 +372,7 @@ PeiCore ( This is the POSTFIX version of the dependency evaluator. When a PUSH [PPI GUID] is encountered, a pointer to the GUID is stored on - the evaluation stack. When that entry is poped from the evaluation + the evaluation stack. When that entry is popped from the evaluation stack, the PPI is checked if it is installed. This method allows some time savings as not all PPIs must be checked for certain operation types (AND, OR). @@ -412,7 +412,7 @@ PeiDispatcher ( @param PrivateData PeiCore's private data structure @param OldCoreData Old data from SecCore - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. @param SecCoreData Points to a data structure containing SEC to PEI handoff data, such as the size and location of temporary RAM, the stack location and the BFV location. @@ -453,7 +453,7 @@ DepexSatisfied ( @param PrivateData Pointer to the PEI Core data. @param OldCoreData Pointer to old PEI Core data. - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. **/ VOID @@ -482,7 +482,7 @@ ConvertPpiPointers ( Install PPI services. It is implementation of EFI_PEI_SERVICE.InstallPpi. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. - @param PpiList Pointer to ppi array that want to be installed. + @param PpiList Pointer to PPI array that want to be installed. @retval EFI_SUCCESS if all PPIs in PpiList are successfully installed. @retval EFI_INVALID_PARAMETER if PpiList is NULL pointer @@ -659,7 +659,7 @@ PeiSetBootMode ( @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. @param OldCoreData Pointer to the old core data. - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. **/ VOID @@ -687,7 +687,7 @@ VerifyFv ( @param PrivateData PeiCore's private data structure @param VolumeHandle Handle of FV - @param FileHandle Handle of PEIM's ffs + @param FileHandle Handle of PEIM's FFS @param AuthenticationStatus Authentication status @retval EFI_SUCCESS Image is OK @@ -730,7 +730,7 @@ PeiGetHobList ( @param Length Length of the new HOB to allocate. @param Hob Pointer to the new HOB. - @return EFI_SUCCESS Success to create hob. + @return EFI_SUCCESS Success to create HOB. @retval EFI_INVALID_PARAMETER if Hob is NULL @retval EFI_NOT_AVAILABLE_YET if HobList is still not available. @retval EFI_OUT_OF_RESOURCES if there is no more memory to grow the Hoblist. @@ -887,7 +887,7 @@ PeiFfsFindNextVolume ( @param SecCoreData Points to a data structure containing SEC to PEI handoff data, such as the size and location of temporary RAM, the stack location and the BFV location. @param OldCoreData Pointer to the PEI Core data. - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. **/ VOID @@ -1111,7 +1111,7 @@ PeiResetSystem2 ( /** - Initialize PeiCore Fv List. + Initialize PeiCore FV List. @param PrivateData - Pointer to PEI_CORE_INSTANCE. @@ -1125,7 +1125,7 @@ PeiInitializeFv ( ); /** - Process Firmware Volum Information once FvInfoPPI install. + Process Firmware Volume Information once FvInfoPPI install. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. @param NotifyDescriptor Address of the notification descriptor data structure. @@ -1136,7 +1136,7 @@ PeiInitializeFv ( **/ EFI_STATUS EFIAPI -FirmwareVolmeInfoPpiNotifyCallback ( +FirmwareVolumeInfoPpiNotifyCallback ( IN EFI_PEI_SERVICES **PeiServices, IN EFI_PEI_NOTIFY_DESCRIPTOR *NotifyDescriptor, IN VOID *Ppi @@ -1293,11 +1293,11 @@ SecurityPpiNotifyCallback ( ); /** - Get Fv image(s) from the FV type file, then install FV INFO(2) ppi, Build FV(2, 3) hob. + Get FV image(s) from the FV type file, then install FV INFO(2) PPI, Build FV(2, 3) HOB. @param PrivateData PeiCore's private data structure - @param ParentFvCoreHandle Pointer of EFI_CORE_FV_HANDLE to parent Fv image that contain this Fv image. - @param ParentFvFileHandle File handle of a Fv type file that contain this Fv image. + @param ParentFvCoreHandle Pointer of EFI_CORE_FV_HANDLE to parent FV image that contain this FV image. + @param ParentFvFileHandle File handle of a FV type file that contain this FV image. @retval EFI_NOT_FOUND FV image can't be found. @retval EFI_SUCCESS Successfully to process it. @@ -1316,7 +1316,7 @@ ProcessFvFile ( /** Get instance of PEI_CORE_FV_HANDLE for next volume according to given index. - This routine also will install FvInfo ppi for FV hob in PI ways. + This routine also will install FvInfo PPI for FV HOB in PI ways. @param Private Pointer of PEI_CORE_INSTANCE @param Instance The index of FV want to be searched. diff --git a/MdeModulePkg/Core/Pei/PeiMain.inf b/MdeModulePkg/Core/Pei/PeiMain.inf index 7c482dacfc3..6e25cc40232 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.inf +++ b/MdeModulePkg/Core/Pei/PeiMain.inf @@ -69,12 +69,12 @@ [Guids] gPeiAprioriFileNameGuid ## SOMETIMES_CONSUMES ## File - ## PRODUCES ## UNDEFINED # Install ppi - ## CONSUMES ## UNDEFINED # Locate ppi + ## PRODUCES ## UNDEFINED # Install PPI + ## CONSUMES ## UNDEFINED # Locate PPI gEfiFirmwareFileSystem2Guid - ## PRODUCES ## UNDEFINED # Install ppi - ## CONSUMES ## UNDEFINED # Locate ppi - ## CONSUMES ## GUID # Used to compare with FV's file system guid and get the FV's file system format + ## PRODUCES ## UNDEFINED # Install PPI + ## CONSUMES ## UNDEFINED # Locate PPI + ## CONSUMES ## GUID # Used to compare with FV's file system GUID and get the FV's file system format gEfiFirmwareFileSystem3Guid [Ppis] diff --git a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c index 33f056ea8f5..025d7f98ec2 100644 --- a/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c +++ b/MdeModulePkg/Core/Pei/PeiMain/PeiMain.c @@ -315,7 +315,7 @@ PeiCore ( } // - // Shadow PEI Core. When permanent memory is avaiable, shadow + // Shadow PEI Core. When permanent memory is available, shadow // PEI Core and PEIMs to get high performance. // OldCoreData->ShadowedPeiCore = (PEICORE_FUNCTION_POINTER) (UINTN) PeiCore; diff --git a/MdeModulePkg/Core/Pei/Ppi/Ppi.c b/MdeModulePkg/Core/Pei/Ppi/Ppi.c index 964aee690e2..1ffe718c470 100644 --- a/MdeModulePkg/Core/Pei/Ppi/Ppi.c +++ b/MdeModulePkg/Core/Pei/Ppi/Ppi.c @@ -1,7 +1,7 @@ /** @file EFI PEI Core PPI services -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -663,7 +663,7 @@ ProcessDispatchNotifyList ( // // Check if the PEIM that was just dispatched resulted in any // Notifies getting installed. If so, go process any dispatch - // level Notifies that match the previouly installed PPIs. + // level Notifies that match the previously installed PPIs. // Use "while" instead of "if" since ProcessNotify can modify // DispatchNotifyList.CurrentCount (with NotifyPpi) so we have // to iterate until the same. diff --git a/MdeModulePkg/Core/Pei/Security/Security.c b/MdeModulePkg/Core/Pei/Security/Security.c index 99da505538f..8c18ed6cc89 100644 --- a/MdeModulePkg/Core/Pei/Security/Security.c +++ b/MdeModulePkg/Core/Pei/Security/Security.c @@ -1,7 +1,7 @@ /** @file EFI PEI Core Security services -Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -20,7 +20,7 @@ EFI_PEI_NOTIFY_DESCRIPTOR mNotifyList = { @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. @param OldCoreData Pointer to the old core data. - NULL if being run in non-permament memory mode. + NULL if being run in non-permanent memory mode. **/ VOID @@ -76,7 +76,7 @@ SecurityPpiNotifyCallback ( @param PrivateData PeiCore's private data structure @param VolumeHandle Handle of FV - @param FileHandle Handle of PEIM's ffs + @param FileHandle Handle of PEIM's FFS @param AuthenticationStatus Authentication status @retval EFI_SUCCESS Image is OK @@ -92,7 +92,7 @@ VerifyPeim ( ) { EFI_STATUS Status; - BOOLEAN DeferExection; + BOOLEAN DeferExecution; Status = EFI_NOT_FOUND; if (PrivateData->PrivateSecurityPpi == NULL) { @@ -114,9 +114,9 @@ VerifyPeim ( AuthenticationStatus, VolumeHandle, FileHandle, - &DeferExection + &DeferExecution ); - if (DeferExection) { + if (DeferExecution) { Status = EFI_SECURITY_VIOLATION; } } From d3add11e87dace180387562d6f1951f2bffbd3d9 Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Wed, 20 Nov 2019 17:31:24 -0800 Subject: [PATCH 177/384] MdeModulePkg PeiCore: Improve comment semantics This patch clarifies wording in several PeiCore comments to improve reading comprehension. Cc: Dandan Bi Cc: Liming Gao Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Jian J Wang --- MdeModulePkg/Core/Pei/Dependency/Dependency.c | 4 ++-- MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c | 4 ++-- MdeModulePkg/Core/Pei/FwVol/FwVol.c | 24 ++++++++++--------- MdeModulePkg/Core/Pei/FwVol/FwVol.h | 9 +++---- MdeModulePkg/Core/Pei/Memory/MemoryServices.c | 6 ++--- MdeModulePkg/Core/Pei/PeiMain.h | 11 +++++---- 6 files changed, 31 insertions(+), 27 deletions(-) diff --git a/MdeModulePkg/Core/Pei/Dependency/Dependency.c b/MdeModulePkg/Core/Pei/Dependency/Dependency.c index 9a8353aef20..b53e5f2686e 100644 --- a/MdeModulePkg/Core/Pei/Dependency/Dependency.c +++ b/MdeModulePkg/Core/Pei/Dependency/Dependency.c @@ -2,8 +2,8 @@ PEI Dispatcher Dependency Evaluator This routine evaluates a dependency expression (DEPENDENCY_EXPRESSION) to determine - if a driver can be scheduled for execution. The criteria for - schedulability is that the dependency expression is satisfied. + if a driver can be scheduled for execution. The criteria to be scheduled is + that the dependency expression is satisfied. Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c index c9f2a912643..a18ac47f617 100644 --- a/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c +++ b/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c @@ -1347,8 +1347,8 @@ DepexSatisfied ( } /** - This routine enable a PEIM to register itself to shadow when PEI Foundation - discovery permanent memory. + This routine enables a PEIM to register itself for shadow when the PEI Foundation + discovers permanent memory. @param FileHandle File handle of a PEIM. diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.c b/MdeModulePkg/Core/Pei/FwVol/FwVol.c index c21eb9c0396..b3661146f29 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.c +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.c @@ -593,7 +593,7 @@ FirmwareVolumeInfoPpiNotifyCallback ( } // - // Locate the corresponding FV_PPI according to founded FV's format GUID + // Locate the corresponding FV_PPI according to the format GUID of the FV found // Status = PeiServicesLocatePpi ( &FvInfo2Ppi.FvFormat, @@ -1533,7 +1533,7 @@ ProcessFvFile ( ); // - // Inform the extracted FvImage to FV HOB consumer phase, i.e. DXE phase + // Expose the extracted FvImage to the FV HOB consumer phase, i.e. DXE phase // BuildFvHob ( (EFI_PHYSICAL_ADDRESS) (UINTN) FvHeader, @@ -2087,12 +2087,13 @@ FvHandleToCoreHandle ( } /** - Get instance of PEI_CORE_FV_HANDLE for next volume according to given index. + Gets a PEI_CORE_FV_HANDLE instance for the next volume according to the given index. - This routine also will install FvInfo PPI for FV HOB in PI ways. + This routine also will install an instance of the FvInfo PPI for the FV HOB + as defined in the PI specification. @param Private Pointer of PEI_CORE_INSTANCE - @param Instance The index of FV want to be searched. + @param Instance Index of the FV to search @return Instance of PEI_CORE_FV_HANDLE. **/ @@ -2185,13 +2186,14 @@ PeiReinitializeFv ( } /** - Report the information for a new discovered FV in unknown third-party format. + Report the information for a newly discovered FV in an unknown format. - If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for third-party FV format, but - the FV in this format has been discovered, then this FV's information will be cached into - PEI_CORE_INSTANCE's UnknownFvInfo array. - Also a notification would be installed for unknown third-party FV format guid, if EFI_PEI_FIRMWARE_VOLUME_PPI - is installed later by platform's PEIM, the original unknown third-party FV will be processed by + If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for a third-party FV format, but + the FV has been discovered, then the information of this FV will be cached into PEI_CORE_INSTANCE's + UnknownFvInfo array. + + Also a notification would be installed for unknown FV format GUID, if EFI_PEI_FIRMWARE_VOLUME_PPI + is installed later by platform's PEIM, the original unknown FV will be processed by using new installed EFI_PEI_FIRMWARE_VOLUME_PPI. @param PrivateData Point to instance of PEI_CORE_INSTANCE diff --git a/MdeModulePkg/Core/Pei/FwVol/FwVol.h b/MdeModulePkg/Core/Pei/FwVol/FwVol.h index 263f0d7a560..7241c01b8cb 100644 --- a/MdeModulePkg/Core/Pei/FwVol/FwVol.h +++ b/MdeModulePkg/Core/Pei/FwVol/FwVol.h @@ -303,11 +303,12 @@ FindFileEx ( ); /** - Report the information for a new discovered FV in unknown format. + Report the information for a newly discovered FV in an unknown format. + + If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for a third-party FV format, but + the FV has been discovered, then the information of this FV will be cached into PEI_CORE_INSTANCE's + UnknownFvInfo array. - If the EFI_PEI_FIRMWARE_VOLUME_PPI has not been installed for specific FV format, but - the FV in this FV format has been discovered, then the information of this FV - will be cached into PEI_CORE_INSTANCE's UnknownFvInfo array. Also a notification would be installed for unknown FV format GUID, if EFI_PEI_FIRMWARE_VOLUME_PPI is installed later by platform's PEIM, the original unknown FV will be processed by using new installed EFI_PEI_FIRMWARE_VOLUME_PPI. diff --git a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c index 838a003baaf..6b3a64a811c 100644 --- a/MdeModulePkg/Core/Pei/Memory/MemoryServices.c +++ b/MdeModulePkg/Core/Pei/Memory/MemoryServices.c @@ -759,8 +759,8 @@ PeiFreePages ( /** Pool allocation service. Before permanent memory is discovered, the pool will - be allocated the heap in the temporary memory. Generally, the size of heap in temporary - memory does not exceed to 64K, so the biggest pool size could be allocated is + be allocated in the heap in temporary memory. Generally, the size of the heap in temporary + memory does not exceed 64K, so the biggest pool size could be allocated is 64K. @param PeiServices An indirect pointer to the EFI_PEI_SERVICES table published by the PEI Foundation. @@ -789,7 +789,7 @@ PeiAllocatePool ( // // - // Generally, the size of heap in temporary memory does not exceed to 64K, + // Generally, the size of heap in temporary memory does not exceed 64K, // HobLength is multiples of 8 bytes, so the maximum size of pool is 0xFFF8 - sizeof (EFI_HOB_MEMORY_POOL) // if (Size > (0xFFF8 - sizeof (EFI_HOB_MEMORY_POOL))) { diff --git a/MdeModulePkg/Core/Pei/PeiMain.h b/MdeModulePkg/Core/Pei/PeiMain.h index 3f61247a0f7..6431bdaaacf 100644 --- a/MdeModulePkg/Core/Pei/PeiMain.h +++ b/MdeModulePkg/Core/Pei/PeiMain.h @@ -1217,8 +1217,8 @@ PeiFfsGetVolumeInfo ( ); /** - This routine enable a PEIM to register itself to shadow when PEI Foundation - discovery permanent memory. + This routine enables a PEIM to register itself for shadow when the PEI Foundation + discovers permanent memory. @param FileHandle File handle of a PEIM. @@ -1314,12 +1314,13 @@ ProcessFvFile ( ); /** - Get instance of PEI_CORE_FV_HANDLE for next volume according to given index. + Gets a PEI_CORE_FV_HANDLE instance for the next volume according to the given index. - This routine also will install FvInfo PPI for FV HOB in PI ways. + This routine also will install an instance of the FvInfo PPI for the FV HOB + as defined in the PI specification. @param Private Pointer of PEI_CORE_INSTANCE - @param Instance The index of FV want to be searched. + @param Instance Index of the FV to search @return Instance of PEI_CORE_FV_HANDLE. **/ From 2fe25a74d6fee3c2ac0b930f7f3596cb432e766e Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Tue, 5 Mar 2019 14:32:48 +0100 Subject: [PATCH 178/384] ArmPkg/MmCommunicationDxe: relay architected PI events to MM context PI defines a few architected events that have significance in the MM context as well as in the non-secure DXE context. So register notify handlers for these events, and relay them into the standalone MM world. Signed-off-by: Ard Biesheuvel Reviewed-by: Jiewen Yao Reviewed-by: Achin Gupta --- .../MmCommunicationDxe/MmCommunication.c | 47 ++++++++++++++++++- .../MmCommunicationDxe/MmCommunication.inf | 5 ++ 2 files changed, 50 insertions(+), 2 deletions(-) diff --git a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c index d06dcc4d208..5f52afa0fed 100644 --- a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c +++ b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.c @@ -259,6 +259,43 @@ GetMmCompatibility () return Status; } +STATIC EFI_GUID* CONST mGuidedEventGuid[] = { + &gEfiEndOfDxeEventGroupGuid, + &gEfiEventExitBootServicesGuid, + &gEfiEventReadyToBootGuid, +}; + +STATIC EFI_EVENT mGuidedEvent[ARRAY_SIZE (mGuidedEventGuid)]; + +/** + Event notification that is fired when GUIDed Event Group is signaled. + + @param Event The Event that is being processed, not used. + @param Context Event Context, not used. + +**/ +STATIC +VOID +EFIAPI +MmGuidedEventNotify ( + IN EFI_EVENT Event, + IN VOID *Context + ) +{ + EFI_MM_COMMUNICATE_HEADER Header; + UINTN Size; + + // + // Use Guid to initialize EFI_SMM_COMMUNICATE_HEADER structure + // + CopyGuid (&Header.HeaderGuid, Context); + Header.MessageLength = 1; + Header.Data[0] = 0; + + Size = sizeof (Header); + MmCommunicationCommunicate (&mMmCommunication, &Header, &Size); +} + /** The Entry Point for MM Communication @@ -281,6 +318,7 @@ MmCommunicationInitialize ( ) { EFI_STATUS Status; + UINTN Index; // Check if we can make the MM call Status = GetMmCompatibility (); @@ -345,8 +383,13 @@ MmCommunicationInitialize ( NULL, &mSetVirtualAddressMapEvent ); - if (Status == EFI_SUCCESS) { - return Status; + ASSERT_EFI_ERROR (Status); + + for (Index = 0; Index < ARRAY_SIZE (mGuidedEventGuid); Index++) { + Status = gBS->CreateEventEx (EVT_NOTIFY_SIGNAL, TPL_CALLBACK, + MmGuidedEventNotify, mGuidedEventGuid[Index], + mGuidedEventGuid[Index], &mGuidedEvent[Index]); + ASSERT_EFI_ERROR (Status); } gBS->UninstallProtocolInterface ( diff --git a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf index 450fc9bb541..505228704ea 100644 --- a/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf +++ b/ArmPkg/Drivers/MmCommunicationDxe/MmCommunication.inf @@ -42,6 +42,11 @@ [Protocols] gEfiMmCommunicationProtocolGuid ## PRODUCES +[Guids] + gEfiEndOfDxeEventGroupGuid + gEfiEventExitBootServicesGuid + gEfiEventReadyToBootGuid + [Pcd.common] gArmTokenSpaceGuid.PcdMmBufferBase gArmTokenSpaceGuid.PcdMmBufferSize From bfb141cf19dd6f9b8df8b9d0914a5b3b15e1a798 Mon Sep 17 00:00:00 2001 From: Pete Batard Date: Tue, 10 Dec 2019 18:23:04 +0000 Subject: [PATCH 179/384] MdePkg/Include: Add DCC and BCM2835 SPCR UART types As per the Microsoft Debug Port Table 2 (DBG2) documentation, that can be found online, we are missing 2 serial interface types for Arm DCC and Bcm2835 (the latter being used with the Raspberry Pi). These same types are present in DebugPort2Table.h so add them to SerialPortConsoleRedirectionTable.h too. Note that we followed the same idiosyncrasies as DebugPort2Table for naming these new macros. Signed-off-by: Pete Batard Acked-by: Ard Biesheuvel Reviewed-by: Liming Gao --- .../SerialPortConsoleRedirectionTable.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/MdePkg/Include/IndustryStandard/SerialPortConsoleRedirectionTable.h b/MdePkg/Include/IndustryStandard/SerialPortConsoleRedirectionTable.h index b069fb2be97..2066c7895e5 100644 --- a/MdePkg/Include/IndustryStandard/SerialPortConsoleRedirectionTable.h +++ b/MdePkg/Include/IndustryStandard/SerialPortConsoleRedirectionTable.h @@ -90,6 +90,16 @@ typedef struct { /// #define EFI_ACPI_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_INTERFACE_TYPE_ARM_SBSA_GENERIC_UART 0x0e +/// +/// ARM DCC +/// +#define EFI_ACPI_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_INTERFACE_TYPE_DCC 0x0f + +/// +/// BCM2835 UART +/// +#define EFI_ACPI_SERIAL_PORT_CONSOLE_REDIRECTION_TABLE_INTERFACE_TYPE_BCM2835_UART 0x10 + // // Interrupt Type // From 8af0e76cb48f479160340048ec71efe72bc0f275 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 12 Dec 2019 15:43:24 -0800 Subject: [PATCH 180/384] Convert all strings from Unicode to ASCII. --- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 218 +++++++++--------- UnitTestPkg/Include/Library/UnitTestLib.h | 14 +- UnitTestPkg/Include/UnitTestTypes.h | 26 +-- UnitTestPkg/Library/UnitTestLib/UnitTestLib.c | 52 ++--- .../Library/UnitTestLogLib/UnitTestLogLib.c | 24 +- .../UnitTestResultReportLibDebug.c | 10 +- .../UnitTestResultReportLibPlainTextOutput.c | 27 ++- UnitTestPkg/ReadMe.md | 8 +- .../SampleUnitTestApp/SampleUnitTestApp.c | 26 ++- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 21 +- .../SampleUnitTestSmm/SampleUnitTestSmm.c | 21 +- 11 files changed, 227 insertions(+), 220 deletions(-) diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 8a7d40fd926..f7781cb0148 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -30,8 +30,8 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "TestBaseSafeIntLib.h" -#define UNIT_TEST_NAME L"Int Safe Lib Unit Test Application" -#define UNIT_TEST_VERSION L"0.1" +#define UNIT_TEST_NAME "Int Safe Lib Unit Test Application" +#define UNIT_TEST_VERSION "0.1" // // Conversion function tests: @@ -2741,20 +2741,18 @@ UefiTestMain ( UNIT_TEST_SUITE *ConversionTestSuite; UNIT_TEST_SUITE *AdditionSubtractionTestSuite; UNIT_TEST_SUITE *MultiplicationTestSuite; - CHAR16 ShortName[100]; Fw = NULL; ConversionTestSuite = NULL; AdditionSubtractionTestSuite = NULL; MultiplicationTestSuite = NULL; - AsciiStrToUnicodeStrS (gEfiCallerBaseName, ShortName, sizeof(ShortName)/sizeof(ShortName[0])); - DEBUG((DEBUG_INFO, "%s v%s\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); + DEBUG((DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework (&Fw, UNIT_TEST_NAME, ShortName, UNIT_TEST_VERSION); + Status = InitUnitTestFramework (&Fw, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); goto EXIT; @@ -2763,133 +2761,133 @@ UefiTestMain ( /// // Test the conversion functions // - Status = CreateUnitTestSuite (&ConversionTestSuite, Fw, L"Int Safe Conversions Test Suite", L"Common.SafeInt.Convert", NULL, NULL); + Status = CreateUnitTestSuite (&ConversionTestSuite, Fw, "Int Safe Conversions Test Suite", "Common.SafeInt.Convert", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Conversions Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint8", L"Common.SafeInt.Convert.TestSafeInt8ToUint8", TestSafeInt8ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint16", L"Common.SafeInt.Convert.TestSafeInt8ToUint16", TestSafeInt8ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint32", L"Common.SafeInt.Convert.TestSafeInt8ToUint32", TestSafeInt8ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUintn", L"Common.SafeInt.Convert.TestSafeInt8ToUintn", TestSafeInt8ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt8ToUint64", L"Common.SafeInt.Convert.TestSafeInt8ToUint64", TestSafeInt8ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint8ToInt8", L"Common.SafeInt.Convert.TestSafeUint8ToInt8", TestSafeUint8ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint8ToChar8", L"Common.SafeInt.Convert.TestSafeUint8ToChar8", TestSafeUint8ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToInt8", L"Common.SafeInt.Convert.TestSafeInt16ToInt8", TestSafeInt16ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToChar8", L"Common.SafeInt.Convert.TestSafeInt16ToChar8", TestSafeInt16ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint8", L"Common.SafeInt.Convert.TestSafeInt16ToUint8", TestSafeInt16ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint16", L"Common.SafeInt.Convert.TestSafeInt16ToUint16", TestSafeInt16ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint32", L"Common.SafeInt.Convert.TestSafeInt16ToUint32", TestSafeInt16ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUintn", L"Common.SafeInt.Convert.TestSafeInt16ToUintn", TestSafeInt16ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt16ToUint64", L"Common.SafeInt.Convert.TestSafeInt16ToUint64", TestSafeInt16ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint16ToInt8", L"Common.SafeInt.Convert.TestSafeUint16ToInt8", TestSafeUint16ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint16ToChar8", L"Common.SafeInt.Convert.TestSafeUint16ToChar8", TestSafeUint16ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint16ToUint8", L"Common.SafeInt.Convert.TestSafeUint16ToUint8", TestSafeUint16ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint16ToInt16", L"Common.SafeInt.Convert.TestSafeUint16ToInt16", TestSafeUint16ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToInt8", L"Common.SafeInt.Convert.TestSafeInt32ToInt8", TestSafeInt32ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToChar8", L"Common.SafeInt.Convert.TestSafeInt32ToChar8", TestSafeInt32ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint8", L"Common.SafeInt.Convert.TestSafeInt32ToUint8", TestSafeInt32ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToInt16", L"Common.SafeInt.Convert.TestSafeInt32ToInt16", TestSafeInt32ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint16", L"Common.SafeInt.Convert.TestSafeInt32ToUint16", TestSafeInt32ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint32", L"Common.SafeInt.Convert.TestSafeInt32ToUint32", TestSafeInt32ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUintn", L"Common.SafeInt.Convert.TestSafeInt32ToUintn", TestSafeInt32ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt32ToUint64", L"Common.SafeInt.Convert.TestSafeInt32ToUint64", TestSafeInt32ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt8", L"Common.SafeInt.Convert.TestSafeUint32ToInt8", TestSafeUint32ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToChar8", L"Common.SafeInt.Convert.TestSafeUint32ToChar8", TestSafeUint32ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToUint8", L"Common.SafeInt.Convert.TestSafeUint32ToUint8", TestSafeUint32ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt16", L"Common.SafeInt.Convert.TestSafeUint32ToInt16", TestSafeUint32ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToUint16", L"Common.SafeInt.Convert.TestSafeUint32ToUint16", TestSafeUint32ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToInt32", L"Common.SafeInt.Convert.TestSafeUint32ToInt32", TestSafeUint32ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint32ToIntn", L"Common.SafeInt.Convert.TestSafeUint32ToIntn", TestSafeUint32ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt8", L"Common.SafeInt.Convert.TestSafeIntnToInt8", TestSafeIntnToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToChar8", L"Common.SafeInt.Convert.TestSafeIntnToChar8", TestSafeIntnToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint8", L"Common.SafeInt.Convert.TestSafeIntnToUint8", TestSafeIntnToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt16", L"Common.SafeInt.Convert.TestSafeIntnToInt16", TestSafeIntnToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint16", L"Common.SafeInt.Convert.TestSafeIntnToUint16", TestSafeIntnToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToInt32", L"Common.SafeInt.Convert.TestSafeIntnToInt32", TestSafeIntnToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint32", L"Common.SafeInt.Convert.TestSafeIntnToUint32", TestSafeIntnToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToUintn", L"Common.SafeInt.Convert.TestSafeIntnToUintn", TestSafeIntnToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeIntnToUint64", L"Common.SafeInt.Convert.TestSafeIntnToUint64", TestSafeIntnToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt8", L"Common.SafeInt.Convert.TestSafeUintnToInt8", TestSafeUintnToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToChar8", L"Common.SafeInt.Convert.TestSafeUintnToChar8", TestSafeUintnToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint8", L"Common.SafeInt.Convert.TestSafeUintnToUint8", TestSafeUintnToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt16", L"Common.SafeInt.Convert.TestSafeUintnToInt16", TestSafeUintnToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint16", L"Common.SafeInt.Convert.TestSafeUintnToUint16", TestSafeUintnToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt32", L"Common.SafeInt.Convert.TestSafeUintnToInt32", TestSafeUintnToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToUint32", L"Common.SafeInt.Convert.TestSafeUintnToUint32", TestSafeUintnToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToIntn", L"Common.SafeInt.Convert.TestSafeUintnToIntn", TestSafeUintnToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUintnToInt64", L"Common.SafeInt.Convert.TestSafeUintnToInt64", TestSafeUintnToInt64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt8", L"Common.SafeInt.Convert.TestSafeInt64ToInt8", TestSafeInt64ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToChar8", L"Common.SafeInt.Convert.TestSafeInt64ToChar8", TestSafeInt64ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint8", L"Common.SafeInt.Convert.TestSafeInt64ToUint8", TestSafeInt64ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt16", L"Common.SafeInt.Convert.TestSafeInt64ToInt16", TestSafeInt64ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint16", L"Common.SafeInt.Convert.TestSafeInt64ToUint16", TestSafeInt64ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToInt32", L"Common.SafeInt.Convert.TestSafeInt64ToInt32", TestSafeInt64ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint32", L"Common.SafeInt.Convert.TestSafeInt64ToUint32", TestSafeInt64ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToIntn", L"Common.SafeInt.Convert.TestSafeInt64ToIntn", TestSafeInt64ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUintn", L"Common.SafeInt.Convert.TestSafeInt64ToUintn", TestSafeInt64ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeInt64ToUint64", L"Common.SafeInt.Convert.TestSafeInt64ToUint64", TestSafeInt64ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt8", L"Common.SafeInt.Convert.TestSafeUint64ToInt8", TestSafeUint64ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToChar8", L"Common.SafeInt.Convert.TestSafeUint64ToChar8", TestSafeUint64ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint8", L"Common.SafeInt.Convert.TestSafeUint64ToUint8", TestSafeUint64ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt16", L"Common.SafeInt.Convert.TestSafeUint64ToInt16", TestSafeUint64ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint16", L"Common.SafeInt.Convert.TestSafeUint64ToUint16", TestSafeUint64ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt32", L"Common.SafeInt.Convert.TestSafeUint64ToInt32", TestSafeUint64ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUint32", L"Common.SafeInt.Convert.TestSafeUint64ToUint32", TestSafeUint64ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToIntn", L"Common.SafeInt.Convert.TestSafeUint64ToIntn", TestSafeUint64ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToUintn", L"Common.SafeInt.Convert.TestSafeUint64ToUintn", TestSafeUint64ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, L"Test SafeUint64ToInt64", L"Common.SafeInt.Convert.TestSafeUint64ToInt64", TestSafeUint64ToInt64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint8", "Common.SafeInt.Convert.TestSafeInt8ToUint8", TestSafeInt8ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint16", "Common.SafeInt.Convert.TestSafeInt8ToUint16", TestSafeInt8ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint32", "Common.SafeInt.Convert.TestSafeInt8ToUint32", TestSafeInt8ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUintn", "Common.SafeInt.Convert.TestSafeInt8ToUintn", TestSafeInt8ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint64", "Common.SafeInt.Convert.TestSafeInt8ToUint64", TestSafeInt8ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint8ToInt8", "Common.SafeInt.Convert.TestSafeUint8ToInt8", TestSafeUint8ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint8ToChar8", "Common.SafeInt.Convert.TestSafeUint8ToChar8", TestSafeUint8ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToInt8", "Common.SafeInt.Convert.TestSafeInt16ToInt8", TestSafeInt16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToChar8", "Common.SafeInt.Convert.TestSafeInt16ToChar8", TestSafeInt16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint8", "Common.SafeInt.Convert.TestSafeInt16ToUint8", TestSafeInt16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint16", "Common.SafeInt.Convert.TestSafeInt16ToUint16", TestSafeInt16ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint32", "Common.SafeInt.Convert.TestSafeInt16ToUint32", TestSafeInt16ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUintn", "Common.SafeInt.Convert.TestSafeInt16ToUintn", TestSafeInt16ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint64", "Common.SafeInt.Convert.TestSafeInt16ToUint64", TestSafeInt16ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt8", "Common.SafeInt.Convert.TestSafeUint16ToInt8", TestSafeUint16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToChar8", "Common.SafeInt.Convert.TestSafeUint16ToChar8", TestSafeUint16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToUint8", "Common.SafeInt.Convert.TestSafeUint16ToUint8", TestSafeUint16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt16", "Common.SafeInt.Convert.TestSafeUint16ToInt16", TestSafeUint16ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt8", "Common.SafeInt.Convert.TestSafeInt32ToInt8", TestSafeInt32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToChar8", "Common.SafeInt.Convert.TestSafeInt32ToChar8", TestSafeInt32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint8", "Common.SafeInt.Convert.TestSafeInt32ToUint8", TestSafeInt32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt16", "Common.SafeInt.Convert.TestSafeInt32ToInt16", TestSafeInt32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint16", "Common.SafeInt.Convert.TestSafeInt32ToUint16", TestSafeInt32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint32", "Common.SafeInt.Convert.TestSafeInt32ToUint32", TestSafeInt32ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUintn", "Common.SafeInt.Convert.TestSafeInt32ToUintn", TestSafeInt32ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint64", "Common.SafeInt.Convert.TestSafeInt32ToUint64", TestSafeInt32ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt8", "Common.SafeInt.Convert.TestSafeUint32ToInt8", TestSafeUint32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToChar8", "Common.SafeInt.Convert.TestSafeUint32ToChar8", TestSafeUint32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint8", "Common.SafeInt.Convert.TestSafeUint32ToUint8", TestSafeUint32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt16", "Common.SafeInt.Convert.TestSafeUint32ToInt16", TestSafeUint32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint16", "Common.SafeInt.Convert.TestSafeUint32ToUint16", TestSafeUint32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt32", "Common.SafeInt.Convert.TestSafeUint32ToInt32", TestSafeUint32ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToIntn", "Common.SafeInt.Convert.TestSafeUint32ToIntn", TestSafeUint32ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt8", "Common.SafeInt.Convert.TestSafeIntnToInt8", TestSafeIntnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToChar8", "Common.SafeInt.Convert.TestSafeIntnToChar8", TestSafeIntnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint8", "Common.SafeInt.Convert.TestSafeIntnToUint8", TestSafeIntnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt16", "Common.SafeInt.Convert.TestSafeIntnToInt16", TestSafeIntnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint16", "Common.SafeInt.Convert.TestSafeIntnToUint16", TestSafeIntnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt32", "Common.SafeInt.Convert.TestSafeIntnToInt32", TestSafeIntnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint32", "Common.SafeInt.Convert.TestSafeIntnToUint32", TestSafeIntnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUintn", "Common.SafeInt.Convert.TestSafeIntnToUintn", TestSafeIntnToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint64", "Common.SafeInt.Convert.TestSafeIntnToUint64", TestSafeIntnToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt8", "Common.SafeInt.Convert.TestSafeUintnToInt8", TestSafeUintnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToChar8", "Common.SafeInt.Convert.TestSafeUintnToChar8", TestSafeUintnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint8", "Common.SafeInt.Convert.TestSafeUintnToUint8", TestSafeUintnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt16", "Common.SafeInt.Convert.TestSafeUintnToInt16", TestSafeUintnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint16", "Common.SafeInt.Convert.TestSafeUintnToUint16", TestSafeUintnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt32", "Common.SafeInt.Convert.TestSafeUintnToInt32", TestSafeUintnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint32", "Common.SafeInt.Convert.TestSafeUintnToUint32", TestSafeUintnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToIntn", "Common.SafeInt.Convert.TestSafeUintnToIntn", TestSafeUintnToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt64", "Common.SafeInt.Convert.TestSafeUintnToInt64", TestSafeUintnToInt64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt8", "Common.SafeInt.Convert.TestSafeInt64ToInt8", TestSafeInt64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToChar8", "Common.SafeInt.Convert.TestSafeInt64ToChar8", TestSafeInt64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint8", "Common.SafeInt.Convert.TestSafeInt64ToUint8", TestSafeInt64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt16", "Common.SafeInt.Convert.TestSafeInt64ToInt16", TestSafeInt64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint16", "Common.SafeInt.Convert.TestSafeInt64ToUint16", TestSafeInt64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt32", "Common.SafeInt.Convert.TestSafeInt64ToInt32", TestSafeInt64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint32", "Common.SafeInt.Convert.TestSafeInt64ToUint32", TestSafeInt64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToIntn", "Common.SafeInt.Convert.TestSafeInt64ToIntn", TestSafeInt64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUintn", "Common.SafeInt.Convert.TestSafeInt64ToUintn", TestSafeInt64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint64", "Common.SafeInt.Convert.TestSafeInt64ToUint64", TestSafeInt64ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt8", "Common.SafeInt.Convert.TestSafeUint64ToInt8", TestSafeUint64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToChar8", "Common.SafeInt.Convert.TestSafeUint64ToChar8", TestSafeUint64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint8", "Common.SafeInt.Convert.TestSafeUint64ToUint8", TestSafeUint64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt16", "Common.SafeInt.Convert.TestSafeUint64ToInt16", TestSafeUint64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint16", "Common.SafeInt.Convert.TestSafeUint64ToUint16", TestSafeUint64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt32", "Common.SafeInt.Convert.TestSafeUint64ToInt32", TestSafeUint64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint32", "Common.SafeInt.Convert.TestSafeUint64ToUint32", TestSafeUint64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToIntn", "Common.SafeInt.Convert.TestSafeUint64ToIntn", TestSafeUint64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUintn", "Common.SafeInt.Convert.TestSafeUint64ToUintn", TestSafeUint64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt64", "Common.SafeInt.Convert.TestSafeUint64ToInt64", TestSafeUint64ToInt64, NULL, NULL, NULL); // // Test the addition and subtraction functions // - Status = CreateUnitTestSuite(&AdditionSubtractionTestSuite, Fw, L"Int Safe Add/Subtract Test Suite", L"Common.SafeInt.AddSubtract", NULL, NULL); + Status = CreateUnitTestSuite(&AdditionSubtractionTestSuite, Fw, "Int Safe Add/Subtract Test Suite", "Common.SafeInt.AddSubtract", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Add/Subtract Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint8Add", L"Common.SafeInt.AddSubtract.TestSafeUint8Add", TestSafeUint8Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint16Add", L"Common.SafeInt.AddSubtract.TestSafeUint16Add", TestSafeUint16Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint32Add", L"Common.SafeInt.AddSubtract.TestSafeUint32Add", TestSafeUint32Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUintnAdd", L"Common.SafeInt.AddSubtract.TestSafeUintnAdd", TestSafeUintnAdd, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint64Add", L"Common.SafeInt.AddSubtract.TestSafeUint64Add", TestSafeUint64Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt8Add", L"Common.SafeInt.AddSubtract.TestSafeInt8Add", TestSafeInt8Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt16Add", L"Common.SafeInt.AddSubtract.TestSafeInt16Add", TestSafeInt16Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt32Add", L"Common.SafeInt.AddSubtract.TestSafeInt32Add", TestSafeInt32Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeIntnAdd", L"Common.SafeInt.AddSubtract.TestSafeIntnAdd", TestSafeIntnAdd, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt64Add", L"Common.SafeInt.AddSubtract.TestSafeInt64Add", TestSafeInt64Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint8Sub", L"Common.SafeInt.AddSubtract.TestSafeUint8Sub", TestSafeUint8Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint16Sub", L"Common.SafeInt.AddSubtract.TestSafeUint16Sub", TestSafeUint16Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint32Sub", L"Common.SafeInt.AddSubtract.TestSafeUint32Sub", TestSafeUint32Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUintnSub", L"Common.SafeInt.AddSubtract.TestSafeUintnSub", TestSafeUintnSub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeUint64Sub", L"Common.SafeInt.AddSubtract.TestSafeUint64Sub", TestSafeUint64Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt8Sub", L"Common.SafeInt.AddSubtract.TestSafeInt8Sub", TestSafeInt8Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt16Sub", L"Common.SafeInt.AddSubtract.TestSafeInt16Sub", TestSafeInt16Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt32Sub", L"Common.SafeInt.AddSubtract.TestSafeInt32Sub", TestSafeInt32Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeIntnSub", L"Common.SafeInt.AddSubtract.TestSafeIntnSub", TestSafeIntnSub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, L"Test SafeInt64Sub", L"Common.SafeInt.AddSubtract.TestSafeInt64Sub", TestSafeInt64Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Add", "Common.SafeInt.AddSubtract.TestSafeUint8Add", TestSafeUint8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Add", "Common.SafeInt.AddSubtract.TestSafeUint16Add", TestSafeUint16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Add", "Common.SafeInt.AddSubtract.TestSafeUint32Add", TestSafeUint32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnAdd", "Common.SafeInt.AddSubtract.TestSafeUintnAdd", TestSafeUintnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Add", "Common.SafeInt.AddSubtract.TestSafeUint64Add", TestSafeUint64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Add", "Common.SafeInt.AddSubtract.TestSafeInt8Add", TestSafeInt8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Add", "Common.SafeInt.AddSubtract.TestSafeInt16Add", TestSafeInt16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Add", "Common.SafeInt.AddSubtract.TestSafeInt32Add", TestSafeInt32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnAdd", "Common.SafeInt.AddSubtract.TestSafeIntnAdd", TestSafeIntnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Add", "Common.SafeInt.AddSubtract.TestSafeInt64Add", TestSafeInt64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Sub", "Common.SafeInt.AddSubtract.TestSafeUint8Sub", TestSafeUint8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Sub", "Common.SafeInt.AddSubtract.TestSafeUint16Sub", TestSafeUint16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Sub", "Common.SafeInt.AddSubtract.TestSafeUint32Sub", TestSafeUint32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnSub", "Common.SafeInt.AddSubtract.TestSafeUintnSub", TestSafeUintnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Sub", "Common.SafeInt.AddSubtract.TestSafeUint64Sub", TestSafeUint64Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Sub", "Common.SafeInt.AddSubtract.TestSafeInt8Sub", TestSafeInt8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Sub", "Common.SafeInt.AddSubtract.TestSafeInt16Sub", TestSafeInt16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Sub", "Common.SafeInt.AddSubtract.TestSafeInt32Sub", TestSafeInt32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnSub", "Common.SafeInt.AddSubtract.TestSafeIntnSub", TestSafeIntnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Sub", "Common.SafeInt.AddSubtract.TestSafeInt64Sub", TestSafeInt64Sub, NULL, NULL, NULL); // // Test the multiplication functions // - Status = CreateUnitTestSuite(&MultiplicationTestSuite, Fw, L"Int Safe Multiply Test Suite", L"Common.SafeInt.Multiply", NULL, NULL); + Status = CreateUnitTestSuite(&MultiplicationTestSuite, Fw, "Int Safe Multiply Test Suite", "Common.SafeInt.Multiply", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Multiply Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(MultiplicationTestSuite, L"Test SafeUint8Mult", L"Common.SafeInt.Multiply.TestSafeUint8Mult", TestSafeUint8Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeUint16Mult", L"Common.SafeInt.Multiply.TestSafeUint16Mult", TestSafeUint16Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeUint32Mult", L"Common.SafeInt.Multiply.TestSafeUint32Mult", TestSafeUint32Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeUintnMult", L"Common.SafeInt.Multiply.TestSafeUintnMult", TestSafeUintnMult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeUint64Mult", L"Common.SafeInt.Multiply.TestSafeUint64Mult", TestSafeUint64Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeInt8Mult", L"Common.SafeInt.Multiply.TestSafeInt8Mult", TestSafeInt8Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeInt16Mult", L"Common.SafeInt.Multiply.TestSafeInt16Mult", TestSafeInt16Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeInt32Mult", L"Common.SafeInt.Multiply.TestSafeInt32Mult", TestSafeInt32Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeIntnMult", L"Common.SafeInt.Multiply.TestSafeIntnMult", TestSafeIntnMult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, L"Test SafeInt64Mult", L"Common.SafeInt.Multiply.TestSafeInt64Mult", TestSafeInt64Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint8Mult", "Common.SafeInt.Multiply.TestSafeUint8Mult", TestSafeUint8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint16Mult", "Common.SafeInt.Multiply.TestSafeUint16Mult", TestSafeUint16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint32Mult", "Common.SafeInt.Multiply.TestSafeUint32Mult", TestSafeUint32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUintnMult", "Common.SafeInt.Multiply.TestSafeUintnMult", TestSafeUintnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint64Mult", "Common.SafeInt.Multiply.TestSafeUint64Mult", TestSafeUint64Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt8Mult", "Common.SafeInt.Multiply.TestSafeInt8Mult", TestSafeInt8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt16Mult", "Common.SafeInt.Multiply.TestSafeInt16Mult", TestSafeInt16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt32Mult", "Common.SafeInt.Multiply.TestSafeInt32Mult", TestSafeInt32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeIntnMult", "Common.SafeInt.Multiply.TestSafeIntnMult", TestSafeIntnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt64Mult", "Common.SafeInt.Multiply.TestSafeInt64Mult", TestSafeInt64Mult, NULL, NULL, NULL); // // Execute the tests. diff --git a/UnitTestPkg/Include/Library/UnitTestLib.h b/UnitTestPkg/Include/Library/UnitTestLib.h index be185727134..d9724640f4d 100644 --- a/UnitTestPkg/Include/Library/UnitTestLib.h +++ b/UnitTestPkg/Include/Library/UnitTestLib.h @@ -26,9 +26,9 @@ EFI_STATUS EFIAPI InitUnitTestFramework ( OUT UNIT_TEST_FRAMEWORK **Framework, - IN CHAR16 *Title, - IN CHAR16 *ShortTitle, - IN CHAR16 *VersionString + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString ); /* @@ -49,8 +49,8 @@ EFIAPI CreateUnitTestSuite ( OUT UNIT_TEST_SUITE **Suite, IN UNIT_TEST_FRAMEWORK *Framework, - IN CHAR16 *Title, - IN CHAR16 *Package, + IN CHAR8 *Title, + IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL ); @@ -73,8 +73,8 @@ EFI_STATUS EFIAPI AddTestCase ( IN UNIT_TEST_SUITE *Suite, - IN CHAR16 *Description, - IN CHAR16 *ClassName, + IN CHAR8 *Description, + IN CHAR8 *ClassName, IN UNIT_TEST_FUNCTION Func, IN UNIT_TEST_PREREQ PreReq OPTIONAL, IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, diff --git a/UnitTestPkg/Include/UnitTestTypes.h b/UnitTestPkg/Include/UnitTestTypes.h index d1f9e86c248..7b499b5460d 100644 --- a/UnitTestPkg/Include/UnitTestTypes.h +++ b/UnitTestPkg/Include/UnitTestTypes.h @@ -115,11 +115,11 @@ VOID typedef struct { - CHAR16 *Description; - CHAR16 *ClassName; //can't have spaces and should be short - CHAR16 *Log; + CHAR8 *Description; + CHAR8 *ClassName; //can't have spaces and should be short + CHAR8 *Log; FAILURE_TYPE FailureType; - CHAR16 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; UNIT_TEST_STATUS Result; UNIT_TEST_FUNCTION RunTest; @@ -135,8 +135,8 @@ typedef struct { } UNIT_TEST_LIST_ENTRY; typedef struct { - CHAR16 *Title; - CHAR16 *Package; + CHAR8 *Title; + CHAR8 *Package; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; UNIT_TEST_SUITE_SETUP Setup; UNIT_TEST_SUITE_TEARDOWN Teardown; @@ -150,10 +150,10 @@ typedef struct { } UNIT_TEST_SUITE_LIST_ENTRY; typedef struct { - CHAR16 *Title; - CHAR16 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. - CHAR16 *VersionString; - CHAR16 *Log; + CHAR8 *Title; + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR8 *VersionString; + CHAR8 *Log; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY EFI_TIME StartTime; @@ -172,10 +172,10 @@ typedef struct { UINT32 Size; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. - CHAR16 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; FAILURE_TYPE FailureType; UNIT_TEST_STATUS Result; - // CHAR16 Log[]; + // CHAR8 Log[]; } UNIT_TEST_SAVE_TEST; typedef struct @@ -195,7 +195,7 @@ typedef struct BOOLEAN HasSavedContext; // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. - // CHAR16 Log[]; // NOTE: Not yet implemented!! + // CHAR8 Log[]; // NOTE: Not yet implemented!! } UNIT_TEST_SAVE_HEADER; #pragma pack () diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c index a3ca011fd22..7d5dcb6fae0 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c @@ -54,7 +54,7 @@ UpdateTestFromSave ( STATIC BOOLEAN IsFrameworkShortNameValid ( - IN CHAR16 *ShortTitleString + IN CHAR8 *ShortTitleString ) { // TODO: Finish this function. @@ -63,19 +63,19 @@ IsFrameworkShortNameValid ( STATIC -CHAR16* +CHAR8* AllocateAndCopyString ( - IN CHAR16 *StringToCopy + IN CHAR8 *StringToCopy ) { - CHAR16 *NewString = NULL; + CHAR8 *NewString = NULL; UINTN NewStringLength; - NewStringLength = StrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; - NewString = AllocatePool( NewStringLength * sizeof( CHAR16 ) ); + NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; + NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); if (NewString != NULL) { - StrCpyS( NewString, NewStringLength, StringToCopy ); + AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); } return NewString; @@ -92,8 +92,8 @@ SetFrameworkFingerprint ( MD5Init( &mFingerprintCtx ); // For this one we'll just use the title and version as the unique fingerprint. - MD5Update( &mFingerprintCtx, Framework->Title, (StrLen( Framework->Title ) * sizeof( CHAR16 )) ); - MD5Update( &mFingerprintCtx, Framework->VersionString, (StrLen( Framework->VersionString ) * sizeof( CHAR16 )) ); + MD5Update( &mFingerprintCtx, Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); + MD5Update( &mFingerprintCtx, Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); MD5Final( &mFingerprintCtx, &Framework->Fingerprint[0] ); return; @@ -112,8 +112,8 @@ SetSuiteFingerprint ( // For this one, we'll use the fingerprint from the framework, and the title of the suite. MD5Update( &mFingerprintCtx, &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - MD5Update( &mFingerprintCtx, Suite->Title, (StrLen( Suite->Title ) * sizeof( CHAR16 )) ); - MD5Update(&mFingerprintCtx, Suite->Package, (StrLen(Suite->Package) * sizeof(CHAR16))); + MD5Update( &mFingerprintCtx, Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); + MD5Update(&mFingerprintCtx, Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8))); MD5Final( &mFingerprintCtx, &Suite->Fingerprint[0] ); return; @@ -132,8 +132,8 @@ SetTestFingerprint ( // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. MD5Update( &mFingerprintCtx, &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - MD5Update( &mFingerprintCtx, Test->Description, (StrLen( Test->Description ) * sizeof( CHAR16 )) ); - MD5Update(&mFingerprintCtx, Test->ClassName, (StrLen(Test->ClassName) * sizeof(CHAR16))); + MD5Update( &mFingerprintCtx, Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); + MD5Update(&mFingerprintCtx, Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8))); MD5Final( &mFingerprintCtx, &Test->Fingerprint[0] ); return; @@ -201,9 +201,9 @@ EFI_STATUS EFIAPI InitUnitTestFramework ( OUT UNIT_TEST_FRAMEWORK **Framework, - IN CHAR16 *Title, - IN CHAR16 *ShortTitle, - IN CHAR16 *VersionString + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString ) { EFI_STATUS Status = EFI_SUCCESS; @@ -288,8 +288,8 @@ EFIAPI CreateUnitTestSuite ( OUT UNIT_TEST_SUITE **Suite, IN UNIT_TEST_FRAMEWORK *Framework, - IN CHAR16 *Title, - IN CHAR16 *Package, + IN CHAR8 *Title, + IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL ) @@ -359,8 +359,8 @@ EFI_STATUS EFIAPI AddTestCase ( IN UNIT_TEST_SUITE *Suite, - IN CHAR16 *Description, - IN CHAR16 *ClassName, + IN CHAR8 *Description, + IN CHAR8 *ClassName, IN UNIT_TEST_FUNCTION Func, IN UNIT_TEST_PREREQ PreReq OPTIONAL, IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, @@ -458,7 +458,7 @@ RunTestSuite ( } DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %s\n", Suite->Title)); + DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); if (Suite->Setup != NULL) @@ -477,7 +477,7 @@ RunTestSuite ( ParentFramework->CurrentTest = Test; DEBUG((DEBUG_VERBOSE, "*********************************************************\n")); - DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %s:\n", Test->Description)); + DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %a:\n", Test->Description)); DEBUG((DEBUG_VERBOSE, "**********************************************************\n")); // @@ -633,7 +633,7 @@ UpdateTestFromSave ( Test->Result = MatchingTest->Result; Test->FailureType = MatchingTest->FailureType; - StrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + AsciiStrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); // If there is a log string associated, grab that. // We can tell that there's a log string because the "size" will be larger than @@ -717,7 +717,7 @@ SerializeState ( if (UnitTest->Log != NULL) { // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (StrLen( UnitTest->Log ) + 1) * sizeof( CHAR16 ); + LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); ASSERT( LogSize < MAX_UINT32 ); TotalSize += (UINT32)LogSize; } @@ -774,7 +774,7 @@ SerializeState ( // Save the result. TestSaveData->Result = UnitTest->Result; TestSaveData->FailureType = UnitTest->FailureType; - StrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + AsciiStrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); // If there is a log, save the log. @@ -782,7 +782,7 @@ SerializeState ( if (UnitTest->Log != NULL) { // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (StrLen( UnitTest->Log ) + 1) * sizeof( CHAR16 ); + LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); CopyMem( FloatingPointer, UnitTest->Log, LogSize ); FloatingPointer += LogSize; } diff --git a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c index fe764d015ef..e793a4e0d06 100644 --- a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -71,7 +71,7 @@ STATIC EFI_STATUS AddStringToUnitTestLog ( IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR16 *String + IN CONST CHAR8 *String ) { EFI_STATUS Status; @@ -97,7 +97,7 @@ AddStringToUnitTestLog ( return EFI_OUT_OF_RESOURCES; } - Status = StrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER/ sizeof(CHAR16), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); + Status = AsciiStrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER / sizeof(CHAR8), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); if(EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); @@ -111,8 +111,8 @@ STATIC EFI_STATUS AddUnitTestFailure( IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR16 *FailureMessage, - FAILURE_TYPE FailureType + IN CONST CHAR8 *FailureMessage, + IN FAILURE_TYPE FailureType ) { // @@ -124,7 +124,7 @@ AddUnitTestFailure( } UnitTest->FailureType = FailureType; - StrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); return EFI_SUCCESS; } @@ -139,8 +139,8 @@ VOID EFIAPI UnitTestLogInit ( IN OUT UNIT_TEST *Test, -IN UINT8 *Buffer, -IN UINTN BufferSize +IN UINT8 *Buffer, +IN UINTN BufferSize ) { // @@ -181,7 +181,7 @@ UnitTestLog ( ) { CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CHAR16 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; CONST CHAR8 *LogTypePrefix = NULL; VA_LIST Marker; UINTN LogLevel = (UINTN) PcdGet32(UnitTestLogLevel); @@ -210,7 +210,7 @@ UnitTestLog ( // Convert the message to an ASCII String // VA_START (Marker, Format); - UnicodeVSPrintAsciiFormat( LogString, sizeof( LogString ), NewFormatString, Marker ); + AsciiVSPrint( LogString, sizeof( LogString ), NewFormatString, Marker ); VA_END (Marker); // @@ -225,12 +225,12 @@ VOID EFIAPI UnitTestLogFailure( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - FAILURE_TYPE FailureType, + IN FAILURE_TYPE FailureType, IN CONST CHAR8 *Format, ... ) { - CHAR16 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; VA_LIST Marker; @@ -238,7 +238,7 @@ UnitTestLogFailure( // Convert the message to an ASCII String // VA_START(Marker, Format); - UnicodeVSPrintAsciiFormat(LogString, sizeof(LogString), Format, Marker); + AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); VA_END(Marker); // diff --git a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c index aacea4a79ad..959ff50d240 100644 --- a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c +++ b/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c @@ -146,8 +146,8 @@ OutputUnitTestFrameworkReport( INTN SNotRun = 0; DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); - DEBUG((DEBUG_INFO, " SUITE: %s\n", Suite->UTS.Title)); - DEBUG((DEBUG_INFO, " PACKAGE: %s\n", Suite->UTS.Package)); + DEBUG((DEBUG_INFO, " SUITE: %a\n", Suite->UTS.Title)); + DEBUG((DEBUG_INFO, " PACKAGE: %a\n", Suite->UTS.Package)); DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); // @@ -159,8 +159,8 @@ OutputUnitTestFrameworkReport( { DEBUG((DEBUG_INFO, "*********************************************************\n")); - DEBUG((DEBUG_INFO, " CLASS NAME: %s\n", Test->UT.ClassName)); - DEBUG((DEBUG_INFO, " TEST: %s\n", Test->UT.Description)); + DEBUG((DEBUG_INFO, " CLASS NAME: %a\n", Test->UT.ClassName)); + DEBUG((DEBUG_INFO, " TEST: %a\n", Test->UT.Description)); DEBUG((DEBUG_INFO, " STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ))); DEBUG((DEBUG_INFO, " FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType))); DEBUG((DEBUG_INFO, " FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage)); @@ -170,7 +170,7 @@ OutputUnitTestFrameworkReport( DEBUG((DEBUG_INFO, " LOG:\n")); // NOTE: This has to be done directly because all of the other // "formatted" print statements have caps on the string size. - DEBUG((DEBUG_INFO, "%s", Test->UT.Log)); + DEBUG((DEBUG_INFO, "%a", Test->UT.Log)); } switch (Test->UT.Result) diff --git a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c index 45ac05688a3..a1ff5ae4130 100644 --- a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c +++ b/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c @@ -9,6 +9,7 @@ Copyright (c) Microsoft #include #include #include +#include #include #include @@ -121,6 +122,8 @@ OutputUnitTestFrameworkReport( INTN Failed = 0; INTN NotRun = 0; UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + UINT16 *LogString = NULL; + UINTN LogStringLength = 0; if (Framework == NULL) { @@ -146,8 +149,8 @@ OutputUnitTestFrameworkReport( INTN SNotRun = 0; Print( L"/////////////////////////////////////////////////////////\n" ); - Print( L" SUITE: %s\n", Suite->UTS.Title ); - Print( L" PACKAGE: %s\n", Suite->UTS.Package); + Print( L" SUITE: %a\n", Suite->UTS.Title ); + Print( L" PACKAGE: %a\n", Suite->UTS.Package); Print( L"/////////////////////////////////////////////////////////\n" ); // @@ -159,18 +162,28 @@ OutputUnitTestFrameworkReport( { Print (L"*********************************************************\n" ); - Print (L" CLASS NAME: %s\n", Test->UT.ClassName); - Print( L" TEST: %s\n", Test->UT.Description ); + Print (L" CLASS NAME: %a\n", Test->UT.ClassName); + Print( L" TEST: %a\n", Test->UT.Description ); Print( L" STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ) ); Print( L" FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType)); Print( L" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); if (Test->UT.Log != NULL) { + // Make sure that we can expand the string into the unicode buffer. + if (LogStringLength <= AsciiStrnLenS( Test->UT.Log, MAX_UINT32 )) { + LogStringLength = AsciiStrnLenS( Test->UT.Log, MAX_UINT32 ) + 1; + if (LogString) { + FreePool( LogString ); + } + LogString = AllocatePool( LogStringLength * sizeof(CHAR16) ); + } + AsciiStrToUnicodeStrS( Test->UT.Log, LogString, LogStringLength ); + Print( L" LOG:\n" ); // NOTE: This has to be done directly because all of the other // "formatted" print statements have caps on the string size. - gST->ConOut->OutputString( gST->ConOut, Test->UT.Log ); + gST->ConOut->OutputString( gST->ConOut, LogString ); } switch (Test->UT.Result) @@ -204,5 +217,9 @@ OutputUnitTestFrameworkReport( Print( L" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun) ); Print( L"=========================================================\n" ); + if (LogString) { + FreePool( LogString ); + } + return EFI_SUCCESS; } \ No newline at end of file diff --git a/UnitTestPkg/ReadMe.md b/UnitTestPkg/ReadMe.md index 0c6d327bd5f..5a5dcad94f1 100644 --- a/UnitTestPkg/ReadMe.md +++ b/UnitTestPkg/ReadMe.md @@ -110,16 +110,12 @@ These strings are copied internally to the Framework, so using stack-allocated o In the 'SampleUnitTestApp', the module name is used as the short name, so the init looks like this. ```c -CHAR16 ShortName[100]; -ShortName[0] = L'\0'; - -UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); -DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); +DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); // // Start setting up the test framework for running the tests. // -Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, ShortName, UNIT_TEST_APP_VERSION ); +Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); ``` The `&Fw` returned here is the handle to the Framework. If it's successfully returned, we can start adding diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 66b1c2af5ac..4c3d273d74d 100644 --- a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -24,10 +24,11 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include +#include -#define UNIT_TEST_APP_NAME L"Sample Unit Test Library Application" -#define UNIT_TEST_APP_VERSION L"0.1" +#define UNIT_TEST_APP_NAME "Sample Unit Test Library Application" +#define UNIT_TEST_APP_VERSION "0.1" BOOLEAN mSampleGlobalTestBoolean = FALSE; @@ -94,6 +95,10 @@ OnePlusOneShouldEqualTwo ( C = A + B; UT_ASSERT_EQUAL(C, 2); + + UT_LOG_WARNING("This should not be. %a", "This also should not be.\n"); + UT_LOG_WARNING("This is also crap.\n"); + return UNIT_TEST_PASSED; } // OnePlusOneShouldEqualTwo() @@ -157,16 +162,13 @@ SampleUnitTestApp ( EFI_STATUS Status; UNIT_TEST_FRAMEWORK *Fw = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; - CHAR16 ShortName[100]; - ShortName[0] = L'\0'; - UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); - DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, ShortName, UNIT_TEST_APP_VERSION ); + Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -176,27 +178,27 @@ SampleUnitTestApp ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 7c94e20e70f..7d28eacb76c 100644 --- a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -26,8 +26,8 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include -#define UNIT_TEST_PEIM_NAME L"Sample Unit Test Library PEIM" -#define UNIT_TEST_PEIM_VERSION L"0.1" +#define UNIT_TEST_PEIM_NAME "Sample Unit Test Library PEIM" +#define UNIT_TEST_PEIM_VERSION "0.1" BOOLEAN mSampleGlobalTestBoolean = FALSE; @@ -159,16 +159,13 @@ SampleUnitTestPeim ( EFI_STATUS Status; UNIT_TEST_FRAMEWORK *Fw = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; - CHAR16 ShortName[100]; - ShortName[0] = L'\0'; - UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); - DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_PEIM_NAME, ShortName, UNIT_TEST_PEIM_VERSION ); + Status = InitUnitTestFramework( &Fw, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -178,27 +175,27 @@ SampleUnitTestPeim ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index c439aabc37b..bf04ad1f585 100644 --- a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -26,8 +26,8 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include -#define UNIT_TEST_SMM_NAME L"Sample Unit Test Library SMM" -#define UNIT_TEST_SMM_VERSION L"0.1" +#define UNIT_TEST_SMM_NAME "Sample Unit Test Library SMM" +#define UNIT_TEST_SMM_VERSION "0.1" BOOLEAN mSampleGlobalTestBoolean = FALSE; @@ -157,16 +157,13 @@ SampleUnitTestSmm ( EFI_STATUS Status; UNIT_TEST_FRAMEWORK *Fw = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; - CHAR16 ShortName[100]; - ShortName[0] = L'\0'; - UnicodeSPrint(&ShortName[0], sizeof(ShortName), L"%a", gEfiCallerBaseName); - DEBUG(( DEBUG_INFO, "%s v%s\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_SMM_NAME, ShortName, UNIT_TEST_SMM_VERSION ); + Status = InitUnitTestFramework( &Fw, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -176,27 +173,27 @@ SampleUnitTestSmm ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, L"Global Variable Tests", L"Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, L"You should be able to change a global BOOLEAN", L"Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, L"You should be able to change a global pointer", L"Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. From d706274af1e1efcddca8d99e7942bba77568258e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 10:32:55 -0800 Subject: [PATCH 181/384] Swap MD5 for CRC32. Hopefully good enough for a fingerprint. --- UnitTestPkg/Include/UnitTestTypes.h | 2 +- UnitTestPkg/Library/UnitTestLib/Md5.c | 347 ------------------ UnitTestPkg/Library/UnitTestLib/Md5.h | 69 ---- UnitTestPkg/Library/UnitTestLib/UnitTestLib.c | 31 +- .../Library/UnitTestLib/UnitTestLibDxe.inf | 1 - .../Library/UnitTestLib/UnitTestLibPei.inf | 1 - .../Library/UnitTestLib/UnitTestLibSmm.inf | 1 - 7 files changed, 15 insertions(+), 437 deletions(-) delete mode 100644 UnitTestPkg/Library/UnitTestLib/Md5.c delete mode 100644 UnitTestPkg/Library/UnitTestLib/Md5.h diff --git a/UnitTestPkg/Include/UnitTestTypes.h b/UnitTestPkg/Include/UnitTestTypes.h index 7b499b5460d..0b0238757af 100644 --- a/UnitTestPkg/Include/UnitTestTypes.h +++ b/UnitTestPkg/Include/UnitTestTypes.h @@ -19,7 +19,7 @@ ///================================================================================================ #define UNIT_TEST_MAX_STRING_LENGTH (120) -#define UNIT_TEST_FINGERPRINT_SIZE (16) // Hardcoded to MD5_HASHSIZE. +#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. #define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) typedef UINT32 UNIT_TEST_STATUS; diff --git a/UnitTestPkg/Library/UnitTestLib/Md5.c b/UnitTestPkg/Library/UnitTestLib/Md5.c deleted file mode 100644 index 16e91f84058..00000000000 --- a/UnitTestPkg/Library/UnitTestLib/Md5.c +++ /dev/null @@ -1,347 +0,0 @@ -/** @file - Implementation of MD5 algorithm. - -Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -#include "Md5.h" - -CONST UINT32 Md5_Data[][2] = { - { 0, 1 }, - { 1, 5 }, - { 5, 3 }, - { 0, 7 } -}; - -CONST UINT32 Md5_S[][4] = { - { 7, 22, 17, 12 }, - { 5, 20, 14, 9 }, - { 4, 23, 16 ,11 }, - { 6, 21, 15, 10 }, -}; - -CONST UINT32 Md5_T[] = { - 0xD76AA478, 0xE8C7B756, 0x242070DB, 0xC1BDCEEE, - 0xF57C0FAF, 0x4787C62A, 0xA8304613, 0xFD469501, - 0x698098D8, 0x8B44F7AF, 0xFFFF5BB1, 0x895CD7BE, - 0x6B901122, 0xFD987193, 0xA679438E, 0x49B40821, - 0xF61E2562, 0xC040B340, 0x265E5A51, 0xE9B6C7AA, - 0xD62F105D, 0x02441453, 0xD8A1E681, 0xE7D3FBC8, - 0x21E1CDE6, 0xC33707D6, 0xF4D50D87, 0x455A14ED, - 0xA9E3E905, 0xFCEFA3F8, 0x676F02D9, 0x8D2A4C8A, - 0xFFFA3942, 0x8771F681, 0x6D9D6122, 0xFDE5380C, - 0xA4BEEA44, 0x4BDECFA9, 0xF6BB4B60, 0xBEBFBC70, - 0x289B7EC6, 0xEAA127FA, 0xD4EF3085, 0x04881D05, - 0xD9D4D039, 0xE6DB99E5, 0x1FA27CF8, 0xC4AC5665, - 0xF4292244, 0x432AFF97, 0xAB9423A7, 0xFC93A039, - 0x655B59C3, 0x8F0CCC92, 0xFFEFF47D, 0x85845DD1, - 0x6FA87E4F, 0xFE2CE6E0, 0xA3014314, 0x4E0811A1, - 0xF7537E82, 0xBD3AF235, 0x2AD7D2BB, 0xEB86D391 -}; - -CONST UINT8 Md5HashPadding[] = -{ - 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, - 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 -}; - -// -// ROTATE_LEFT rotates x left n bits. -// -#define ROTATE_LEFT(x, n) (((x) << (n)) | ((x) >> (32 - (n)))) - -#define SA MedStates[Index2 & 3] -#define SB MedStates[(Index2 + 1) & 3] -#define SC MedStates[(Index2 + 2) & 3] -#define SD MedStates[(Index2 + 3) & 3] - -/** - Tf1 is one basic MD5 transform function. - - @param[in] A A 32-bit quantity. - @param[in] B A 32-bit quantity. - @param[in] C A 32-bit quantity. - - @return Output was produced as a 32-bit quantity based on the - three 32-bit input quantity. -**/ -UINT32 -Tf1 ( - IN UINT32 A, - IN UINT32 B, - IN UINT32 C - ) -{ - return (A & B) | (~A & C); -} - -/** - Tf2 is one basic MD5 transform function. - - @param[in] A A 32-bit quantity. - @param[in] B A 32-bit quantity. - @param[in] C A 32-bit quantity. - - @return Output was produced as a 32-bit quantity based on the - three 32-bit input quantity. -**/ -UINT32 -Tf2 ( - IN UINT32 A, - IN UINT32 B, - IN UINT32 C - ) -{ - return (A & C) | (B & ~C); -} - -/** - Tf3 is one basic MD5 transform function. - - @param[in] A A 32-bit quantity. - @param[in] B A 32-bit quantity. - @param[in] C A 32-bit quantity. - - @return Output was produced as a 32-bit quantity based on the - three 32-bit input quantity. -**/ -UINT32 -Tf3 ( - IN UINT32 A, - IN UINT32 B, - IN UINT32 C - ) -{ - return A ^ B ^ C; -} - -/** - Tf4 is one basic MD5 transform function. - - @param[in] A A 32-bit quantity. - @param[in] B A 32-bit quantity. - @param[in] C A 32-bit quantity. - - @return Output was produced as a 32-bit quantity based on the - three 32-bit input quantity. -**/ -UINT32 -Tf4 ( - IN UINT32 A, - IN UINT32 B, - IN UINT32 C - ) -{ - return B ^ (A | ~C); -} - -typedef -UINT32 -(*MD5_TRANSFORM_FUNC) ( - IN UINT32 A, - IN UINT32 B, - IN UINT32 C - ); - -CONST MD5_TRANSFORM_FUNC Md5_F[] = { - Tf1, - Tf2, - Tf3, - Tf4 -}; - -/** - Perform the MD5 transform on 64 bytes data segment. - - @param[in, out] Md5Ctx It includes the data segment for Md5 transform. -**/ -VOID -MD5Transform ( - IN OUT MD5_CTX *Md5Ctx - ) -{ - UINT32 Index1; - UINT32 Index2; - UINT32 MedStates[MD5_HASHSIZE >> 2]; - UINT32 *Data; - UINT32 IndexD; - UINT32 IndexT; - - Data = (UINT32 *) Md5Ctx->M; - - // - // Copy MD5 states to MedStates - // - CopyMem (MedStates, Md5Ctx->States, MD5_HASHSIZE); - - IndexT = 0; - for (Index1 = 0; Index1 < 4; Index1++) { - IndexD = Md5_Data[Index1][0]; - for (Index2 = 16; Index2 > 0; Index2--) { - SA += (*Md5_F[Index1]) (SB, SC, SD) + Data[IndexD] + Md5_T[IndexT]; - SA = ROTATE_LEFT (SA, Md5_S[Index1][Index2 & 3]); - SA += SB; - - IndexD += Md5_Data[Index1][1]; - IndexD &= 15; - - IndexT++; - } - } - - for (Index1 = 0; Index1 < 4; Index1++) { - Md5Ctx->States[Index1] += MedStates[Index1]; - } -} - -/** - Copy data segment into the M field of MD5_CTX structure for later transform. - If the length of data segment is larger than 64 bytes, then does the transform - immediately and the generated Md5 code is stored in the States field of MD5_CTX - data struct for later accumulation. - All of Md5 code generated for the sequential 64-bytes data segaments are be - accumulated in MD5Final() function. - - @param[in, out] Md5Ctx The data structure of storing the original data - segment and the final result. - @param[in] Data The data wanted to be transformed. - @param[in] DataLen The length of data. -**/ -VOID -MD5UpdateBlock ( - IN OUT MD5_CTX *Md5Ctx, - IN CONST UINT8 *Data, - IN UINTN DataLen - ) -{ - UINTN Limit; - - for (Limit = 64 - Md5Ctx->Count; DataLen >= 64 - Md5Ctx->Count; Limit = 64) { - CopyMem (Md5Ctx->M + Md5Ctx->Count, (VOID *)Data, Limit); - MD5Transform (Md5Ctx); - - Md5Ctx->Count = 0; - Data += Limit; - DataLen -= Limit; - } - - CopyMem (Md5Ctx->M + Md5Ctx->Count, (VOID *)Data, DataLen); - Md5Ctx->Count += DataLen; -} - -/** - Initialize four 32-bits chaining variables and use them to do the Md5 transform. - - @param[out] Md5Ctx The data structure of Md5. - - @retval EFI_SUCCESS Initialization is ok. -**/ -EFI_STATUS -MD5Init ( - OUT MD5_CTX *Md5Ctx - ) -{ - ZeroMem (Md5Ctx, sizeof (*Md5Ctx)); - - // - // Set magic initialization constants. - // - Md5Ctx->States[0] = 0x67452301; - Md5Ctx->States[1] = 0xefcdab89; - Md5Ctx->States[2] = 0x98badcfe; - Md5Ctx->States[3] = 0x10325476; - - return EFI_SUCCESS; -} - -/** - the external interface of Md5 algorithm - - @param[in, out] Md5Ctx The data structure of storing the original data - segment and the final result. - @param[in] Data The data wanted to be transformed. - @param[in] DataLen The length of data. - - @retval EFI_SUCCESS The transform is ok. - @retval Others Other errors as indicated. -**/ -EFI_STATUS -MD5Update ( - IN OUT MD5_CTX *Md5Ctx, - IN VOID *Data, - IN UINTN DataLen - ) -{ - if (EFI_ERROR (Md5Ctx->Status)) { - return Md5Ctx->Status; - } - - MD5UpdateBlock (Md5Ctx, (CONST UINT8 *) Data, DataLen); - Md5Ctx->Length += DataLen; - return EFI_SUCCESS; -} - -/** - Accumulate the MD5 value of every data segment and generate the finial - result according to MD5 algorithm. - - @param[in, out] Md5Ctx The data structure of storing the original data - segment and the final result. - @param[out] HashVal The final 128-bits output. - - @retval EFI_SUCCESS The transform is ok. - @retval Others Other errors as indicated. -**/ -EFI_STATUS -MD5Final ( - IN OUT MD5_CTX *Md5Ctx, - OUT UINT8 *HashVal - ) -{ - UINTN PadLength; - - if (Md5Ctx->Status == EFI_ALREADY_STARTED) { - // - // Store Hashed value & Zeroize sensitive context information. - // - CopyMem (HashVal, (UINT8 *) Md5Ctx->States, MD5_HASHSIZE); - ZeroMem ((UINT8 *)Md5Ctx, sizeof (*Md5Ctx)); - - return EFI_SUCCESS; - } - - if (EFI_ERROR (Md5Ctx->Status)) { - return Md5Ctx->Status; - } - - PadLength = Md5Ctx->Count >= 56 ? 120 : 56; - PadLength -= Md5Ctx->Count; - MD5UpdateBlock (Md5Ctx, Md5HashPadding, PadLength); - Md5Ctx->Length = LShiftU64 (Md5Ctx->Length, 3); - MD5UpdateBlock (Md5Ctx, (CONST UINT8 *) &Md5Ctx->Length, 8); - - ZeroMem (Md5Ctx->M, sizeof (Md5Ctx->M)); - Md5Ctx->Length = 0; - Md5Ctx->Status = EFI_ALREADY_STARTED; - return MD5Final (Md5Ctx, HashVal); -} - diff --git a/UnitTestPkg/Library/UnitTestLib/Md5.h b/UnitTestPkg/Library/UnitTestLib/Md5.h deleted file mode 100644 index 320f443ac01..00000000000 --- a/UnitTestPkg/Library/UnitTestLib/Md5.h +++ /dev/null @@ -1,69 +0,0 @@ -/** @file - Header file for Md5. - -Copyright (c) 2004 - 2008, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef _MD5_H_ -#define _MD5_H_ - -#define MD5_HASHSIZE 16 - -typedef struct _MD5_CTX { - EFI_STATUS Status; - UINT64 Length; - UINT32 States[MD5_HASHSIZE / sizeof (UINT32)]; - UINT8 M[64]; - UINTN Count; -} MD5_CTX; - -/** - Initialize four 32-bits chaining variables and use them to do the Md5 transform. - - @param[out] Md5Ctx The data structure of Md5. - - @retval EFI_SUCCESS Initialization is ok. -**/ -EFI_STATUS -MD5Init ( - OUT MD5_CTX *Md5Ctx - ); - -/** - the external interface of Md5 algorithm - - @param[in, out] Md5Ctx The data structure of storing the original data - segment and the final result. - @param[in] Data The data wanted to be transformed. - @param[in] DataLen The length of data. - - @retval EFI_SUCCESS The transform is ok. - @retval Others Other errors as indicated. -**/ -EFI_STATUS -MD5Update ( - IN OUT MD5_CTX *Md5Ctx, - IN VOID *Data, - IN UINTN DataLen - ); - -/** - Accumulate the MD5 value of every data segment and generate the finial - result according to MD5 algorithm. - - @param[in, out] Md5Ctx The data structure of storing the original data - segment and the final result. - @param[out] HashVal The final 128-bits output. - - @retval EFI_SUCCESS The transform is ok. - @retval Others Other errors as indicated. -**/ -EFI_STATUS -MD5Final ( - IN OUT MD5_CTX *Md5Ctx, - OUT UINT8 *HashVal - ); - -#endif diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c index 7d5dcb6fae0..2e70f73217a 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c @@ -18,9 +18,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#include "Md5.h" - -MD5_CTX mFingerprintCtx; // Prototyped here so that it can be included near the functions that // it logically goes with. @@ -89,13 +86,13 @@ SetFrameworkFingerprint ( IN UNIT_TEST_FRAMEWORK *Framework ) { - MD5Init( &mFingerprintCtx ); + UINT32 NewFingerprint; // For this one we'll just use the title and version as the unique fingerprint. - MD5Update( &mFingerprintCtx, Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); - MD5Update( &mFingerprintCtx, Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); + NewFingerprint = CalculateCrc32( Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); - MD5Final( &mFingerprintCtx, &Framework->Fingerprint[0] ); + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); return; } // SetFrameworkFingerprint() @@ -108,14 +105,14 @@ SetSuiteFingerprint ( IN UNIT_TEST_SUITE *Suite ) { - MD5Init( &mFingerprintCtx ); + UINT32 NewFingerprint; // For this one, we'll use the fingerprint from the framework, and the title of the suite. - MD5Update( &mFingerprintCtx, &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - MD5Update( &mFingerprintCtx, Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); - MD5Update(&mFingerprintCtx, Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8))); + NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); - MD5Final( &mFingerprintCtx, &Suite->Fingerprint[0] ); + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); return; } // SetSuiteFingerprint() @@ -128,14 +125,14 @@ SetTestFingerprint ( IN UNIT_TEST *Test ) { - MD5Init( &mFingerprintCtx ); + UINT32 NewFingerprint; // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. - MD5Update( &mFingerprintCtx, &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - MD5Update( &mFingerprintCtx, Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); - MD5Update(&mFingerprintCtx, Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8))); + NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); - MD5Final( &mFingerprintCtx, &Test->Fingerprint[0] ); + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); return; } // SetTestFingerprint() diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf index f29ff0cd2e4..86e6779c5c8 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf @@ -42,4 +42,3 @@ LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION [Sources] UnitTestLib.c - Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf index e9cdce949d6..ced85aca3d1 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -40,4 +40,3 @@ LIBRARY_CLASS = UnitTestLib|PEIM [Sources] UnitTestLib.c - Md5.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf index f5870c545f8..093fa6575b8 100644 --- a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf +++ b/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf @@ -41,4 +41,3 @@ LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER [Sources] UnitTestLib.c - Md5.c From f88bd23f6ae3e79cc28b485d1307b57b4c59b671 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 10:53:41 -0800 Subject: [PATCH 182/384] Remove unnecessary pragmas. --- UnitTestPkg/Include/UnitTestTypes.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/UnitTestPkg/Include/UnitTestTypes.h b/UnitTestPkg/Include/UnitTestTypes.h index 0b0238757af..a6eed7ecb21 100644 --- a/UnitTestPkg/Include/UnitTestTypes.h +++ b/UnitTestPkg/Include/UnitTestTypes.h @@ -166,7 +166,6 @@ typedef struct { // //Structures for the framework to serializing unit test status // -#pragma pack (1) typedef struct { @@ -198,6 +197,4 @@ typedef struct // CHAR8 Log[]; // NOTE: Not yet implemented!! } UNIT_TEST_SAVE_HEADER; -#pragma pack () - #endif \ No newline at end of file From 150b75850c95b79f9d26496b891bde7e33426682 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 11:56:09 -0800 Subject: [PATCH 183/384] Move the UnitTestPkg dependency to HOST-APPLICATION only. --- MdePkg/MdePkg.ci.yaml | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 10db2312572..3ce5c8056f4 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -23,11 +23,12 @@ ## options defined ci/Plugin/DependencyCheck "DependencyCheck": { "AcceptableDependencies": [ - "MdePkg/MdePkg.dec", - "UnitTestPkg/UnitTestPkg.dec" + "MdePkg/MdePkg.dec" ], # For host based unit tests - "AcceptableDependencies-HOST_APPLICATION":[], + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestPkg/UnitTestPkg.dec" + ], # For UEFI shell based apps "AcceptableDependencies-UEFI_APPLICATION":[], "IgnoreInf": [] From 58297b6665df5912873e6ad6891974199999cbed Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 12:07:38 -0800 Subject: [PATCH 184/384] Move all HostLibrary files into the Test directory. --- MdePkg/MdePkgTest.dsc | 18 +++++++++--------- .../HostLibrary/BaseLibHost/ARShiftU64.c | 0 .../HostLibrary/BaseLibHost/BaseLibHost.inf | 0 .../BaseLibHost/BaseLibHostNoAsm.inf | 0 .../HostLibrary/BaseLibHost/BitField.c | 0 .../{ => Test}/HostLibrary/BaseLibHost/Cache.c | 0 .../HostLibrary/BaseLibHost/CheckSum.c | 0 .../{ => Test}/HostLibrary/BaseLibHost/Cpu.c | 0 .../HostLibrary/BaseLibHost/CpuBreakpointGcc.c | 0 .../BaseLibHost/CpuBreakpointMsvc.c | 0 .../HostLibrary/BaseLibHost/CpuDeadLoop.c | 0 .../BaseLibHost/DivS64x64Remainder.c | 0 .../HostLibrary/BaseLibHost/DivU64x32.c | 0 .../BaseLibHost/DivU64x32Remainder.c | 0 .../BaseLibHost/DivU64x64Remainder.c | 0 .../HostLibrary/BaseLibHost/DummyRdRand.c | 0 .../HostLibrary/BaseLibHost/DummyReadTsc.c | 0 .../HostLibrary/BaseLibHost/GetPowerOfTwo32.c | 0 .../HostLibrary/BaseLibHost/GetPowerOfTwo64.c | 0 .../HostLibrary/BaseLibHost/HighBitSet32.c | 0 .../HostLibrary/BaseLibHost/HighBitSet64.c | 0 .../HostLibrary/BaseLibHost/Ia32/RdRand.nasm | 0 .../HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm | 0 .../HostLibrary/BaseLibHost/LRotU32.c | 0 .../HostLibrary/BaseLibHost/LRotU64.c | 0 .../HostLibrary/BaseLibHost/LShiftU64.c | 0 .../HostLibrary/BaseLibHost/Lfence.c | 0 .../HostLibrary/BaseLibHost/LinkedList.c | 0 .../HostLibrary/BaseLibHost/LongJump.c | 0 .../HostLibrary/BaseLibHost/LowBitSet32.c | 0 .../HostLibrary/BaseLibHost/LowBitSet64.c | 0 .../HostLibrary/BaseLibHost/Math64.c | 0 .../HostLibrary/BaseLibHost/ModU64x32.c | 0 .../HostLibrary/BaseLibHost/MultS64x64.c | 0 .../HostLibrary/BaseLibHost/MultU64x32.c | 0 .../HostLibrary/BaseLibHost/MultU64x64.c | 0 .../HostLibrary/BaseLibHost/RRotU32.c | 0 .../HostLibrary/BaseLibHost/RRotU64.c | 0 .../HostLibrary/BaseLibHost/RShiftU64.c | 0 .../HostLibrary/BaseLibHost/SafeString.c | 0 .../HostLibrary/BaseLibHost/SetJump.c | 0 .../HostLibrary/BaseLibHost/String.c | 0 .../HostLibrary/BaseLibHost/SwapBytes16.c | 0 .../HostLibrary/BaseLibHost/SwapBytes32.c | 0 .../HostLibrary/BaseLibHost/SwapBytes64.c | 0 .../HostLibrary/BaseLibHost/SwitchStackNull.c | 0 .../HostLibrary/BaseLibHost/Unaligned.c | 0 .../HostLibrary/BaseLibHost/X64/RdRand.nasm | 0 .../HostLibrary/BaseLibHost/X64/ReadTsc.nasm | 0 .../{ => Test}/HostLibrary/BaseLibHost/X86Cr.c | 0 .../BaseLibHost/X86DisablePaging64Null.c | 0 .../{ => Test}/HostLibrary/BaseLibHost/X86Dr.c | 0 .../HostLibrary/BaseLibHost/X86GdtrNull.c | 0 .../HostLibrary/BaseLibHost/X86IdtrNull.c | 0 .../BaseLibHost/X86MemoryFenceGcc.c | 0 .../BaseLibHost/X86MemoryFenceMsvc.c | 0 .../BaseLibHost/X86PatchInstruction.c | 0 .../HostLibrary/BaseLibHost/X86RdRand.c | 0 .../HostLibrary/BaseLibHost/X86SegmentNull.c | 0 .../BaseMemoryLibHost/BaseMemoryLibHost.c | 0 .../BaseMemoryLibHost/BaseMemoryLibHost.inf | 0 .../HostLibrary/DebugLibHost/DebugLibHost.c | 0 .../HostLibrary/DebugLibHost/DebugLibHost.inf | 0 .../MemoryAllocationLibHost.c | 0 .../MemoryAllocationLibHost.inf | 0 65 files changed, 9 insertions(+), 9 deletions(-) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/ARShiftU64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/BaseLibHost.inf (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/BitField.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Cache.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/CheckSum.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Cpu.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/CpuBreakpointGcc.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/CpuDeadLoop.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DivS64x64Remainder.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DivU64x32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DivU64x32Remainder.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DivU64x64Remainder.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DummyRdRand.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/DummyReadTsc.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/GetPowerOfTwo32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/GetPowerOfTwo64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/HighBitSet32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/HighBitSet64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Ia32/RdRand.nasm (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LRotU32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LRotU64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LShiftU64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Lfence.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LinkedList.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LongJump.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LowBitSet32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/LowBitSet64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Math64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/ModU64x32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/MultS64x64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/MultU64x32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/MultU64x64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/RRotU32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/RRotU64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/RShiftU64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SafeString.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SetJump.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/String.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SwapBytes16.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SwapBytes32.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SwapBytes64.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/SwitchStackNull.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/Unaligned.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X64/RdRand.nasm (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X64/ReadTsc.nasm (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86Cr.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86DisablePaging64Null.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86Dr.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86GdtrNull.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86IdtrNull.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86PatchInstruction.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86RdRand.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseLibHost/X86SegmentNull.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c (100%) rename MdePkg/{ => Test}/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf (100%) rename MdePkg/{ => Test}/HostLibrary/DebugLibHost/DebugLibHost.c (100%) rename MdePkg/{ => Test}/HostLibrary/DebugLibHost/DebugLibHost.inf (100%) rename MdePkg/{ => Test}/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c (100%) rename MdePkg/{ => Test}/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf (100%) diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/MdePkgTest.dsc index 2c4206e23a9..4179c6ff42c 100644 --- a/MdePkg/MdePkgTest.dsc +++ b/MdePkg/MdePkgTest.dsc @@ -18,10 +18,10 @@ [LibraryClasses] CmockaLib|CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf - BaseLib|MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf - BaseMemoryLib|MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf - DebugLib|MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf - MemoryAllocationLib|MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + BaseLib|MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf + BaseMemoryLib|MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf + DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf + MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf OsServiceLib|HostBasedUnitTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf @@ -47,11 +47,11 @@ #compile all host application components - MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf - MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf - MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf - MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf - MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf + MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf + MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf + MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf + MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf [BuildOptions] diff --git a/MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/ARShiftU64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf b/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/BaseLibHost.inf rename to MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf diff --git a/MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf b/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf rename to MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf diff --git a/MdePkg/HostLibrary/BaseLibHost/BitField.c b/MdePkg/Test/HostLibrary/BaseLibHost/BitField.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/BitField.c rename to MdePkg/Test/HostLibrary/BaseLibHost/BitField.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Cache.c b/MdePkg/Test/HostLibrary/BaseLibHost/Cache.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Cache.c rename to MdePkg/Test/HostLibrary/BaseLibHost/Cache.c diff --git a/MdePkg/HostLibrary/BaseLibHost/CheckSum.c b/MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/CheckSum.c rename to MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Cpu.c b/MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Cpu.c rename to MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/CpuBreakpointGcc.c rename to MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c rename to MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c diff --git a/MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/CpuDeadLoop.c rename to MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DivS64x64Remainder.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DivU64x32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DivU64x32Remainder.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DivU64x64Remainder.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c b/MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DummyRdRand.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c diff --git a/MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c b/MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/DummyReadTsc.c rename to MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c diff --git a/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c b/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c b/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/GetPowerOfTwo64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c b/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/HighBitSet32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c b/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/HighBitSet64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Ia32/RdRand.nasm rename to MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm diff --git a/MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm rename to MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm diff --git a/MdePkg/HostLibrary/BaseLibHost/LRotU32.c b/MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LRotU32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LRotU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LRotU64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LShiftU64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Lfence.c b/MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Lfence.c rename to MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LinkedList.c b/MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LinkedList.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LongJump.c b/MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LongJump.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c b/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LowBitSet32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/LowBitSet64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Math64.c b/MdePkg/Test/HostLibrary/BaseLibHost/Math64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Math64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/Math64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/ModU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/ModU64x32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/MultS64x64.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/MultS64x64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/MultU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/MultU64x32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/MultU64x64.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/MultU64x64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/RRotU32.c b/MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/RRotU32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/RRotU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/RRotU64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/RShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/RShiftU64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SafeString.c b/MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SafeString.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SetJump.c b/MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SetJump.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c diff --git a/MdePkg/HostLibrary/BaseLibHost/String.c b/MdePkg/Test/HostLibrary/BaseLibHost/String.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/String.c rename to MdePkg/Test/HostLibrary/BaseLibHost/String.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SwapBytes16.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SwapBytes32.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SwapBytes64.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c diff --git a/MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/SwitchStackNull.c rename to MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c diff --git a/MdePkg/HostLibrary/BaseLibHost/Unaligned.c b/MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/Unaligned.c rename to MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X64/RdRand.nasm rename to MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm diff --git a/MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X64/ReadTsc.nasm rename to MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm diff --git a/MdePkg/HostLibrary/BaseLibHost/X86Cr.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86Cr.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86DisablePaging64Null.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86Dr.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86Dr.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86GdtrNull.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86IdtrNull.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86PatchInstruction.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86RdRand.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86RdRand.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c diff --git a/MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c similarity index 100% rename from MdePkg/HostLibrary/BaseLibHost/X86SegmentNull.c rename to MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c diff --git a/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c b/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c similarity index 100% rename from MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c rename to MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c diff --git a/MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf b/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf similarity index 100% rename from MdePkg/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf rename to MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf diff --git a/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c b/MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.c similarity index 100% rename from MdePkg/HostLibrary/DebugLibHost/DebugLibHost.c rename to MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.c diff --git a/MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf b/MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf similarity index 100% rename from MdePkg/HostLibrary/DebugLibHost/DebugLibHost.inf rename to MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf diff --git a/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c b/MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c similarity index 100% rename from MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c rename to MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c diff --git a/MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf b/MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf similarity index 100% rename from MdePkg/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf rename to MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf From 74913ffa833a4f60d73969b3d9a3f03180094853 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 12:36:03 -0800 Subject: [PATCH 185/384] Move the Test DSC into the Test directory. --- MdePkg/MdePkg.ci.yaml | 2 +- MdePkg/{ => Test}/MdePkgTest.dsc | 0 2 files changed, 1 insertion(+), 1 deletion(-) rename MdePkg/{ => Test}/MdePkgTest.dsc (100%) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index 3ce5c8056f4..fc8e5678db0 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -12,7 +12,7 @@ ## options defined ci/Plugin/HostUnitTestCompilerPlugin "HostUnitTestCompilerPlugin": { - "DscPath": "MdePkgTest.dsc" + "DscPath": "Test/MdePkgTest.dsc" }, ## options defined ci/Plugin/CharEncodingCheck diff --git a/MdePkg/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc similarity index 100% rename from MdePkg/MdePkgTest.dsc rename to MdePkg/Test/MdePkgTest.dsc From 40bf9d32b74d1d9a61f1fbeec493c77f1c3f7b94 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 13:10:27 -0800 Subject: [PATCH 186/384] Drop extraneous package name strings. Can be assembled in the report lib, if wanted. --- UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c | 6 +++--- UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c | 6 +++--- UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c | 6 +++--- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 4c3d273d74d..6ecce81a8c9 100644 --- a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -185,7 +185,7 @@ SampleUnitTestApp ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. @@ -197,8 +197,8 @@ SampleUnitTestApp ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 7d28eacb76c..0cc83348869 100644 --- a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -182,7 +182,7 @@ SampleUnitTestPeim ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. @@ -194,8 +194,8 @@ SampleUnitTestPeim ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index bf04ad1f585..9f04cda3e48 100644 --- a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -180,7 +180,7 @@ SampleUnitTestSmm ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); // // Populate the GlobalVarTests Unit Test Suite. @@ -192,8 +192,8 @@ SampleUnitTestSmm ( Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Sample.Globals.Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Sample.Globals.Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); // // Execute the tests. From 66aac121e99ba02306a56f058b26898a7ab69ea9 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 13 Dec 2019 16:35:35 -0800 Subject: [PATCH 187/384] Change all Fws into Frameworks. --- .../Sample/SampleUnitTestApp/SampleUnitTestApp.c | 14 +++++++------- .../Sample/SampleUnitTestPeim/SampleUnitTestPeim.c | 14 +++++++------- .../Sample/SampleUnitTestSmm/SampleUnitTestSmm.c | 14 +++++++------- 3 files changed, 21 insertions(+), 21 deletions(-) diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 6ecce81a8c9..df69b775fba 100644 --- a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -160,7 +160,7 @@ SampleUnitTestApp ( ) { EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_FRAMEWORK *Framework = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); @@ -168,7 +168,7 @@ SampleUnitTestApp ( // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); + Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -178,7 +178,7 @@ SampleUnitTestApp ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); @@ -190,7 +190,7 @@ SampleUnitTestApp ( // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); @@ -203,12 +203,12 @@ SampleUnitTestApp ( // // Execute the tests. // - Status = RunAllTestSuites( Fw ); + Status = RunAllTestSuites( Framework ); EXIT: - if (Fw) + if (Framework) { - FreeUnitTestFramework( Fw ); + FreeUnitTestFramework( Framework ); } return Status; diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 0cc83348869..e2b0a724f17 100644 --- a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -157,7 +157,7 @@ SampleUnitTestPeim ( ) { EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_FRAMEWORK *Framework = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); @@ -165,7 +165,7 @@ SampleUnitTestPeim ( // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); + Status = InitUnitTestFramework( &Framework, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -175,7 +175,7 @@ SampleUnitTestPeim ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); @@ -187,7 +187,7 @@ SampleUnitTestPeim ( // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); @@ -200,12 +200,12 @@ SampleUnitTestPeim ( // // Execute the tests. // - Status = RunAllTestSuites( Fw ); + Status = RunAllTestSuites( Framework ); EXIT: - if (Fw) + if (Framework) { - FreeUnitTestFramework( Fw ); + FreeUnitTestFramework( Framework ); } return Status; diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index 9f04cda3e48..e42b0de9b18 100644 --- a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -155,7 +155,7 @@ SampleUnitTestSmm ( ) { EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Fw = NULL; + UNIT_TEST_FRAMEWORK *Framework = NULL; UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); @@ -163,7 +163,7 @@ SampleUnitTestSmm ( // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); + Status = InitUnitTestFramework( &Framework, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -173,7 +173,7 @@ SampleUnitTestSmm ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); @@ -185,7 +185,7 @@ SampleUnitTestSmm ( // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Fw, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); @@ -198,12 +198,12 @@ SampleUnitTestSmm ( // // Execute the tests. // - Status = RunAllTestSuites( Fw ); + Status = RunAllTestSuites( Framework ); EXIT: - if (Fw) + if (Framework) { - FreeUnitTestFramework( Fw ); + FreeUnitTestFramework( Framework ); } return Status; From b4a8a274db07829cb76051466bbac78f3c59daeb Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Sat, 14 Dec 2019 12:08:50 -0800 Subject: [PATCH 188/384] Changes to build on GCC. --- UnitTestPkg/Include/Library/UnitTestLogLib.h | 8 ++++---- UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c | 4 ++-- .../Sample/SampleUnitTestPeim/SampleUnitTestPeim.c | 4 ++-- UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c | 4 ++-- 4 files changed, 10 insertions(+), 10 deletions(-) diff --git a/UnitTestPkg/Include/Library/UnitTestLogLib.h b/UnitTestPkg/Include/Library/UnitTestLogLib.h index ef163691ecb..e83e3fb8b62 100644 --- a/UnitTestPkg/Include/Library/UnitTestLogLib.h +++ b/UnitTestPkg/Include/Library/UnitTestLogLib.h @@ -26,13 +26,13 @@ // They will consume the Framework Handle and update the Framework->CurrentTest. #define UT_LOG_ERROR(Format, ...) \ - UnitTestLog( Framework, DEBUG_ERROR, Format, __VA_ARGS__ ); + UnitTestLog( Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); #define UT_LOG_WARNING(Format, ...) \ - UnitTestLog( Framework, DEBUG_WARN, Format, __VA_ARGS__ ); + UnitTestLog( Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); #define UT_LOG_INFO(Format, ...) \ - UnitTestLog( Framework, DEBUG_INFO, Format, __VA_ARGS__ ); + UnitTestLog( Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); #define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog( Framework, DEBUG_VERBOSE, Format, __VA_ARGS__ ); + UnitTestLog( Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); VOID EFIAPI diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index df69b775fba..4a215bf6065 100644 --- a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -55,7 +55,7 @@ MakeSureThatPointerIsNull ( IN UNIT_TEST_CONTEXT Context ) { - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); return UNIT_TEST_PASSED; } // ListsShouldHaveTheSameDescriptorSize() @@ -128,7 +128,7 @@ GlobalPointerShouldBeChangeable ( ) { mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); return UNIT_TEST_PASSED; } // GlobalPointerShouldBeChangeable() diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index e2b0a724f17..1ed0e462186 100644 --- a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -54,7 +54,7 @@ MakeSureThatPointerIsNull ( IN UNIT_TEST_CONTEXT Context ) { - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); return UNIT_TEST_PASSED; } // ListsShouldHaveTheSameDescriptorSize() @@ -123,7 +123,7 @@ GlobalPointerShouldBeChangeable ( ) { mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); return UNIT_TEST_PASSED; } // GlobalPointerShouldBeChangeable() diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index e42b0de9b18..89974cf25d9 100644 --- a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -54,7 +54,7 @@ MakeSureThatPointerIsNull ( IN UNIT_TEST_CONTEXT Context ) { - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, NULL); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); return UNIT_TEST_PASSED; } // ListsShouldHaveTheSameDescriptorSize() @@ -123,7 +123,7 @@ GlobalPointerShouldBeChangeable ( ) { mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL(mSampleGlobalTestPointer, ((VOID*)-1)); + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID *)-1)); return UNIT_TEST_PASSED; } // GlobalPointerShouldBeChangeable() From 7f752fca9a9784a98776783041434b7e00d7eb99 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Sat, 14 Dec 2019 12:09:02 -0800 Subject: [PATCH 189/384] Drop an accidental change that should have never made it in. --- UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c | 3 --- 1 file changed, 3 deletions(-) diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 4a215bf6065..0cbef7fa2fd 100644 --- a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -96,9 +96,6 @@ OnePlusOneShouldEqualTwo ( UT_ASSERT_EQUAL(C, 2); - UT_LOG_WARNING("This should not be. %a", "This also should not be.\n"); - UT_LOG_WARNING("This is also crap.\n"); - return UNIT_TEST_PASSED; } // OnePlusOneShouldEqualTwo() From 78fb6b0e022f2e0835ca6d075f4a7a36e36d0f23 Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Wed, 11 Dec 2019 19:22:21 +0800 Subject: [PATCH 190/384] BaseTools: Fix build failure when multiple build targets given BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2371 This patch is to fix a regression issue that build fails if multiple build targets given. Two changes cause this regression issue. One is AutoGen object __hash__ function only hash file path and arch, missing ToolChain and build target. The other is changing the multiple-thread-genfds function as default build behavior. To generate the genffs command to Makefile, there is a global data set is used, GenFdsGlobalVariable, which cause build tool use the data of first build-target build in the second build-target build. Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Cc: Ard Biesheuvel Reviewed-by: Liming Gao --- BaseTools/Source/Python/AutoGen/ModuleAutoGen.py | 2 +- BaseTools/Source/Python/AutoGen/PlatformAutoGen.py | 2 +- BaseTools/Source/Python/build/build.py | 2 ++ 3 files changed, 4 insertions(+), 2 deletions(-) diff --git a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py index 74662d1b52b..aad591de65f 100755 --- a/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/ModuleAutoGen.py @@ -270,7 +270,7 @@ def __init_platform_info__(self): # @cached_class_function def __hash__(self): - return hash((self.MetaFile, self.Arch)) + return hash((self.MetaFile, self.Arch, self.ToolChain,self.BuildTarget)) def __repr__(self): return "%s [%s]" % (self.MetaFile, self.Arch) diff --git a/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py b/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py index 4c3cdf82d57..7bd24dad42f 100644 --- a/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py +++ b/BaseTools/Source/Python/AutoGen/PlatformAutoGen.py @@ -148,7 +148,7 @@ def FillData_LibConstPcd(self): # @cached_class_function def __hash__(self): - return hash((self.MetaFile, self.Arch)) + return hash((self.MetaFile, self.Arch,self.ToolChain,self.BuildTarget)) @cached_class_function def __repr__(self): return "%s [%s]" % (self.MetaFile, self.Arch) diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 8a8e32e496f..77b46341b5a 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -58,6 +58,7 @@ from AutoGen.ModuleAutoGenHelper import WorkSpaceInfo, PlatformInfo from GenFds.FdfParser import FdfParser from AutoGen.IncludesAutoGen import IncludesAutoGen +from GenFds.GenFds import resetFdsGlobalVariable ## standard targets of build command gSupportedTarget = ['all', 'genc', 'genmake', 'modules', 'libraries', 'fds', 'clean', 'cleanall', 'cleanlib', 'run'] @@ -2207,6 +2208,7 @@ def _MultiThreadBuildPlatform(self): GlobalData.gGlobalDefines['TARGET'] = BuildTarget index = 0 for ToolChain in self.ToolChainList: + resetFdsGlobalVariable() GlobalData.gGlobalDefines['TOOLCHAIN'] = ToolChain GlobalData.gGlobalDefines['TOOL_CHAIN_TAG'] = ToolChain GlobalData.gGlobalDefines['FAMILY'] = self.ToolChainFamily[index] From 69ebe8280672589d8f5826f74c0fa92c103c8042 Mon Sep 17 00:00:00 2001 From: "Fan, Zhiju" Date: Tue, 17 Dec 2019 13:51:51 +0800 Subject: [PATCH 191/384] BaseTools:replaces the two offending quotes by ascii quotes BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2423 That commit 13c5e34a1b introduces the first two UTF-8 characters (the quote ') in an otherwise all-ascii file. In Conf\tools_def.template There is tow lines of Notes: Since this tool chain is obsolete, it doesn't enable the compiler option for included header file list generation, we replaces the two offending quotes by proper ascii quotes The patch is going to fix this issue Signed-off-by: Zhiju.Fan Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- BaseTools/Conf/tools_def.template | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/BaseTools/Conf/tools_def.template b/BaseTools/Conf/tools_def.template index 41a6ca246e0..feee2bbf161 100755 --- a/BaseTools/Conf/tools_def.template +++ b/BaseTools/Conf/tools_def.template @@ -337,7 +337,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc # Required to build platforms or ACPI tables: # Microsoft ASL ACPI Compiler (asl.exe) v4.0.0 from # http://download.microsoft.com/download/2/c/1/2c16c7e0-96c1-40f5-81fc-3e4bf7b65496/microsoft_asl_compiler-v4-0-0.msi -# Notes: Since this tool chain is obsolete, it doesn’t enable the compiler option for included header file list generation, +# Notes: Since this tool chain is obsolete, it doesn't enable the compiler option for included header file list generation, # and lose the incremental build capability. # RVCTLINUX -unix- Requires: # ARM C/C++ Compiler, 5.00 @@ -345,7 +345,7 @@ DEFINE DTC_BIN = ENV(DTC_PREFIX)dtc # Required to build platforms or ACPI tables: # Intel(r) ACPI Compiler from # https://acpica.org/downloads -# Notes: Since this tool chain is obsolete, it doesn’t enable the compiler option for included header file list generation, +# Notes: Since this tool chain is obsolete, it doesn't enable the compiler option for included header file list generation, # and lose the incremental build capability. # * Commented out - All versions of VS2005 use the same standard install directory # From c5d6a57da02774019127e5ac271de274aee0d9e2 Mon Sep 17 00:00:00 2001 From: Maciej Rabeda Date: Wed, 11 Dec 2019 17:54:19 +0800 Subject: [PATCH 192/384] Maintainers.txt: Update email address and role Created new email account that will not append legal disclaimers to my responses/patches. Switching to NetworkPkg maintainer. Cc: Jiaxin Wu Cc: Siyuan Fu Signed-off-by: Maciej Rabeda Reviewed-by: Jiaxin Wu --- Maintainers.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Maintainers.txt b/Maintainers.txt index d6e8d5d5c79..146d8aca93f 100644 --- a/Maintainers.txt +++ b/Maintainers.txt @@ -378,8 +378,8 @@ NetworkPkg F: NetworkPkg/ W: https://github.com/tianocore/tianocore.github.io/wiki/NetworkPkg M: Jiaxin Wu +M: Maciej Rabeda R: Siyuan Fu -R: Maciej Rabeda OvmfPkg F: OvmfPkg/ From 01b6090b75922bc72604c334bd3dc331490af3bb Mon Sep 17 00:00:00 2001 From: Bob Feng Date: Mon, 16 Dec 2019 18:18:46 +0800 Subject: [PATCH 193/384] BaseTools: Resolve a issue of Incremental build BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2311 In patch set 13c5e34a - 0c3e8e99, we implemented incremental build with using compiler/pre-processor generate dependent header file function. A issue is found for MSVC compiler, that the cl.exe /showIncludes build option generate header file list to either stdout or stderr. For .c file, the header file list is print out to stdout while for .vfr, .aslc and .nasm file, the file list is print out to stderr. The build tool use two threads to process the message from stdout and stderr, but to generate correct *.deps file, build tool need to combine the header file list from stderr and other messages from stdout together with correct time sequence order. So this patch is trying to combine the stdout and stderr together for the process which is for calling make program. The impact of this patch is that the output message of build with -q will be changed. The compiler error message will not print out. The build behavior of other log level setting will not be impacted. Signed-off-by: Bob Feng Cc: Liming Gao Cc: Steven Shi Cc: Michael D Kinney Reviewed-by: Liming Gao --- BaseTools/Source/Python/build/build.py | 11 ++--------- 1 file changed, 2 insertions(+), 9 deletions(-) diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 77b46341b5a..3cc4220e2ff 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -24,7 +24,7 @@ import multiprocessing from threading import Thread,Event,BoundedSemaphore import threading -from subprocess import Popen,PIPE +from subprocess import Popen,PIPE, STDOUT from collections import OrderedDict, defaultdict from Common.buildoptions import BuildOption,BuildTarget from AutoGen.PlatformAutoGen import PlatformAutoGen @@ -230,7 +230,7 @@ def LaunchCommand(Command, WorkingDir,ModuleAuto = None): EndOfProcedure = None try: # launch the command - Proc = MakeSubProc(Command, stdout=PIPE, stderr=PIPE, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True) + Proc = MakeSubProc(Command, stdout=PIPE, stderr=STDOUT, env=os.environ, cwd=WorkingDir, bufsize=-1, shell=True) # launch two threads to read the STDOUT and STDERR EndOfProcedure = Event() @@ -241,11 +241,6 @@ def LaunchCommand(Command, WorkingDir,ModuleAuto = None): StdOutThread.setDaemon(False) StdOutThread.start() - if Proc.stderr: - StdErrThread = Thread(target=ReadMessage, args=(Proc.stderr, EdkLogger.quiet, EndOfProcedure,Proc.ProcOut)) - StdErrThread.setName("STDERR-Redirector") - StdErrThread.setDaemon(False) - StdErrThread.start() # waiting for program exit Proc.wait() @@ -261,8 +256,6 @@ def LaunchCommand(Command, WorkingDir,ModuleAuto = None): if Proc.stdout: StdOutThread.join() - if Proc.stderr: - StdErrThread.join() # check the return code of the program if Proc.returncode != 0: From d2e70c382e600a1e9bbbacda170fadc3ac315c3e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:01:13 -0800 Subject: [PATCH 194/384] Change the name of the UnitTestPkg to UnitTestFrameworkPkg. --- .../Include/Library/UnitTestAssertLib.h | 0 .../Include/Library/UnitTestLib.h | 0 .../Include/Library/UnitTestLogLib.h | 0 .../Include/Library/UnitTestPersistenceLib.h | 0 .../Include/Library/UnitTestResultReportLib.h | 0 .../Include/Library/UnitTestTerminationLib.h | 0 {UnitTestPkg => UnitTestFrameworkPkg}/Include/UnitTestTypes.h | 0 .../Library/UnitTestAssertLib/UnitTestAssertLib.c | 0 .../Library/UnitTestAssertLib/UnitTestAssertLib.inf | 0 .../Library/UnitTestLib/UnitTestLib.c | 0 .../Library/UnitTestLib/UnitTestLibDxe.inf | 0 .../Library/UnitTestLib/UnitTestLibPei.inf | 0 .../Library/UnitTestLib/UnitTestLibSmm.inf | 0 .../Library/UnitTestLogLib/UnitTestLogLib.c | 0 .../Library/UnitTestLogLib/UnitTestLogLib.inf | 0 .../UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c | 0 .../UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf | 0 .../UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c | 0 .../UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf | 0 .../UnitTestResultReportLibPlainTextOutput.c | 0 .../UnitTestResultReportLibPlainTextOutput.inf | 0 .../Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c | 0 .../UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf | 0 .../Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c | 0 .../UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf | 0 {UnitTestPkg => UnitTestFrameworkPkg}/ReadMe.md | 0 .../Sample/SampleUnitTestApp/SampleUnitTestApp.c | 0 .../Sample/SampleUnitTestApp/SampleUnitTestApp.inf | 0 .../Sample/SampleUnitTestPeim/SampleUnitTestPeim.c | 0 .../Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf | 0 .../Sample/SampleUnitTestSmm/SampleUnitTestSmm.c | 0 .../Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf | 0 {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.ci.yaml | 0 {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.dec | 0 {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.dsc | 0 35 files changed, 0 insertions(+), 0 deletions(-) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestAssertLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestLogLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestPersistenceLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestResultReportLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/Library/UnitTestTerminationLib.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Include/UnitTestTypes.h (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestAssertLib/UnitTestAssertLib.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestAssertLib/UnitTestAssertLib.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLib/UnitTestLib.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLib/UnitTestLibDxe.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLib/UnitTestLibPei.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLib/UnitTestLibSmm.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLogLib/UnitTestLogLib.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestLogLib/UnitTestLogLib.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/ReadMe.md (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestApp/SampleUnitTestApp.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestApp/SampleUnitTestApp.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.ci.yaml (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.dec (100%) rename {UnitTestPkg => UnitTestFrameworkPkg}/UnitTestPkg.dsc (100%) diff --git a/UnitTestPkg/Include/Library/UnitTestAssertLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestAssertLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestAssertLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestAssertLib.h diff --git a/UnitTestPkg/Include/Library/UnitTestLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestLib.h diff --git a/UnitTestPkg/Include/Library/UnitTestLogLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestLogLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h diff --git a/UnitTestPkg/Include/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestPersistenceLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h diff --git a/UnitTestPkg/Include/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestResultReportLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestResultReportLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestResultReportLib.h diff --git a/UnitTestPkg/Include/Library/UnitTestTerminationLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h similarity index 100% rename from UnitTestPkg/Include/Library/UnitTestTerminationLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h diff --git a/UnitTestPkg/Include/UnitTestTypes.h b/UnitTestFrameworkPkg/Include/UnitTestTypes.h similarity index 100% rename from UnitTestPkg/Include/UnitTestTypes.h rename to UnitTestFrameworkPkg/Include/UnitTestTypes.h diff --git a/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c similarity index 100% rename from UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c diff --git a/UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf rename to UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c similarity index 100% rename from UnitTestPkg/Library/UnitTestLib/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf rename to UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf rename to UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf diff --git a/UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf rename to UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf diff --git a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c similarity index 100% rename from UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.c rename to UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c diff --git a/UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf rename to UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf diff --git a/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c similarity index 100% rename from UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c diff --git a/UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf diff --git a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c similarity index 100% rename from UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c diff --git a/UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf diff --git a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c similarity index 100% rename from UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf diff --git a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c similarity index 100% rename from UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c rename to UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c diff --git a/UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf rename to UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf diff --git a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c similarity index 100% rename from UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c rename to UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c diff --git a/UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf similarity index 100% rename from UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf rename to UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf diff --git a/UnitTestPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md similarity index 100% rename from UnitTestPkg/ReadMe.md rename to UnitTestFrameworkPkg/ReadMe.md diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c rename to UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c diff --git a/UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf rename to UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c rename to UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c diff --git a/UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf rename to UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c rename to UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c diff --git a/UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf similarity index 100% rename from UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf rename to UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf diff --git a/UnitTestPkg/UnitTestPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestPkg.ci.yaml similarity index 100% rename from UnitTestPkg/UnitTestPkg.ci.yaml rename to UnitTestFrameworkPkg/UnitTestPkg.ci.yaml diff --git a/UnitTestPkg/UnitTestPkg.dec b/UnitTestFrameworkPkg/UnitTestPkg.dec similarity index 100% rename from UnitTestPkg/UnitTestPkg.dec rename to UnitTestFrameworkPkg/UnitTestPkg.dec diff --git a/UnitTestPkg/UnitTestPkg.dsc b/UnitTestFrameworkPkg/UnitTestPkg.dsc similarity index 100% rename from UnitTestPkg/UnitTestPkg.dsc rename to UnitTestFrameworkPkg/UnitTestPkg.dsc From 233bf9864ebe04611c8c3ead847a682ba10c0cf9 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:26:01 -0800 Subject: [PATCH 195/384] Prepare for the big move. --- .../FrameworkInclude/Library/OsServiceLib.h | 24 + .../Library/UnitTestBootLib.h | 25 + .../Library/UnitTestPersistenceLib.h | 0 .../Library/UnitTestResultReportLib.h | 0 .../Library/UnitTestTerminationLib.h | 0 .../UnitTestFrameworkTypes.h} | 0 .../FrameworkLibrary/CmockaLib/CmockaLib.inf | 33 ++ .../FrameworkLibrary/CmockaLib/CmockaLib.uni | 16 + .../OsServiceLibHost/OsServiceLibGcc.c | 45 ++ .../OsServiceLibHost/OsServiceLibHost.inf | 26 + .../OsServiceLibHost/OsServiceLibMsvc.c | 41 ++ .../OsServiceLibHost/WinNTInclude.h | 74 +++ .../UnitTestAssertLib.c | 189 ++++++ .../UnitTestAssertLibcmocka.inf | 29 + .../UnitTestBootLibNull/UnitTestBootLibNull.c | 18 + .../UnitTestBootLibNull.inf | 28 + .../UnitTestBootLibUsbClass.c | 112 ++++ .../UnitTestBootLibUsbClass.inf | 42 ++ .../IA32/cmockaFuncTemplateGcc.nasm | 165 ++++++ .../IA32/cmockaFuncTemplateMsvc.nasm | 165 ++++++ .../UnitTestLibcmocka/UnitTestLib.c | 548 ++++++++++++++++++ .../UnitTestLibcmocka/UnitTestLibcmocka.inf | 39 ++ .../X64/cmockaFuncTemplateGcc.nasm | 172 ++++++ .../X64/cmockaFuncTemplateMsvc.nasm | 192 ++++++ .../UnitTestPersistenceLibFileSystem.c | 399 +++++++++++++ .../UnitTestPersistenceLibFileSystem.inf | 64 ++ .../UnitTestPersistenceLibNull.c | 0 .../UnitTestPersistenceLibNull.inf | 0 .../UnitTestResultReportLibDebug.c | 0 .../UnitTestResultReportLibDebug.inf | 0 .../UnitTestResultReportLibPlainTextOutput.c | 0 ...UnitTestResultReportLibPlainTextOutput.inf | 0 .../UnitTestTerminationLibShell.c | 50 ++ .../UnitTestTerminationLibShell.inf | 35 ++ UnitTestFrameworkPkg/UnitTestPkg.dec | 6 +- 35 files changed, 2535 insertions(+), 2 deletions(-) create mode 100644 UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h create mode 100644 UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h rename UnitTestFrameworkPkg/{Include => FrameworkInclude}/Library/UnitTestPersistenceLib.h (100%) rename UnitTestFrameworkPkg/{Include => FrameworkInclude}/Library/UnitTestResultReportLib.h (100%) rename UnitTestFrameworkPkg/{Include => FrameworkInclude}/Library/UnitTestTerminationLib.h (100%) rename UnitTestFrameworkPkg/{Include/UnitTestTypes.h => FrameworkInclude/UnitTestFrameworkTypes.h} (100%) create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c (100%) rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (100%) rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c (100%) rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf (100%) rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c (100%) rename UnitTestFrameworkPkg/{Library => FrameworkLibrary}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf (100%) create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c create mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h new file mode 100644 index 00000000000..7672c09d8d3 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h @@ -0,0 +1,24 @@ +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#ifndef _OS_SERVICE_LIB_H_ +#define _OS_SERVICE_LIB_H_ + +#include + +VOID * +AllocateExecutableMemory ( + IN UINTN Size + ); + +VOID +FreeExecutableMemory ( + IN VOID *Buffer, + IN UINTN Size + ); + +#endif diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h new file mode 100644 index 00000000000..133456b2045 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h @@ -0,0 +1,25 @@ +/** @file + Provides a library function that can be customized to set the platform to boot from USB on the next boot. + This allows the test framework to reboot back to USB. Since boot managers are not all the same creating a lib to + support platform customization will make porting to new code base/platform easier. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_BOOT_LIB_H__ +#define __UNIT_TEST_BOOT_LIB_H__ + +/** +Set the boot manager to boot from a specific device on the next boot. +This should be set only for the next boot and shouldn't +require any manual clean up +**/ +EFI_STATUS +EFIAPI +SetBootNextDevice ( VOID ); + + +#endif \ No newline at end of file diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestPersistenceLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestPersistenceLib.h rename to UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestPersistenceLib.h diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestResultReportLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestResultReportLib.h rename to UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestResultReportLib.h diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestTerminationLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h rename to UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestTerminationLib.h diff --git a/UnitTestFrameworkPkg/Include/UnitTestTypes.h b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h similarity index 100% rename from UnitTestFrameworkPkg/Include/UnitTestTypes.h rename to UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf new file mode 100644 index 00000000000..a642336222f --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf @@ -0,0 +1,33 @@ +## @file +# This module provides Cmocka Library implementation. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = CmockaLib + MODULE_UNI_FILE = CmockaLib.uni + FILE_GUID = F1662152-3399-49AC-BE44-CAA97575FACE + MODULE_TYPE = BASE + VERSION_STRING = 0.1 + LIBRARY_CLASS = CmockaLib + DEFINE CMOCKA_PATH = cmocka + +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + cmocka_extdep/cmocka/src/cmocka.c + +[Packages] + CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + + GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H + GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni new file mode 100644 index 00000000000..5e24d33725e --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni @@ -0,0 +1,16 @@ +// /** @file +// This module provides Cmocka Library implementation. +// +// This module provides Cmocka Library implementation. +// +// Copyright (c) 2019, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Cmocka Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides Cmocka Library implementation." + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c new file mode 100644 index 00000000000..2bea976c685 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c @@ -0,0 +1,45 @@ +/**@file + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +VOID * +AllocateExecutableMemory ( + IN UINTN Size + ) +{ + VOID *Buffer; + size_t FinalSize; + size_t PageSize; + + PageSize = getpagesize(); + + FinalSize = (Size + PageSize - 1) / PageSize * PageSize; + + Buffer = mmap(NULL, FinalSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); + if (Buffer == NULL) { + return NULL; + } + + return Buffer; +} + +VOID +FreeExecutableMemory ( + IN VOID *Buffer, + IN UINTN Size + ) +{ + size_t FinalSize; + size_t PageSize; + + PageSize = getpagesize(); + + FinalSize = (Size + PageSize - 1) / PageSize * PageSize; + + munmap (Buffer, FinalSize); +} diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf new file mode 100644 index 00000000000..4ae9805703e --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf @@ -0,0 +1,26 @@ +## @file +# +# Copyright (c) 2017, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = OsServiceLibHost + FILE_GUID = 56DCD496-CD73-42D0-B145-B7C100CE5877 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = OsServiceLib + +[Sources] + OsServiceLibMsvc.c | MSFT + OsServiceLibGcc.c | GCC + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + +[BuildOptions] + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c new file mode 100644 index 00000000000..843d4885788 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c @@ -0,0 +1,41 @@ +/**@file + +Copyright (c) 2019, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include + +VOID * +AllocateExecutableMemory ( + IN UINTN Size + ) +{ + VOID *Buffer; + SIZE_T FinalSize; + UINT32 PageSize; + SYSTEM_INFO SystemInfo; + + GetSystemInfo(&SystemInfo); + PageSize = SystemInfo.dwPageSize; + + FinalSize = (Size + PageSize - 1) / PageSize * PageSize; + + Buffer = VirtualAlloc(NULL, FinalSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); + if (Buffer == NULL) { + return NULL; + } + + return Buffer; +} + +VOID +FreeExecutableMemory ( + IN VOID *Buffer, + IN UINTN Size + ) +{ + VirtualFree(Buffer, 0, MEM_RELEASE); +} diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h new file mode 100644 index 00000000000..10a7aaddcc7 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h @@ -0,0 +1,74 @@ +/**@file + +Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.
+SPDX-License-Identifier: BSD-2-Clause-Patent + +Module Name: + WinNtLib.h + +Abstract: + Public include file for the WinNt Library + +**/ + +#ifndef __WIN_NT_INCLUDE_H__ +#define __WIN_NT_INCLUDE_H__ + +// +// Win32 include files do not compile clean with /W4, so we use the warning +// pragma to suppress the warnings for Win32 only. This way our code can stil +// compile at /W4 (highest warning level) with /WX (warnings cause build +// errors). +// +#pragma warning(disable : 4115) +#pragma warning(disable : 4201) +#pragma warning(disable : 4028) +#pragma warning(disable : 4133) + +#define GUID _WINNT_DUP_GUID_____ +#define _LIST_ENTRY _WINNT_DUP_LIST_ENTRY_FORWARD +#define LIST_ENTRY _WINNT_DUP_LIST_ENTRY +#if defined (MDE_CPU_IA32) && (_MSC_VER < 1800) +#define InterlockedIncrement _WINNT_DUP_InterlockedIncrement +#define InterlockedDecrement _WINNT_DUP_InterlockedDecrement +#define InterlockedCompareExchange64 _WINNT_DUP_InterlockedCompareExchange64 +#endif +#undef UNALIGNED +#undef CONST +#undef VOID +#undef DEBUG_EVENT + +// WQBugBug: This typedef is to make "windows.h" buildable. +// It should be removed after the root cause why +// size_t is undefined when go into the line below is found. +#if defined (MDE_CPU_IA32) +typedef UINT32 size_t ; +#endif + +#include "windows.h" + +#undef GUID +#undef _LIST_ENTRY +#undef LIST_ENTRY +#undef InterlockedIncrement +#undef InterlockedDecrement +#undef InterlockedCompareExchange64 +#undef InterlockedCompareExchangePointer +#undef CreateEventEx + +#define VOID void + +// +// Prevent collisions with Windows API name macros that deal with Unicode/Not issues +// +#undef LoadImage +#undef CreateEvent + +// +// Set the warnings back on as the EFI code must be /W4. +// +#pragma warning(default : 4115) +#pragma warning(default : 4201) + + +#endif diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c new file mode 100644 index 00000000000..b4e9e3d3332 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c @@ -0,0 +1,189 @@ +/** @file + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#define MAX_STRING_SIZE 1025 + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_TRUE(%s:%x)", Description, Expression); + _assert_true (Expression, Description, FileName, (INT32)LineNumber); + + return Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_FALSE(%s:%x)", Description, Expression); + _assert_true (!Expression, Description, FileName, (INT32)LineNumber); + + return !Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); + _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); + + return !EFI_ERROR (Status); +} + + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + BOOLEAN Result; + + Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); + + sprintf (TempStr, "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); + _assert_true (Result, TempStr, FileName, (INT32)LineNumber); + + return Result; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA != ValueB); +} + + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); + _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); + + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + sprintf (TempStr, "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); + _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); + + return (Pointer != NULL); +} diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf new file mode 100644 index 00000000000..bd4022207ce --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf @@ -0,0 +1,29 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestAssertLibcmocka + FILE_GUID = 8841561C-ABF2-4989-9039-4C6485D61C23 + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestAssertLib + +[LibraryClasses] + BaseMemoryLib + CmockaLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + +[Sources] + UnitTestAssertLib.c + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c new file mode 100644 index 00000000000..349b229d63c --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c @@ -0,0 +1,18 @@ +/** + +NULL implementation for UnitTestBootLib to allow simple compliation + + +Copyright (c) Microsoft +**/ + +#include + +EFI_STATUS +EFIAPI +SetBootNextDevice( + VOID +) +{ + return EFI_UNSUPPORTED; +} \ No newline at end of file diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf new file mode 100644 index 00000000000..5b0ac87d5b6 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf @@ -0,0 +1,28 @@ +## @file +# NULL library for UnitTestBootUsb +# +# +# @copyright +# Copyright (c) 2018 Microsoft Corporation. All rights reserved +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestBootLibNull +FILE_GUID = f143e75d-76e1-4040-b134-8f4f0bd5e3bd +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestBootLib + + +[LibraryClasses] + +[Packages] + MdePkg/MdePkg.dec + +[Guids] + +[Sources] + UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c new file mode 100644 index 00000000000..d1fc9cccb9e --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -0,0 +1,112 @@ +/** + +Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should +work on all platforms + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include + +EFI_STATUS +EFIAPI +SetBootNextDevice( + VOID +) +{ + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION NewOption; + UINT32 Attributes; + UINT8 *OptionalData = NULL; + UINT32 OptionalDataSize = 0; + UINT16 BootNextValue = 0xABCD; // this should be a safe number... + USB_CLASS_DEVICE_PATH UsbDp; + EFI_DEVICE_PATH_PROTOCOL *DpEnd = NULL; + EFI_DEVICE_PATH_PROTOCOL *Dp = NULL; + BOOLEAN NewOptionValid = FALSE; + + UsbDp.Header.Length[0] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) & 0xff); + UsbDp.Header.Length[1] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) >> 8); + UsbDp.Header.Type = MESSAGING_DEVICE_PATH; + UsbDp.Header.SubType = MSG_USB_CLASS_DP; + UsbDp.VendorId = 0xFFFF; + UsbDp.ProductId = 0xFFFF; + UsbDp.DeviceClass = 0xFF; + UsbDp.DeviceSubClass = 0xFF; + UsbDp.DeviceProtocol = 0xFF; + + Attributes = LOAD_OPTION_ACTIVE; + + DpEnd = AppendDevicePathNode(NULL, NULL); + if (DpEnd == NULL) + { + DEBUG((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + Dp = AppendDevicePathNode(DpEnd, (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp); //@MRT --- Is this memory leak becasue we lose the old Dp memory + if (Dp == NULL) + { + DEBUG((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + Status = EfiBootManagerInitializeLoadOption( + &NewOption, + (UINTN) BootNextValue, + LoadOptionTypeBoot, + Attributes, + L"Generic USB Class Device", + Dp, + OptionalData, + OptionalDataSize + ); + + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + NewOptionValid = TRUE; + DEBUG((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); + Status = EfiBootManagerLoadOptionToVariable(&NewOption); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + //Set Boot Next + Status = gRT->SetVariable(L"BootNext", + &gEfiGlobalVariableGuid, + (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE), + sizeof(BootNextValue), + &(BootNextValue)); + + DEBUG((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); + +CLEANUP: + if (Dp != NULL) + { + FreePool(Dp); + } + + if (DpEnd != NULL) + { + FreePool(DpEnd); + } + + if (NewOptionValid) + { + EfiBootManagerFreeLoadOption(&NewOption); + } + + return Status; +} \ No newline at end of file diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf new file mode 100644 index 00000000000..4e1a32104cf --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -0,0 +1,42 @@ +## @file +# Library to support booting to USB on the next boot +# This instance uses the industry standard usb class boot option. +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestBootLibUsbClass +FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + UefiRuntimeServicesTableLib + MemoryAllocationLib + DevicePathLib + UefiBootManagerLib + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestPkg/UnitTestPkg.dec + + +[Guids] + gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. + + +[Sources] + UnitTestBootLibUsbClass.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm new file mode 100644 index 00000000000..70c0aeae0db --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm @@ -0,0 +1,165 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2019, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;------------------------------------------------------------------------------ + +SECTION .text + +; This must be aligned to MY_UNIT_TEST_SUITE +%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (4 * 5) +%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (4 * 6) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (4 * 9) + +; This must be aligned to MY_UNIT_TEST +%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (4 * 6) +%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (4 * 7) +%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (4 * 8) +%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (4 * 9) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (4 * 11) + +;------------------------------------------------------------------------------ +; int GroupSetupTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupSetupTemplate) +ASM_PFX(GroupSetupTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] + test eax, eax + jz GroupSetupDone + push ecx + call eax + add esp, 4 +GroupSetupDone: + + pop ebx + xor eax, eax + ret + +global ASM_PFX(mGroupSetupTemplateSize) +ASM_PFX(mGroupSetupTemplateSize) DD $ - ASM_PFX(GroupSetupTemplate) + +;------------------------------------------------------------------------------ +; int GroupTeardownTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupTeardownTemplate) +ASM_PFX(GroupTeardownTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] + test eax, eax + jz GroupTeardownDone + push ecx + call eax + add esp, 4 +GroupTeardownDone: + + pop ebx + xor eax, eax + ret + +global ASM_PFX(mGroupTeardownTemplateSize) +ASM_PFX(mGroupTeardownTemplateSize) DD $ - ASM_PFX(GroupTeardownTemplate) + +;------------------------------------------------------------------------------ +; void TestFuncTemplate (void); +;------------------------------------------------------------------------------ +global ASM_PFX(TestFuncTemplate) +ASM_PFX(TestFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] + test eax, eax + jz DeadLoop + push edx + push ecx + call eax + add esp, 8 + + pop ebx + ret + +DeadLoop: + jmp $ + ret +global ASM_PFX(mTestFuncTemplateSize) +ASM_PFX(mTestFuncTemplateSize) DD $ - ASM_PFX(TestFuncTemplate) + +;------------------------------------------------------------------------------ +; int SetupFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(SetupFuncTemplate) +ASM_PFX(SetupFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] + test eax, eax + jz SetupDone + push edx + push ecx + call eax + add esp, 8 +SetupDone: + + pop ebx + ret +global ASM_PFX(mSetupFuncTemplateSize) +ASM_PFX(mSetupFuncTemplateSize) DD $ - ASM_PFX(SetupFuncTemplate) + +;------------------------------------------------------------------------------ +; int TeardownFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(TeardownFuncTemplate) +ASM_PFX(TeardownFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] + test eax, eax + jz TeardownDone + push edx + push ecx + call eax + add esp, 8 +TeardownDone: + + pop ebx + xor eax, eax + ret +global ASM_PFX(mTeardownFuncTemplateSize) +ASM_PFX(mTeardownFuncTemplateSize) DD $ - ASM_PFX(TeardownFuncTemplate) + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm new file mode 100644 index 00000000000..70c0aeae0db --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm @@ -0,0 +1,165 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2019, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;------------------------------------------------------------------------------ + +SECTION .text + +; This must be aligned to MY_UNIT_TEST_SUITE +%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (4 * 5) +%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (4 * 6) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (4 * 9) + +; This must be aligned to MY_UNIT_TEST +%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (4 * 6) +%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (4 * 7) +%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (4 * 8) +%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (4 * 9) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (4 * 11) + +;------------------------------------------------------------------------------ +; int GroupSetupTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupSetupTemplate) +ASM_PFX(GroupSetupTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] + test eax, eax + jz GroupSetupDone + push ecx + call eax + add esp, 4 +GroupSetupDone: + + pop ebx + xor eax, eax + ret + +global ASM_PFX(mGroupSetupTemplateSize) +ASM_PFX(mGroupSetupTemplateSize) DD $ - ASM_PFX(GroupSetupTemplate) + +;------------------------------------------------------------------------------ +; int GroupTeardownTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupTeardownTemplate) +ASM_PFX(GroupTeardownTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] + test eax, eax + jz GroupTeardownDone + push ecx + call eax + add esp, 4 +GroupTeardownDone: + + pop ebx + xor eax, eax + ret + +global ASM_PFX(mGroupTeardownTemplateSize) +ASM_PFX(mGroupTeardownTemplateSize) DD $ - ASM_PFX(GroupTeardownTemplate) + +;------------------------------------------------------------------------------ +; void TestFuncTemplate (void); +;------------------------------------------------------------------------------ +global ASM_PFX(TestFuncTemplate) +ASM_PFX(TestFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] + test eax, eax + jz DeadLoop + push edx + push ecx + call eax + add esp, 8 + + pop ebx + ret + +DeadLoop: + jmp $ + ret +global ASM_PFX(mTestFuncTemplateSize) +ASM_PFX(mTestFuncTemplateSize) DD $ - ASM_PFX(TestFuncTemplate) + +;------------------------------------------------------------------------------ +; int SetupFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(SetupFuncTemplate) +ASM_PFX(SetupFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] + test eax, eax + jz SetupDone + push edx + push ecx + call eax + add esp, 8 +SetupDone: + + pop ebx + ret +global ASM_PFX(mSetupFuncTemplateSize) +ASM_PFX(mSetupFuncTemplateSize) DD $ - ASM_PFX(SetupFuncTemplate) + +;------------------------------------------------------------------------------ +; int TeardownFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(TeardownFuncTemplate) +ASM_PFX(TeardownFuncTemplate): + ; mov eax, + DB 0xB8 + DD 0x0 ; to be patched + push ebx + mov ebx, eax + + ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov eax, [ebx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] + test eax, eax + jz TeardownDone + push edx + push ecx + call eax + add esp, 8 +TeardownDone: + + pop ebx + xor eax, eax + ret +global ASM_PFX(mTeardownFuncTemplateSize) +ASM_PFX(mTeardownFuncTemplateSize) DD $ - ASM_PFX(TeardownFuncTemplate) + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c new file mode 100644 index 00000000000..af62d1e385b --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c @@ -0,0 +1,548 @@ +/** @file + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +#define MAX_STRING_SIZE 1025 + +int GroupSetupTemplate (void **state); +int GroupTeardownTemplate (void **state); +void TestFuncTemplate (void **state); +int SetupFuncTemplate (void **state); +int TeardownFuncTemplate (void **state); + +extern UINTN mGroupSetupTemplateSize; +extern UINTN mGroupTeardownTemplateSize; +extern UINTN mTestFuncTemplateSize; +extern UINTN mSetupFuncTemplateSize; +extern UINTN mTeardownFuncTemplateSize; + +// NOTE: Changing structure below requires NASM file update +typedef struct { + CHAR8 *TestName; + CMUnitTestFunction TestFunc; + CMFixtureFunction SetupFunc; + CMFixtureFunction TeardownFunc; + CHAR8 *Description; + CHAR8 *ClassName; //can't have spaces and should be short + UNIT_TEST_FUNCTION RunTest; + UNIT_TEST_PREREQ PreReq; + UNIT_TEST_CLEANUP CleanUp; + UNIT_TEST_CONTEXT Context; + UNIT_TEST_SUITE_HANDLE ParentSuite; + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} MY_UNIT_TEST; + +typedef struct { + LIST_ENTRY Entry; + MY_UNIT_TEST UT; +} MY_UNIT_TEST_LIST_ENTRY; + +// NOTE: Changing structure below requires NASM file update +typedef struct { + UINTN NumTests; + CMFixtureFunction GroupSetup; + CMFixtureFunction GroupTeardown; + CHAR8 *Title; + CHAR8 *Package; + UNIT_TEST_SUITE_SETUP Setup; + UNIT_TEST_SUITE_TEARDOWN Teardown; + LIST_ENTRY TestCaseList; // MY_UNIT_TEST_LIST_ENTRY + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} MY_UNIT_TEST_SUITE; + +typedef struct { + LIST_ENTRY Entry; + MY_UNIT_TEST_SUITE UTS; +} MY_UNIT_TEST_SUITE_LIST_ENTRY; + +typedef struct { + CHAR8 *Title; + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR8 *VersionString; + LIST_ENTRY TestSuiteList; // MY_UNIT_TEST_SUITE_LIST_ENTRY +} MY_UNIT_TEST_FRAMEWORK; + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + +/** + This function will determine whether the short name violates any rules that would + prevent it from being used as a reporting name or as a serialization name. + + Example: If the name cannot be serialized to a filesystem file name. + + @param[in] ShortTitleString A pointer to the short title string to be evaluated. + + @retval TRUE The string is acceptable. + @retval FALSE The string should not be used. + +**/ +STATIC +BOOLEAN +IsFrameworkShortNameValid ( + IN CHAR8 *ShortTitleString + ) +{ + // TODO: Finish this function. + return TRUE; +} // IsFrameworkShortNameValid() + +STATIC +CHAR8* +AllocateAndCopyString ( + IN CHAR8 *StringToCopy + ) +{ + CHAR8 *NewString = NULL; + UINTN NewStringLength; + + NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; + NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); + if (NewString != NULL) + { + AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); + } + + return NewString; +} // AllocateAndCopyString () + + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestFramework() + + +STATIC +EFI_STATUS +FreeUnitTestSuiteEntry ( + IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestSuiteEntry() + + +STATIC +EFI_STATUS +FreeUnitTestTestEntry ( + IN UNIT_TEST_LIST_ENTRY *TestEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestTestEntry() + + + +//============================================================================= +// +// ---------------- TEST SETUP FUNCTIONS ------------------------------------- +// +//============================================================================= + + +/* +Method to Initialize the Unit Test framework + +@retval Success - Unit Test init. +@retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK **Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_FRAMEWORK *NewFramework; + + Status = EFI_SUCCESS; + NewFramework = NULL; + + // + // First, check all pointers and make sure nothing's broked. + if (Framework == NULL || Title == NULL || + ShortTitle == NULL || VersionString == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, determine whether all of the strings are good to use. + if (!IsFrameworkShortNameValid( ShortTitle )) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, set aside some space to start messing with the framework. + NewFramework = AllocateZeroPool( sizeof( MY_UNIT_TEST_FRAMEWORK ) ); + if (NewFramework == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Next, set up all the test data. + NewFramework->Title = AllocateAndCopyString( Title ); + NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); + NewFramework->VersionString = AllocateAndCopyString( VersionString ); + if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || + NewFramework->VersionString == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + InitializeListHead( &(NewFramework->TestSuiteList) ); + +Exit: + // + // If we're good, then let's copy the framework. + if (!EFI_ERROR( Status )) + { + *Framework = (UNIT_TEST_FRAMEWORK *)NewFramework; + } + // Otherwise, we need to undo this horrible thing that we've done. + else + { + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK *)NewFramework); + } + + return Status; +} + +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE **Suite, + IN UNIT_TEST_FRAMEWORK *Framework, + IN CHAR8 *Title, + IN CHAR8 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + MY_UNIT_TEST_FRAMEWORK *MyFramework; + + Status = EFI_SUCCESS; + MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; + + // + // First, let's check to make sure that our parameters look good. + if ((MyFramework == NULL) || (Title == NULL) || (Package == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewSuiteEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_SUITE_LIST_ENTRY ) ); + if (NewSuiteEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewSuiteEntry->UTS.NumTests = 0; + NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); + NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); + NewSuiteEntry->UTS.Setup = Sup; + NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.ParentFramework = MyFramework; + InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. + InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. + if (NewSuiteEntry->UTS.Title == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + if (NewSuiteEntry->UTS.Package == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mGroupSetupTemplateSize); + ASSERT(NewSuiteEntry->UTS.GroupSetup != NULL); + CopyMem ((VOID *)(UINTN)NewSuiteEntry->UTS.GroupSetup, (VOID *)(UINTN)GroupSetupTemplate, mGroupSetupTemplateSize); + *(UINTN *)((UINTN)NewSuiteEntry->UTS.GroupSetup + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewSuiteEntry->UTS; + + NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mGroupTeardownTemplateSize); + ASSERT(NewSuiteEntry->UTS.GroupTeardown != NULL); + CopyMem ((VOID *)(UINTN)NewSuiteEntry->UTS.GroupTeardown, (VOID *)(UINTN)GroupTeardownTemplate, mGroupTeardownTemplateSize); + *(UINTN *)((UINTN)NewSuiteEntry->UTS.GroupTeardown + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewSuiteEntry->UTS; + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(MyFramework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); + *Suite = (UNIT_TEST_SUITE *)&NewSuiteEntry->UTS; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestSuiteEntry( (UNIT_TEST_SUITE_LIST_ENTRY *)NewSuiteEntry ); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE *Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_SUITE *MySuite; + MY_UNIT_TEST_LIST_ENTRY *NewTestEntry; + MY_UNIT_TEST_FRAMEWORK *ParentFramework; + UINTN TestNameSize; + + Status = EFI_SUCCESS; + MySuite = (MY_UNIT_TEST_SUITE *)Suite; + ParentFramework = (MY_UNIT_TEST_FRAMEWORK*)MySuite->ParentFramework; + + // + // First, let's check to make sure that our parameters look good. + if ((MySuite == NULL) || (Description == NULL) || (ClassName == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewTestEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_LIST_ENTRY ) ); + if (NewTestEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewTestEntry->UT.Description = AllocateAndCopyString( Description ); + NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); + NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.CleanUp = CleanUp; + NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.Context = Context; + NewTestEntry->UT.ParentSuite = MySuite; + NewTestEntry->UT.ParentFramework = MySuite->ParentFramework; + InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. + if (NewTestEntry->UT.Description == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + NewTestEntry->UT.TestFunc = (CMUnitTestFunction)(UINTN)AllocateExecutableMemory (mTestFuncTemplateSize); + ASSERT(NewTestEntry->UT.TestFunc != NULL); + CopyMem ((VOID *)(UINTN)NewTestEntry->UT.TestFunc, (VOID *)(UINTN)TestFuncTemplate, mTestFuncTemplateSize); + *(UINTN *)((UINTN)NewTestEntry->UT.TestFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; + + NewTestEntry->UT.SetupFunc = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mSetupFuncTemplateSize); + ASSERT(NewTestEntry->UT.SetupFunc != NULL); + CopyMem ((VOID *)(UINTN)NewTestEntry->UT.SetupFunc, (VOID *)(UINTN)SetupFuncTemplate, mSetupFuncTemplateSize); + *(UINTN *)((UINTN)NewTestEntry->UT.SetupFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; + + NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mTeardownFuncTemplateSize); + ASSERT(NewTestEntry->UT.TeardownFunc != NULL); + CopyMem ((VOID *)(UINTN)NewTestEntry->UT.TeardownFunc, (VOID *)(UINTN)TeardownFuncTemplate, mTeardownFuncTemplateSize); + *(UINTN *)((UINTN)NewTestEntry->UT.TeardownFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; + + TestNameSize = AsciiStrLen (Description) + 1; + NewTestEntry->UT.TestName = AllocatePool (TestNameSize); + ASSERT (NewTestEntry->UT.TestName != NULL); + + Status = AsciiStrCpyS (NewTestEntry->UT.TestName, TestNameSize, Description); + ASSERT_EFI_ERROR(Status); + + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(MySuite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); + MySuite->NumTests ++; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestTestEntry( (UNIT_TEST_LIST_ENTRY *)NewTestEntry ); + } + + return Status; +} + + +//============================================================================= +// +// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- +// +//============================================================================= + +EFI_STATUS +EFIAPI +RunAllTestSuites( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_FRAMEWORK *MyFramework; + LIST_ENTRY *TestSuiteList; + LIST_ENTRY *TestSuiteLink; + MY_UNIT_TEST_SUITE_LIST_ENTRY *TestSuiteListEntry; + MY_UNIT_TEST_SUITE *TestSuite; + CHAR8 GroupName[MAX_STRING_SIZE]; + struct CMUnitTest *Tests; + LIST_ENTRY *UnitTestList; + LIST_ENTRY *UnitTestLink; + MY_UNIT_TEST_LIST_ENTRY *UnitTestListEntry; + MY_UNIT_TEST *UnitTest; + UINTN Index; + + // MU_CHANGE - We control this from our build system. + // May need to revisit. + // if (PcdGet8 (HostUnitTestMode) == 1) { + // cmocka_set_message_output (CM_OUTPUT_XML); + // } + + MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; + + TestSuiteList = &MyFramework->TestSuiteList; + for (TestSuiteLink = TestSuiteList->ForwardLink; + TestSuiteLink != TestSuiteList; + TestSuiteLink = TestSuiteLink->ForwardLink) { + TestSuiteListEntry = BASE_CR ( + TestSuiteLink, + MY_UNIT_TEST_SUITE_LIST_ENTRY, + Entry + ); + TestSuite = &TestSuiteListEntry->UTS; + Status = AsciiStrCpyS (GroupName, sizeof(GroupName), TestSuite->Title); + ASSERT_EFI_ERROR(Status); + + Tests = AllocateZeroPool (TestSuite->NumTests * sizeof(struct CMUnitTest)); + ASSERT (Tests != NULL); + Index = 0; + + UnitTestList = &TestSuite->TestCaseList; + for (UnitTestLink = UnitTestList->ForwardLink; + UnitTestLink != UnitTestList; + UnitTestLink = UnitTestLink->ForwardLink) { + UnitTestListEntry = BASE_CR ( + UnitTestLink, + MY_UNIT_TEST_LIST_ENTRY, + Entry + ); + UnitTest = &UnitTestListEntry->UT; + + Tests[Index].name = UnitTest->TestName; + Tests[Index].test_func = UnitTest->TestFunc; + Tests[Index].setup_func = UnitTest->SetupFunc; + Tests[Index].teardown_func = UnitTest->TeardownFunc; + Tests[Index].initial_state = NULL; + Index++; + } + ASSERT (Index == TestSuite->NumTests); + + _cmocka_run_group_tests (GroupName, Tests, TestSuite->NumTests, TestSuite->GroupSetup, TestSuite->GroupTeardown); + FreePool (Tests); + } + + return EFI_SUCCESS; +} + +//============================================================================= +// +// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- +// +//============================================================================= + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + return EFI_UNSUPPORTED; +} // SaveFrameworkState() + + +EFI_STATUS +EFIAPI +SaveFrameworkStateAndQuit ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + return EFI_UNSUPPORTED; +} // SaveFrameworkStateAndQuit() + + +/** + NOTE: Takes in a ResetType, but currently only supports EfiResetCold + and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. + If a more specific reset is required, use SaveFrameworkState() and + call gRT->ResetSystem() directly. + +**/ +EFI_STATUS +EFIAPI +SaveFrameworkStateAndReboot ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize, + IN EFI_RESET_TYPE ResetType + ) +{ + return EFI_UNSUPPORTED; +} // SaveFrameworkStateAndReboot() diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf new file mode 100644 index 00000000000..70c6dd8b763 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf @@ -0,0 +1,39 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestLibcmocka + FILE_GUID = C800595F-45A3-45A1-8B50-28F01C2A5A4F + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestLib + +[LibraryClasses] + BaseLib + MemoryAllocationLib + OsServiceLib + CmockaLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + HostBasedUnitTestPkg/HostBasedUnitTestPkg.dec + CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + +[Sources] + UnitTestLib.c + +[Sources.Ia32] + IA32/cmockaFuncTemplateMsvc.nasm | MSFT + IA32/cmockaFuncTemplateGcc.nasm | GCC + +[Sources.X64] + X64/cmockaFuncTemplateMsvc.nasm | MSFT + X64/cmockaFuncTemplateGcc.nasm | GCC + +[Pcd] diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm new file mode 100644 index 00000000000..3bd81c13fbf --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm @@ -0,0 +1,172 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2019, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;------------------------------------------------------------------------------ + +SECTION .text + +; This must be aligned to MY_UNIT_TEST_SUITE +%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (8 * 5) +%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (8 * 6) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (8 * 9) + +; This must be aligned to MY_UNIT_TEST +%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (8 * 6) +%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (8 * 7) +%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (8 * 8) +%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (8 * 9) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (8 * 11) + +;------------------------------------------------------------------------------ +; int GroupSetupTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupSetupTemplate) +ASM_PFX(GroupSetupTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) + mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] + test rax, rax + jz GroupSetupDone + push rbx + push rbp + call rax + pop rbp + pop rbx +GroupSetupDone: + + pop rbx + xor rax, rax + ret + +global ASM_PFX(mGroupSetupTemplateSize) +ASM_PFX(mGroupSetupTemplateSize) DQ $ - ASM_PFX(GroupSetupTemplate) + +;------------------------------------------------------------------------------ +; int GroupTeardownTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupTeardownTemplate) +ASM_PFX(GroupTeardownTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) + mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] + test rax, rax + jz GroupTeardownDone + push rbx + push rbp + call rax + pop rbp + pop rbx +GroupTeardownDone: + + pop rbx + xor rax, rax + ret + +global ASM_PFX(mGroupTeardownTemplateSize) +ASM_PFX(mGroupTeardownTemplateSize) DQ $ - ASM_PFX(GroupTeardownTemplate) + +;------------------------------------------------------------------------------ +; void TestFuncTemplate (void); +;------------------------------------------------------------------------------ +global ASM_PFX(TestFuncTemplate) +ASM_PFX(TestFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] + test rax, rax + jz DeadLoop + push rbx + push rbp + call rax + pop rbp + pop rbx + + pop rbx + ret + +DeadLoop: + jmp $ + ret +global ASM_PFX(mTestFuncTemplateSize) +ASM_PFX(mTestFuncTemplateSize) DQ $ - ASM_PFX(TestFuncTemplate) + +;------------------------------------------------------------------------------ +; int SetupFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(SetupFuncTemplate) +ASM_PFX(SetupFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] + test rax, rax + jz SetupDone + push rbx + push rbp + call rax + pop rbp + pop rbx +SetupDone: + + pop rbx + ret +global ASM_PFX(mSetupFuncTemplateSize) +ASM_PFX(mSetupFuncTemplateSize) DQ $ - ASM_PFX(SetupFuncTemplate) + +;------------------------------------------------------------------------------ +; int TeardownFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(TeardownFuncTemplate) +ASM_PFX(TeardownFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] + test rax, rax + jz TeardownDone + push rbx + push rbp + call rax + pop rbp + pop rbx +TeardownDone: + + pop rbx + xor rax, rax + ret +global ASM_PFX(mTeardownFuncTemplateSize) +ASM_PFX(mTeardownFuncTemplateSize) DQ $ - ASM_PFX(TeardownFuncTemplate) + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm new file mode 100644 index 00000000000..2d40a9d3f18 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm @@ -0,0 +1,192 @@ +;------------------------------------------------------------------------------ +; +; Copyright (c) 2019, Intel Corporation. All rights reserved.
+; SPDX-License-Identifier: BSD-2-Clause-Patent +; +;------------------------------------------------------------------------------ + +SECTION .text + +; This must be aligned to MY_UNIT_TEST_SUITE +%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (8 * 5) +%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (8 * 6) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (8 * 9) + +; This must be aligned to MY_UNIT_TEST +%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (8 * 6) +%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (8 * 7) +%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (8 * 8) +%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (8 * 9) +%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (8 * 11) + +;------------------------------------------------------------------------------ +; int GroupSetupTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupSetupTemplate) +ASM_PFX(GroupSetupTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) + mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] + test rax, rax + jz GroupSetupDone + push rbx + push rbp + push rsi + push rdi + call rax + pop rdi + pop rsi + pop rbp + pop rbx +GroupSetupDone: + + pop rbx + xor rax, rax + ret + +global ASM_PFX(mGroupSetupTemplateSize) +ASM_PFX(mGroupSetupTemplateSize) DQ $ - ASM_PFX(GroupSetupTemplate) + +;------------------------------------------------------------------------------ +; int GroupTeardownTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(GroupTeardownTemplate) +ASM_PFX(GroupTeardownTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) + mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] + test rax, rax + jz GroupTeardownDone + push rbx + push rbp + push rsi + push rdi + call rax + pop rdi + pop rsi + pop rbp + pop rbx +GroupTeardownDone: + + pop rbx + xor rax, rax + ret + +global ASM_PFX(mGroupTeardownTemplateSize) +ASM_PFX(mGroupTeardownTemplateSize) DQ $ - ASM_PFX(GroupTeardownTemplate) + +;------------------------------------------------------------------------------ +; void TestFuncTemplate (void); +;------------------------------------------------------------------------------ +global ASM_PFX(TestFuncTemplate) +ASM_PFX(TestFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] + test rax, rax + jz DeadLoop + push rbx + push rbp + push rsi + push rdi + call rax + pop rdi + pop rsi + pop rbp + pop rbx + + pop rbx + ret + +DeadLoop: + jmp $ + ret +global ASM_PFX(mTestFuncTemplateSize) +ASM_PFX(mTestFuncTemplateSize) DQ $ - ASM_PFX(TestFuncTemplate) + +;------------------------------------------------------------------------------ +; int SetupFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(SetupFuncTemplate) +ASM_PFX(SetupFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] + test rax, rax + jz SetupDone + push rbx + push rbp + push rsi + push rdi + call rax + pop rdi + pop rsi + pop rbp + pop rbx +SetupDone: + + pop rbx + ret +global ASM_PFX(mSetupFuncTemplateSize) +ASM_PFX(mSetupFuncTemplateSize) DQ $ - ASM_PFX(SetupFuncTemplate) + +;------------------------------------------------------------------------------ +; int TeardownFuncTemplate (void **state); +;------------------------------------------------------------------------------ +global ASM_PFX(TeardownFuncTemplate) +ASM_PFX(TeardownFuncTemplate): + ; mov rax, + DB 0x48, 0xB8 + DQ 0x0 ; to be patched + push rbx + mov rbx, rax + + ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) + mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] + mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] + mov rax, [rbx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] + test rax, rax + jz TeardownDone + push rbx + push rbp + push rsi + push rdi + call rax + pop rdi + pop rsi + pop rbp + pop rbx +TeardownDone: + + pop rbx + xor rax, rax + ret +global ASM_PFX(mTeardownFuncTemplateSize) +ASM_PFX(mTeardownFuncTemplateSize) DQ $ - ASM_PFX(TeardownFuncTemplate) + diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c new file mode 100644 index 00000000000..86bacface25 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c @@ -0,0 +1,399 @@ +/** @file -- UnitTestPersistenceFilesystemLib.c + +This is an instance of the Unit Test Persistence Lib that will utilize +the filesystem that a test application is running from to save a serialized +version of the internal test state in case the test needs to quit and restore. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ +#include +#include +#include +//#include +#include +#include +#include +#include +#include +#include + +#include + +/** + TODO: STUFF!! + + @retval !NULL A pointer to the EFI_FILE protocol instance for the filesystem. + @retval NULL Filesystem could not be found or an error occurred. + +**/ +STATIC +EFI_DEVICE_PATH_PROTOCOL* +GetCacheFileDevicePath ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + CHAR16 *AppPath = NULL, *CacheFilePath = NULL; + CHAR16 *FileSuffix = L"_Cache.dat"; + UINTN DirectorySlashOffset, CacheFilePathLength; + EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath = NULL; + + // + // First, we need to get some information from the loaded image. + // Namely, where the hell are you? + // + Status = gBS->HandleProtocol( gImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID**)&LoadedImage ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status )); + return NULL; + } + + // + // Now we should have the device path of the root device and a file path for the rest. + // In order to target the directory for the test application, we must process + // the file path a little. + // + // NOTE: This may not be necessary... Path processing functions exist... + // PathCleanUpDirectories (FileNameCopy); + // if (PathRemoveLastItem (FileNameCopy)) { + AppPath = ConvertDevicePathToText( LoadedImage->FilePath, TRUE, TRUE ); // NOTE: This must be freed. + DirectorySlashOffset = StrLen( AppPath ); + // Make sure we didn't get any weird data. + if (DirectorySlashOffset == 0) + { + DEBUG(( DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__ )); + goto Exit; + } + // Now that we know we have a decent string, let's take a deeper look. + do + { + if (AppPath[DirectorySlashOffset] == L'\\') + { + break; + } + DirectorySlashOffset--; + } while (DirectorySlashOffset > 0); + + // + // After that little maneuver, DirectorySlashOffset should be pointing at the last '\' in AppString. + // That would be the path to the parent directory that the test app is executing from. + // Let's check and make sure that's right. + // + if (AppPath[DirectorySlashOffset] != L'\\') + { + DEBUG(( DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__ )); + goto Exit; + } + + // + // Now we know some things, we're ready to produce our output string, I think. + // + CacheFilePathLength = DirectorySlashOffset + 1; + CacheFilePathLength += StrLen( Framework->ShortTitle ); + CacheFilePathLength += StrLen( FileSuffix ); + CacheFilePathLength += 1; // Don't forget the NULL terminator. + CacheFilePath = AllocateZeroPool( CacheFilePathLength * sizeof( CHAR16 ) ); + + // + // Let's produce our final path string, shall we? + // + StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. + StrCatS( CacheFilePath, CacheFilePathLength, Framework->ShortTitle ); // Copy the base name for the test cache. + StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. + + // + // Finally, try to create the device path for the thing thing. + // + CacheFileDevicePath = FileDevicePath( LoadedImage->DeviceHandle, CacheFilePath ); + +Exit: + // Always put away your toys. + if (AppPath != NULL) + { + FreePool( AppPath ); + } + if (CacheFilePath != NULL) + { + FreePool( CacheFilePath); + } + + return CacheFileDevicePath; +} // GetCacheFileDevicePath() + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // Check to see whether the file exists. + // If the file can be opened for reading, it exists. + // Otherwise, probably not. + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 ); + if (!EFI_ERROR( Status )) + { + ShellCloseFile( &FileHandle ); + } + + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + + DEBUG(( DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR( Status ) )); + + return !EFI_ERROR( Status ); +} // DoesCacheExist() + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + UINTN WriteCount; + + // + // Check the inputs for sanity. + if (FrameworkHandle == NULL || SaveData == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // + //First lets open the file if it exists so we can delete it...This is the work around for truncation + // + Status = ShellOpenFileByDevicePath(&FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE), + 0); + + if (!EFI_ERROR(Status)) + { + //if file handle above was opened it will be closed by the delete. + Status = ShellDeleteFile(&FileHandle); + if (EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); + } + } + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE), + 0 ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); + goto Exit; + } + + // + // Write the data to the file. + // + WriteCount = SaveData->BlobSize; + DEBUG(( DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount )); + Status = ShellWriteFile( FileHandle, + &WriteCount, + SaveData ); + + if (EFI_ERROR( Status ) || WriteCount != SaveData->BlobSize) + { + DEBUG(( DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status )); + } + else + { + DEBUG(( DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__ )); + } + + // + // No matter what, we should probably close the file. + // + ShellCloseFile( &FileHandle ); + +Exit: + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + + return Status; +} // SaveUnitTestCache() + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + SHELL_FILE_HANDLE FileHandle; + BOOLEAN IsFileOpened = FALSE; + UINT64 LargeFileSize; + UINTN FileSize; + UNIT_TEST_SAVE_HEADER *Buffer = NULL; + + // + // Check the inputs for sanity. + if (FrameworkHandle == NULL || SaveData == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); + goto Exit; + } + else + { + IsFileOpened = TRUE; + } + + // + // Now that the file is opened, we need to determine how large a buffer we need. + Status = ShellGetFileSize( FileHandle, &LargeFileSize ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status )); + goto Exit; + } + + // + // Now that we know the size, let's allocated a buffer to hold the contents. + FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. + Buffer = AllocatePool( FileSize ); + if (Buffer == NULL) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status )); + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Finally, let's read the bloody data. + Status = ShellReadFile( FileHandle, &FileSize, Buffer ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status )); + } + +Exit: + // + // Always put away your toys. + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + if (IsFileOpened) + { + ShellCloseFile( &FileHandle ); + } + + // + // If we're returning an error, make sure + // the state is sane. + if (EFI_ERROR( Status ) && Buffer != NULL) + { + FreePool( Buffer ); + Buffer = NULL; + } + + *SaveData = Buffer; + return Status; +} // LoadUnitTestCache() diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf new file mode 100644 index 00000000000..f5d56bde948 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf @@ -0,0 +1,64 @@ +## @file UnitTestPersistenceLibFileSystem.inf +# This is an instance of the Unit Test Persistence Lib that will utilize +# the filesystem that a test application is running from to save a serialized +# version of the internal test state in case the test needs to quit and restore. +# +# @copyright +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +# +# +# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibFileSystem + FILE_GUID = 9200844A-CDFD-4368-B4BD-106354702605 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_APPLICATION + LIBRARY_CLASS = UnitTestPersistenceLib|UEFI_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + UnitTestPersistenceLibFileSystem.c + + +[Packages] + MdePkg/MdePkg.dec + UnitTestPkg/UnitTestPkg.dec + ShellPkg/ShellPkg.dec + + +[LibraryClasses] + DebugLib + UefiBootServicesTableLib + BaseLib + ShellLib + + +[Protocols] + gEfiLoadedImageProtocolGuid + gEfiSimpleFileSystemProtocolGuid + + +[Guids] + gEfiFileInfoGuid + gEfiFileSystemInfoGuid diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf rename to UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c new file mode 100644 index 00000000000..57f66f1b0ab --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c @@ -0,0 +1,50 @@ +/** @file -- UnitTestTerminationLibShell.c +DXE Driver-/Application-specific methods of exiting a test. + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + + +/** + Specific function to take steps to quit the test in progress immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkExit ( + VOID + ) +{ + gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); +} // FrameworkExit() + +/** + Specific function to take steps to reboot the test machine immediately + without proceeding through the remaining test cases. This may be used because + a test case specifically needs to hand of execution and re-enter to + complete a test. + + NOTE: If this function returns, test harness will assume something has gone wrong. + +**/ +VOID +FrameworkResetSystem ( + IN EFI_RESET_TYPE ResetType + ) +{ + // + // Next, we want to update the BootNext variable to the device + // so that we have a fighting chance of coming back here. + // + SetBootNextDevice(); + + gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); +} // FrameworkResetSystem() diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf new file mode 100644 index 00000000000..b837b1a6df2 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf @@ -0,0 +1,35 @@ +## @file UnitTestTerminationLibShell.inf +# DXE Driver-/Application-specific methods of exiting a test. +# +## +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestTerminationLibShell + FILE_GUID = E5C189CF-CA58-45C0-9EA9-C30D04FB705D + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = UnitTestTerminationLib|UEFI_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + + +[Sources] + UnitTestTerminationLibShell.c + + +[Packages] + MdePkg/MdePkg.dec + + +[LibraryClasses] + UefiBootServicesTableLib + UnitTestBootLib diff --git a/UnitTestFrameworkPkg/UnitTestPkg.dec b/UnitTestFrameworkPkg/UnitTestPkg.dec index 69e2b7224c3..17756c06eb2 100644 --- a/UnitTestFrameworkPkg/UnitTestPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestPkg.dec @@ -19,8 +19,10 @@ [Includes] Include -[LibraryClasses] +[Includes.Common.Private] + FrameworkInclude +[LibraryClasses] ## @libraryclass Provide unit test assert helpers # UnitTestAssertLib|Include/Library/UnitTestAssertLib.h @@ -33,6 +35,7 @@ # UnitTestLogLib|Include/Library/UnitTestLogLib.h +[LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state # UnitTestPersistenceLib|Include/Library/UnitTestPersistenceLib.h @@ -47,7 +50,6 @@ UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h [Guids] - gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } [Ppis] From 1c70c9980d0fa83a4ed1cff0b11a872b830db301 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:28:59 -0800 Subject: [PATCH 196/384] Add Cmocka as a submodule. --- .gitmodules | 3 +++ UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf | 2 +- UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka | 1 + 3 files changed, 5 insertions(+), 1 deletion(-) create mode 160000 UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka diff --git a/.gitmodules b/.gitmodules index 508f0c18287..279eccadc52 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "SoftFloat"] path = ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 url = https://github.com/ucb-bar/berkeley-softfloat-3.git +[submodule "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka"] + path = UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka + url = https://git.cryptomilk.org/projects/cmocka.git diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf index a642336222f..8924000298d 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf @@ -21,7 +21,7 @@ # [Sources] - cmocka_extdep/cmocka/src/cmocka.c + cmocka/src/cmocka.c [Packages] CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka new file mode 160000 index 00000000000..1cc9cde3448 --- /dev/null +++ b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka @@ -0,0 +1 @@ +Subproject commit 1cc9cde3448cdd2e000886a26acf1caac2db7cf1 From b7e4054f8af73f183891f93933885d35a96df0db Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:29:22 -0800 Subject: [PATCH 197/384] Drop EDK2_TEST as a CI dependency. --- .pytool/CISettings.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 37331b44eef..4c1dd069bb3 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -150,11 +150,6 @@ def GetName(self): def GetDependencies(self): return [ - { - "Path": "EDK2_TEST", - "Url": "https://github.com/corthon/edk2-test.git", - "Branch": "edk2-host-test_v2" - } ] def GetPackagesPath(self): From 459ed825bb8c6c93ee5de8506545c1741ccd6f22 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:30:09 -0800 Subject: [PATCH 198/384] Add Cmocka as a RequiredSubmodule. --- .gitignore | 1 - .pytool/CISettings.py | 4 +++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index cbd304f066c..ca67689b60b 100644 --- a/.gitignore +++ b/.gitignore @@ -7,4 +7,3 @@ tags/ .vscode/ # Dependencies -EDK2_TEST/ diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 4c1dd069bb3..21343e4b9a0 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -143,6 +143,8 @@ def GetRequiredSubmodules(self): "ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3", False)) rs.append(RequiredSubmodule( "CryptoPkg/Library/OpensslLib/openssl", False)) + rs.append(RequiredSubmodule( + "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka", False)) return rs def GetName(self): @@ -153,7 +155,7 @@ def GetDependencies(self): ] def GetPackagesPath(self): - return ('EDK2_TEST',) + return () def GetWorkspaceRoot(self): ''' get WorkspacePath ''' From 163e40e42846a8af4a17314464af20259c61c38d Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 15:40:11 -0800 Subject: [PATCH 199/384] Settle on an idea for the TerminationLib. --- .../Library/UnitTestTerminationLib.h | 0 .../UnitTestTerminationLibTbd.c | 45 ------------------- .../UnitTestTerminationLibTbd.inf | 31 ------------- 3 files changed, 76 deletions(-) rename UnitTestFrameworkPkg/{FrameworkInclude => Include}/Library/UnitTestTerminationLib.h (100%) delete mode 100644 UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c delete mode 100644 UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestTerminationLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestTerminationLib.h rename to UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h diff --git a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c deleted file mode 100644 index 7f8b3697032..00000000000 --- a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.c +++ /dev/null @@ -1,45 +0,0 @@ -/** @file -- UnitTestTerminationLibTbd.c -This is an invalid implementation of this lib while we figure out what -best to do in difficult contexts. - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - - -/** - Specific function to take steps to quit the test in progress immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkExit ( - VOID - ) -{ - // TBD -} // FrameworkExit() - -/** - Specific function to take steps to reboot the test machine immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - // TBD -} // FrameworkResetSystem() diff --git a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf deleted file mode 100644 index 4e2a7e7c492..00000000000 --- a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf +++ /dev/null @@ -1,31 +0,0 @@ -## @file UnitTestTerminationLibTbd.inf -# This is an invalid implementation of this lib while we figure out what -# best to do in difficult contexts. -# -## -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestTerminationLibTbd - FILE_GUID = DFD5BB45-A030-4182-BB93-F4697DCF4577 - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestTerminationLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - - -[Sources] - UnitTestTerminationLibTbd.c - - -[Packages] - MdePkg/MdePkg.dec From 764386dd57d306fabb0e5b316ca881285c3de0fa Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 17:31:56 -0800 Subject: [PATCH 200/384] Shuffle some more things around. Need to do some build testing. --- .../Include/Library/UnitTestLib.h | 105 +++++++++++------- 1 file changed, 66 insertions(+), 39 deletions(-) diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h index d9724640f4d..8d899f9cf70 100644 --- a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h +++ b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h @@ -11,6 +11,68 @@ #ifndef __UNIT_TEST_LIB_H__ #define __UNIT_TEST_LIB_H__ +typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. +typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. +typedef VOID* UNIT_TEST_CONTEXT; +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST FUNCTION TYPE DEFINITIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Unit-Test Function pointer type. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_FUNCTION) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Prerequisite Function pointer type. +// NOTE: Should be the same as UnitTest. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_PREREQ) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Cleanup (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_CLEANUP) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Suite Setup (before) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_SETUP) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + +// +// Unit-Test Test Suite Teardown (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_TEARDOWN) ( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + + /* Method to Initialize the Unit Test framework @@ -25,10 +87,10 @@ Method to Initialize the Unit Test framework EFI_STATUS EFIAPI InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK **Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString ); /* @@ -101,39 +163,4 @@ SaveFrameworkState ( IN UINTN ContextToSaveSize ); -EFI_STATUS -EFIAPI -SaveFrameworkStateAndQuit ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ); - -/** - NOTE: Takes in a ResetType, but currently only supports EfiResetCold - and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. - If a more specific reset is required, use SaveFrameworkState() and - call gRT->ResetSystem() directly. - -**/ -EFI_STATUS -EFIAPI -SaveFrameworkStateAndReboot ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize, - IN EFI_RESET_TYPE ResetType - ); - -/** - Set the boot manager to boot from a specific device on the next boot. - This should be set only for the next boot and shouldn't - require any manual clean up -**/ -EFI_STATUS -EFIAPI -SetFrameworkBootNextDevice ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ); - #endif \ No newline at end of file From c7a0aca0ed0e9b51efe0c437ff77b30cf1457f8a Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Wed, 18 Dec 2019 10:56:28 +0800 Subject: [PATCH 201/384] MdePkg/Spdm: fix Nonce structure error. Align to SPDM 1.0.0 specification. Fix Nonce data structure error. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Jiewen Yao Reviewed-by: Liming Gao --- MdePkg/Include/IndustryStandard/Spdm.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/Spdm.h b/MdePkg/Include/IndustryStandard/Spdm.h index c05395fea76..38ec7748a70 100644 --- a/MdePkg/Include/IndustryStandard/Spdm.h +++ b/MdePkg/Include/IndustryStandard/Spdm.h @@ -1,6 +1,6 @@ /** @file Definitions of Security Protocol & Data Model Specification (SPDM) - version 0.99a in Distributed Management Task Force (DMTF). + version 1.0.0 in Distributed Management Task Force (DMTF). Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -215,7 +215,7 @@ typedef struct { /// typedef struct { SPDM_MESSAGE_HEADER Header; - UINT32 Nonce; + UINT8 Nonce[32]; } SPDM_CHALLENGE_REQUEST; /// @@ -224,7 +224,7 @@ typedef struct { typedef struct { SPDM_MESSAGE_HEADER Header; //UINT8 CertChainHash[DigestSize]; -//UINT32 Nonce; +//UINT8 Nonce[32]; //UINT8 MeasurementSummaryHash[DigestSize]; //UINT16 OpaqueLength; //UINT8 OpaqueData[OpaqueLength]; @@ -236,7 +236,7 @@ typedef struct { /// typedef struct { SPDM_MESSAGE_HEADER Header; - UINT32 Nonce; + UINT8 Nonce[32]; } SPDM_GET_MEASUREMENTS_REQUEST; /// @@ -277,7 +277,7 @@ typedef struct { UINT8 NumberOfBlocks; UINT8 MeasurementRecordLength[3]; //UINT8 MeasurementRecord[MeasurementRecordLength]; -//UINT32 Nonce; +//UINT8 Nonce[32]; //UINT16 OpaqueLength; //UINT8 OpaqueData[OpaqueLength]; //UINT8 Signature[KeySize]; From 95bb203861c5e19b7b7d5d9318e16d82108f2134 Mon Sep 17 00:00:00 2001 From: Zhichao Gao Date: Fri, 29 Nov 2019 16:51:45 +0800 Subject: [PATCH 202/384] ShellPkg/ShellProtocol: Return error code while fail parsing cmd-line REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2395 Errors happened in the arguments parsing is not a critical error. And it would miss the error status code in the release version of shell. So replace the ASSERT with returning error status code while fail parsing command-line in UpdateArgcArgv. Cc: Ray Ni Cc: Linson Augustine Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Ray Ni Signed-off-by: Zhichao Gao --- ShellPkg/Application/Shell/ShellProtocol.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ShellPkg/Application/Shell/ShellProtocol.c b/ShellPkg/Application/Shell/ShellProtocol.c index 5e529b6568a..f0362a42d89 100644 --- a/ShellPkg/Application/Shell/ShellProtocol.c +++ b/ShellPkg/Application/Shell/ShellProtocol.c @@ -1497,7 +1497,10 @@ InternalShellExecuteDevicePath( ShellParamsProtocol.StdOut = ShellInfoObject.NewShellParametersProtocol->StdOut; ShellParamsProtocol.StdErr = ShellInfoObject.NewShellParametersProtocol->StdErr; Status = UpdateArgcArgv(&ShellParamsProtocol, NewCmdLine, Efi_Application, NULL, NULL); - ASSERT_EFI_ERROR(Status); + if (EFI_ERROR (Status)) { + goto UnloadImage; + } + // // Replace Argv[0] with the full path of the binary we're executing: // If the command line was "foo", the binary might be called "foo.efi". From 09816e21d3023ad54bf50640c29db3e2c115f45c Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 22:20:06 -0800 Subject: [PATCH 203/384] TestBaseSafeIntLib builds again. --- MdePkg/Test/MdePkgTest.dsc | 10 +- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 228 +++++++++--------- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 1 - .../BaseSafeIntLib/TestBaseSafeIntLib.inf | 2 +- .../FrameworkInclude/UnitTestFrameworkTypes.h | 77 +----- .../FrameworkLibrary/CmockaLib/CmockaLib.inf | 2 +- .../UnitTestAssertLib.c | 4 +- .../UnitTestAssertLibcmocka.inf | 3 +- .../UnitTestBootLibUsbClass.inf | 2 +- .../UnitTestLibcmocka/UnitTestLib.c | 4 +- .../UnitTestLibcmocka/UnitTestLibcmocka.inf | 4 +- .../UnitTestPersistenceLibFileSystem.c | 5 +- .../UnitTestPersistenceLibFileSystem.inf | 2 +- .../UnitTestPersistenceLibNull.c | 2 +- .../UnitTestPersistenceLibNull.inf | 2 +- .../UnitTestResultReportLibDebug.c | 2 +- .../UnitTestResultReportLibDebug.inf | 2 +- .../UnitTestResultReportLibPlainTextOutput.c | 2 +- ...UnitTestResultReportLibPlainTextOutput.inf | 2 +- .../Include/Library/UnitTestLib.h | 43 +++- .../UnitTestAssertLib/UnitTestAssertLib.c | 2 +- .../UnitTestAssertLib/UnitTestAssertLib.inf | 2 +- .../Library/UnitTestLib/UnitTestLib.c | 2 +- .../Library/UnitTestLib/UnitTestLibDxe.inf | 2 +- .../Library/UnitTestLib/UnitTestLibPei.inf | 2 +- .../Library/UnitTestLib/UnitTestLibSmm.inf | 2 +- .../Library/UnitTestLogLib/UnitTestLogLib.c | 2 +- .../Library/UnitTestLogLib/UnitTestLogLib.inf | 2 +- .../SampleUnitTestApp/SampleUnitTestApp.c | 2 +- .../SampleUnitTestApp/SampleUnitTestApp.inf | 2 +- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 2 +- .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 2 +- .../SampleUnitTestSmm/SampleUnitTestSmm.c | 2 +- .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 2 +- ...g.ci.yaml => UnitTestFrameworkPkg.ci.yaml} | 0 ...itTestPkg.dec => UnitTestFrameworkPkg.dec} | 2 + ...itTestPkg.dsc => UnitTestFrameworkPkg.dsc} | 0 37 files changed, 188 insertions(+), 241 deletions(-) rename UnitTestFrameworkPkg/{UnitTestPkg.ci.yaml => UnitTestFrameworkPkg.ci.yaml} (100%) rename UnitTestFrameworkPkg/{UnitTestPkg.dec => UnitTestFrameworkPkg.dec} (94%) rename UnitTestFrameworkPkg/{UnitTestPkg.dsc => UnitTestFrameworkPkg.dsc} (100%) diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 4179c6ff42c..6a33a9b09a7 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -16,13 +16,13 @@ SKUID_IDENTIFIER = DEFAULT [LibraryClasses] - CmockaLib|CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf + CmockaLib|UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf BaseLib|MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf BaseMemoryLib|MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - OsServiceLib|HostBasedUnitTestPkg/Library/OsServiceLibHost/OsServiceLibHost.inf + OsServiceLib|UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf @@ -30,12 +30,12 @@ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - UnitTestAssertLib|CmockaHostUnitTestPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf - UnitTestLib|CmockaHostUnitTestPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf + UnitTestAssertLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf + UnitTestLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf [Components] - CmockaHostUnitTestPkg/Library/CmockaLib/CmockaLib.inf { + UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf { MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index f7781cb0148..c6cb4bc895c 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -2736,13 +2736,13 @@ UefiTestMain ( VOID ) { - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Fw; - UNIT_TEST_SUITE *ConversionTestSuite; - UNIT_TEST_SUITE *AdditionSubtractionTestSuite; - UNIT_TEST_SUITE *MultiplicationTestSuite; + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_SUITE_HANDLE ConversionTestSuite; + UNIT_TEST_SUITE_HANDLE AdditionSubtractionTestSuite; + UNIT_TEST_SUITE_HANDLE MultiplicationTestSuite; - Fw = NULL; + Framework = NULL; ConversionTestSuite = NULL; AdditionSubtractionTestSuite = NULL; MultiplicationTestSuite = NULL; @@ -2752,7 +2752,7 @@ UefiTestMain ( // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework (&Fw, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); + Status = InitUnitTestFramework (&Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); goto EXIT; @@ -2761,142 +2761,142 @@ UefiTestMain ( /// // Test the conversion functions // - Status = CreateUnitTestSuite (&ConversionTestSuite, Fw, "Int Safe Conversions Test Suite", "Common.SafeInt.Convert", NULL, NULL); + Status = CreateUnitTestSuite (&ConversionTestSuite, Framework, "Int Safe Conversions Test Suite", "Common.SafeInt.Convert", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Conversions Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint8", "Common.SafeInt.Convert.TestSafeInt8ToUint8", TestSafeInt8ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint16", "Common.SafeInt.Convert.TestSafeInt8ToUint16", TestSafeInt8ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint32", "Common.SafeInt.Convert.TestSafeInt8ToUint32", TestSafeInt8ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt8ToUintn", "Common.SafeInt.Convert.TestSafeInt8ToUintn", TestSafeInt8ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint64", "Common.SafeInt.Convert.TestSafeInt8ToUint64", TestSafeInt8ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint8ToInt8", "Common.SafeInt.Convert.TestSafeUint8ToInt8", TestSafeUint8ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint8ToChar8", "Common.SafeInt.Convert.TestSafeUint8ToChar8", TestSafeUint8ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToInt8", "Common.SafeInt.Convert.TestSafeInt16ToInt8", TestSafeInt16ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToChar8", "Common.SafeInt.Convert.TestSafeInt16ToChar8", TestSafeInt16ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint8", "Common.SafeInt.Convert.TestSafeInt16ToUint8", TestSafeInt16ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint16", "Common.SafeInt.Convert.TestSafeInt16ToUint16", TestSafeInt16ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint32", "Common.SafeInt.Convert.TestSafeInt16ToUint32", TestSafeInt16ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToUintn", "Common.SafeInt.Convert.TestSafeInt16ToUintn", TestSafeInt16ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint64", "Common.SafeInt.Convert.TestSafeInt16ToUint64", TestSafeInt16ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt8", "Common.SafeInt.Convert.TestSafeUint16ToInt8", TestSafeUint16ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint16ToChar8", "Common.SafeInt.Convert.TestSafeUint16ToChar8", TestSafeUint16ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint16ToUint8", "Common.SafeInt.Convert.TestSafeUint16ToUint8", TestSafeUint16ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt16", "Common.SafeInt.Convert.TestSafeUint16ToInt16", TestSafeUint16ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt8", "Common.SafeInt.Convert.TestSafeInt32ToInt8", TestSafeInt32ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToChar8", "Common.SafeInt.Convert.TestSafeInt32ToChar8", TestSafeInt32ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint8", "Common.SafeInt.Convert.TestSafeInt32ToUint8", TestSafeInt32ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt16", "Common.SafeInt.Convert.TestSafeInt32ToInt16", TestSafeInt32ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint16", "Common.SafeInt.Convert.TestSafeInt32ToUint16", TestSafeInt32ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint32", "Common.SafeInt.Convert.TestSafeInt32ToUint32", TestSafeInt32ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToUintn", "Common.SafeInt.Convert.TestSafeInt32ToUintn", TestSafeInt32ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint64", "Common.SafeInt.Convert.TestSafeInt32ToUint64", TestSafeInt32ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt8", "Common.SafeInt.Convert.TestSafeUint32ToInt8", TestSafeUint32ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToChar8", "Common.SafeInt.Convert.TestSafeUint32ToChar8", TestSafeUint32ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint8", "Common.SafeInt.Convert.TestSafeUint32ToUint8", TestSafeUint32ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt16", "Common.SafeInt.Convert.TestSafeUint32ToInt16", TestSafeUint32ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint16", "Common.SafeInt.Convert.TestSafeUint32ToUint16", TestSafeUint32ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt32", "Common.SafeInt.Convert.TestSafeUint32ToInt32", TestSafeUint32ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint32ToIntn", "Common.SafeInt.Convert.TestSafeUint32ToIntn", TestSafeUint32ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToInt8", "Common.SafeInt.Convert.TestSafeIntnToInt8", TestSafeIntnToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToChar8", "Common.SafeInt.Convert.TestSafeIntnToChar8", TestSafeIntnToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToUint8", "Common.SafeInt.Convert.TestSafeIntnToUint8", TestSafeIntnToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToInt16", "Common.SafeInt.Convert.TestSafeIntnToInt16", TestSafeIntnToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToUint16", "Common.SafeInt.Convert.TestSafeIntnToUint16", TestSafeIntnToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToInt32", "Common.SafeInt.Convert.TestSafeIntnToInt32", TestSafeIntnToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToUint32", "Common.SafeInt.Convert.TestSafeIntnToUint32", TestSafeIntnToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToUintn", "Common.SafeInt.Convert.TestSafeIntnToUintn", TestSafeIntnToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeIntnToUint64", "Common.SafeInt.Convert.TestSafeIntnToUint64", TestSafeIntnToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToInt8", "Common.SafeInt.Convert.TestSafeUintnToInt8", TestSafeUintnToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToChar8", "Common.SafeInt.Convert.TestSafeUintnToChar8", TestSafeUintnToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToUint8", "Common.SafeInt.Convert.TestSafeUintnToUint8", TestSafeUintnToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToInt16", "Common.SafeInt.Convert.TestSafeUintnToInt16", TestSafeUintnToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToUint16", "Common.SafeInt.Convert.TestSafeUintnToUint16", TestSafeUintnToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToInt32", "Common.SafeInt.Convert.TestSafeUintnToInt32", TestSafeUintnToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToUint32", "Common.SafeInt.Convert.TestSafeUintnToUint32", TestSafeUintnToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToIntn", "Common.SafeInt.Convert.TestSafeUintnToIntn", TestSafeUintnToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUintnToInt64", "Common.SafeInt.Convert.TestSafeUintnToInt64", TestSafeUintnToInt64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt8", "Common.SafeInt.Convert.TestSafeInt64ToInt8", TestSafeInt64ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToChar8", "Common.SafeInt.Convert.TestSafeInt64ToChar8", TestSafeInt64ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint8", "Common.SafeInt.Convert.TestSafeInt64ToUint8", TestSafeInt64ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt16", "Common.SafeInt.Convert.TestSafeInt64ToInt16", TestSafeInt64ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint16", "Common.SafeInt.Convert.TestSafeInt64ToUint16", TestSafeInt64ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt32", "Common.SafeInt.Convert.TestSafeInt64ToInt32", TestSafeInt64ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint32", "Common.SafeInt.Convert.TestSafeInt64ToUint32", TestSafeInt64ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToIntn", "Common.SafeInt.Convert.TestSafeInt64ToIntn", TestSafeInt64ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToUintn", "Common.SafeInt.Convert.TestSafeInt64ToUintn", TestSafeInt64ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint64", "Common.SafeInt.Convert.TestSafeInt64ToUint64", TestSafeInt64ToUint64, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt8", "Common.SafeInt.Convert.TestSafeUint64ToInt8", TestSafeUint64ToInt8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToChar8", "Common.SafeInt.Convert.TestSafeUint64ToChar8", TestSafeUint64ToChar8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint8", "Common.SafeInt.Convert.TestSafeUint64ToUint8", TestSafeUint64ToUint8, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt16", "Common.SafeInt.Convert.TestSafeUint64ToInt16", TestSafeUint64ToInt16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint16", "Common.SafeInt.Convert.TestSafeUint64ToUint16", TestSafeUint64ToUint16, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt32", "Common.SafeInt.Convert.TestSafeUint64ToInt32", TestSafeUint64ToInt32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint32", "Common.SafeInt.Convert.TestSafeUint64ToUint32", TestSafeUint64ToUint32, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToIntn", "Common.SafeInt.Convert.TestSafeUint64ToIntn", TestSafeUint64ToIntn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToUintn", "Common.SafeInt.Convert.TestSafeUint64ToUintn", TestSafeUint64ToUintn, NULL, NULL, NULL); - AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt64", "Common.SafeInt.Convert.TestSafeUint64ToInt64", TestSafeUint64ToInt64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint8", "TestSafeInt8ToUint8", TestSafeInt8ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint16", "TestSafeInt8ToUint16", TestSafeInt8ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint32", "TestSafeInt8ToUint32", TestSafeInt8ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUintn", "TestSafeInt8ToUintn", TestSafeInt8ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt8ToUint64", "TestSafeInt8ToUint64", TestSafeInt8ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint8ToInt8", "TestSafeUint8ToInt8", TestSafeUint8ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint8ToChar8", "TestSafeUint8ToChar8", TestSafeUint8ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToInt8", "TestSafeInt16ToInt8", TestSafeInt16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToChar8", "TestSafeInt16ToChar8", TestSafeInt16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint8", "TestSafeInt16ToUint8", TestSafeInt16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint16", "TestSafeInt16ToUint16", TestSafeInt16ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint32", "TestSafeInt16ToUint32", TestSafeInt16ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUintn", "TestSafeInt16ToUintn", TestSafeInt16ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt16ToUint64", "TestSafeInt16ToUint64", TestSafeInt16ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt8", "TestSafeUint16ToInt8", TestSafeUint16ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToChar8", "TestSafeUint16ToChar8", TestSafeUint16ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToUint8", "TestSafeUint16ToUint8", TestSafeUint16ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint16ToInt16", "TestSafeUint16ToInt16", TestSafeUint16ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt8", "TestSafeInt32ToInt8", TestSafeInt32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToChar8", "TestSafeInt32ToChar8", TestSafeInt32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint8", "TestSafeInt32ToUint8", TestSafeInt32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToInt16", "TestSafeInt32ToInt16", TestSafeInt32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint16", "TestSafeInt32ToUint16", TestSafeInt32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint32", "TestSafeInt32ToUint32", TestSafeInt32ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUintn", "TestSafeInt32ToUintn", TestSafeInt32ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt32ToUint64", "TestSafeInt32ToUint64", TestSafeInt32ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt8", "TestSafeUint32ToInt8", TestSafeUint32ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToChar8", "TestSafeUint32ToChar8", TestSafeUint32ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint8", "TestSafeUint32ToUint8", TestSafeUint32ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt16", "TestSafeUint32ToInt16", TestSafeUint32ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToUint16", "TestSafeUint32ToUint16", TestSafeUint32ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToInt32", "TestSafeUint32ToInt32", TestSafeUint32ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint32ToIntn", "TestSafeUint32ToIntn", TestSafeUint32ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt8", "TestSafeIntnToInt8", TestSafeIntnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToChar8", "TestSafeIntnToChar8", TestSafeIntnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint8", "TestSafeIntnToUint8", TestSafeIntnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt16", "TestSafeIntnToInt16", TestSafeIntnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint16", "TestSafeIntnToUint16", TestSafeIntnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToInt32", "TestSafeIntnToInt32", TestSafeIntnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint32", "TestSafeIntnToUint32", TestSafeIntnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUintn", "TestSafeIntnToUintn", TestSafeIntnToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeIntnToUint64", "TestSafeIntnToUint64", TestSafeIntnToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt8", "TestSafeUintnToInt8", TestSafeUintnToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToChar8", "TestSafeUintnToChar8", TestSafeUintnToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint8", "TestSafeUintnToUint8", TestSafeUintnToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt16", "TestSafeUintnToInt16", TestSafeUintnToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint16", "TestSafeUintnToUint16", TestSafeUintnToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt32", "TestSafeUintnToInt32", TestSafeUintnToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToUint32", "TestSafeUintnToUint32", TestSafeUintnToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToIntn", "TestSafeUintnToIntn", TestSafeUintnToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUintnToInt64", "TestSafeUintnToInt64", TestSafeUintnToInt64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt8", "TestSafeInt64ToInt8", TestSafeInt64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToChar8", "TestSafeInt64ToChar8", TestSafeInt64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint8", "TestSafeInt64ToUint8", TestSafeInt64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt16", "TestSafeInt64ToInt16", TestSafeInt64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint16", "TestSafeInt64ToUint16", TestSafeInt64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToInt32", "TestSafeInt64ToInt32", TestSafeInt64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint32", "TestSafeInt64ToUint32", TestSafeInt64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToIntn", "TestSafeInt64ToIntn", TestSafeInt64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUintn", "TestSafeInt64ToUintn", TestSafeInt64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeInt64ToUint64", "TestSafeInt64ToUint64", TestSafeInt64ToUint64, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt8", "TestSafeUint64ToInt8", TestSafeUint64ToInt8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToChar8", "TestSafeUint64ToChar8", TestSafeUint64ToChar8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint8", "TestSafeUint64ToUint8", TestSafeUint64ToUint8, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt16", "TestSafeUint64ToInt16", TestSafeUint64ToInt16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint16", "TestSafeUint64ToUint16", TestSafeUint64ToUint16, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt32", "TestSafeUint64ToInt32", TestSafeUint64ToInt32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUint32", "TestSafeUint64ToUint32", TestSafeUint64ToUint32, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToIntn", "TestSafeUint64ToIntn", TestSafeUint64ToIntn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToUintn", "TestSafeUint64ToUintn", TestSafeUint64ToUintn, NULL, NULL, NULL); + AddTestCase(ConversionTestSuite, "Test SafeUint64ToInt64", "TestSafeUint64ToInt64", TestSafeUint64ToInt64, NULL, NULL, NULL); // // Test the addition and subtraction functions // - Status = CreateUnitTestSuite(&AdditionSubtractionTestSuite, Fw, "Int Safe Add/Subtract Test Suite", "Common.SafeInt.AddSubtract", NULL, NULL); + Status = CreateUnitTestSuite(&AdditionSubtractionTestSuite, Framework, "Int Safe Add/Subtract Test Suite", "Common.SafeInt.AddSubtract", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Add/Subtract Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Add", "Common.SafeInt.AddSubtract.TestSafeUint8Add", TestSafeUint8Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Add", "Common.SafeInt.AddSubtract.TestSafeUint16Add", TestSafeUint16Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Add", "Common.SafeInt.AddSubtract.TestSafeUint32Add", TestSafeUint32Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnAdd", "Common.SafeInt.AddSubtract.TestSafeUintnAdd", TestSafeUintnAdd, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Add", "Common.SafeInt.AddSubtract.TestSafeUint64Add", TestSafeUint64Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Add", "Common.SafeInt.AddSubtract.TestSafeInt8Add", TestSafeInt8Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Add", "Common.SafeInt.AddSubtract.TestSafeInt16Add", TestSafeInt16Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Add", "Common.SafeInt.AddSubtract.TestSafeInt32Add", TestSafeInt32Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnAdd", "Common.SafeInt.AddSubtract.TestSafeIntnAdd", TestSafeIntnAdd, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Add", "Common.SafeInt.AddSubtract.TestSafeInt64Add", TestSafeInt64Add, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Sub", "Common.SafeInt.AddSubtract.TestSafeUint8Sub", TestSafeUint8Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Sub", "Common.SafeInt.AddSubtract.TestSafeUint16Sub", TestSafeUint16Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Sub", "Common.SafeInt.AddSubtract.TestSafeUint32Sub", TestSafeUint32Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnSub", "Common.SafeInt.AddSubtract.TestSafeUintnSub", TestSafeUintnSub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Sub", "Common.SafeInt.AddSubtract.TestSafeUint64Sub", TestSafeUint64Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Sub", "Common.SafeInt.AddSubtract.TestSafeInt8Sub", TestSafeInt8Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Sub", "Common.SafeInt.AddSubtract.TestSafeInt16Sub", TestSafeInt16Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Sub", "Common.SafeInt.AddSubtract.TestSafeInt32Sub", TestSafeInt32Sub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnSub", "Common.SafeInt.AddSubtract.TestSafeIntnSub", TestSafeIntnSub, NULL, NULL, NULL); - AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Sub", "Common.SafeInt.AddSubtract.TestSafeInt64Sub", TestSafeInt64Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Add", "TestSafeUint8Add", TestSafeUint8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Add", "TestSafeUint16Add", TestSafeUint16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Add", "TestSafeUint32Add", TestSafeUint32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnAdd", "TestSafeUintnAdd", TestSafeUintnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Add", "TestSafeUint64Add", TestSafeUint64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Add", "TestSafeInt8Add", TestSafeInt8Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Add", "TestSafeInt16Add", TestSafeInt16Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Add", "TestSafeInt32Add", TestSafeInt32Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnAdd", "TestSafeIntnAdd", TestSafeIntnAdd, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Add", "TestSafeInt64Add", TestSafeInt64Add, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint8Sub", "TestSafeUint8Sub", TestSafeUint8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint16Sub", "TestSafeUint16Sub", TestSafeUint16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint32Sub", "TestSafeUint32Sub", TestSafeUint32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUintnSub", "TestSafeUintnSub", TestSafeUintnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeUint64Sub", "TestSafeUint64Sub", TestSafeUint64Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt8Sub", "TestSafeInt8Sub", TestSafeInt8Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt16Sub", "TestSafeInt16Sub", TestSafeInt16Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt32Sub", "TestSafeInt32Sub", TestSafeInt32Sub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeIntnSub", "TestSafeIntnSub", TestSafeIntnSub, NULL, NULL, NULL); + AddTestCase(AdditionSubtractionTestSuite, "Test SafeInt64Sub", "TestSafeInt64Sub", TestSafeInt64Sub, NULL, NULL, NULL); // // Test the multiplication functions // - Status = CreateUnitTestSuite(&MultiplicationTestSuite, Fw, "Int Safe Multiply Test Suite", "Common.SafeInt.Multiply", NULL, NULL); + Status = CreateUnitTestSuite(&MultiplicationTestSuite, Framework, "Int Safe Multiply Test Suite", "Common.SafeInt.Multiply", NULL, NULL); if (EFI_ERROR(Status)) { DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for Int Safe Multiply Test Suite\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase(MultiplicationTestSuite, "Test SafeUint8Mult", "Common.SafeInt.Multiply.TestSafeUint8Mult", TestSafeUint8Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeUint16Mult", "Common.SafeInt.Multiply.TestSafeUint16Mult", TestSafeUint16Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeUint32Mult", "Common.SafeInt.Multiply.TestSafeUint32Mult", TestSafeUint32Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeUintnMult", "Common.SafeInt.Multiply.TestSafeUintnMult", TestSafeUintnMult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeUint64Mult", "Common.SafeInt.Multiply.TestSafeUint64Mult", TestSafeUint64Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeInt8Mult", "Common.SafeInt.Multiply.TestSafeInt8Mult", TestSafeInt8Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeInt16Mult", "Common.SafeInt.Multiply.TestSafeInt16Mult", TestSafeInt16Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeInt32Mult", "Common.SafeInt.Multiply.TestSafeInt32Mult", TestSafeInt32Mult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeIntnMult", "Common.SafeInt.Multiply.TestSafeIntnMult", TestSafeIntnMult, NULL, NULL, NULL); - AddTestCase(MultiplicationTestSuite, "Test SafeInt64Mult", "Common.SafeInt.Multiply.TestSafeInt64Mult", TestSafeInt64Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint8Mult", "TestSafeUint8Mult", TestSafeUint8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint16Mult", "TestSafeUint16Mult", TestSafeUint16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint32Mult", "TestSafeUint32Mult", TestSafeUint32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUintnMult", "TestSafeUintnMult", TestSafeUintnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeUint64Mult", "TestSafeUint64Mult", TestSafeUint64Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt8Mult", "TestSafeInt8Mult", TestSafeInt8Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt16Mult", "TestSafeInt16Mult", TestSafeInt16Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt32Mult", "TestSafeInt32Mult", TestSafeInt32Mult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeIntnMult", "TestSafeIntnMult", TestSafeIntnMult, NULL, NULL, NULL); + AddTestCase(MultiplicationTestSuite, "Test SafeInt64Mult", "TestSafeInt64Mult", TestSafeInt64Mult, NULL, NULL, NULL); // // Execute the tests. // - Status = RunAllTestSuites(Fw); + Status = RunAllTestSuites(Framework); EXIT: - if (Fw != NULL) { - FreeUnitTestFramework(Fw); + if (Framework != NULL) { + FreeUnitTestFramework(Framework); } return Status; diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index c1d8ee8f7ca..93bbe899254 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -35,7 +35,6 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include #include #include #include diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf index 7bc63699c46..27a7200fe11 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf @@ -50,7 +50,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] BaseLib diff --git a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h index a6eed7ecb21..ab06d4f239f 100644 --- a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h @@ -22,14 +22,6 @@ #define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. #define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) -typedef UINT32 UNIT_TEST_STATUS; -#define UNIT_TEST_PASSED (0) -#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) -#define UNIT_TEST_ERROR_TEST_FAILED (2) -#define UNIT_TEST_SKIPPED (0xFFFFFFFD) -#define UNIT_TEST_RUNNING (0xFFFFFFFE) -#define UNIT_TEST_PENDING (0xFFFFFFFF) - typedef UINT32 FAILURE_TYPE; #define FAILURETYPE_NOFAILURE (0) #define FAILURETYPE_OTHER (1) @@ -41,69 +33,6 @@ typedef UINT32 FAILURE_TYPE; #define FAILURETYPE_ASSERTSTATUSEQUAL (7) #define FAILURETYPE_ASSERTNOTNULL (8) -typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. -typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. -typedef VOID* UNIT_TEST_CONTEXT; - - -///================================================================================================ -///================================================================================================ -/// -/// UNIT TEST FUNCTION TYPE DEFINITIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Unit-Test Function pointer type. -// -typedef -UNIT_TEST_STATUS -(EFIAPI *UNIT_TEST_FUNCTION) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Prerequisite Function pointer type. -// NOTE: Should be the same as UnitTest. -// -typedef -UNIT_TEST_STATUS -(EFIAPI *UNIT_TEST_PREREQ) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Test Cleanup (after) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_CLEANUP) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Test Suite Setup (before) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_SUITE_SETUP) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework - ); - -// -// Unit-Test Test Suite Teardown (after) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_SUITE_TEARDOWN) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework - ); - ///================================================================================================ ///================================================================================================ @@ -113,7 +42,6 @@ VOID ///================================================================================================ ///================================================================================================ - typedef struct { CHAR8 *Description; CHAR8 *ClassName; //can't have spaces and should be short @@ -162,7 +90,6 @@ typedef struct { VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. } UNIT_TEST_FRAMEWORK; - // //Structures for the framework to serializing unit test status // @@ -174,14 +101,14 @@ typedef struct CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; FAILURE_TYPE FailureType; UNIT_TEST_STATUS Result; - // CHAR8 Log[]; + CHAR8 Log[]; } UNIT_TEST_SAVE_TEST; typedef struct { UINT32 Size; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. - // UINT8 Data[]; // Actual data of the context. + UINT8 Data[]; // Actual data of the context. } UNIT_TEST_SAVE_CONTEXT; typedef struct diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf index 8924000298d..20eaa2b9eca 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf @@ -24,7 +24,7 @@ cmocka/src/cmocka.c [Packages] - CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [BuildOptions] MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c index b4e9e3d3332..bfd5593c200 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c @@ -13,11 +13,13 @@ #include #include -#include #include #include #include +#include +#include + #define MAX_STRING_SIZE 1025 BOOLEAN diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf index bd4022207ce..a75a03312e5 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf @@ -19,8 +19,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec - CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Sources] UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index 4e1a32104cf..8480405599d 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -31,7 +31,7 @@ LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c index af62d1e385b..1eb5f88aa2f 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c @@ -13,13 +13,15 @@ #include #include -#include #include #include #include #include #include +#include +#include + #define MAX_STRING_SIZE 1025 int GroupSetupTemplate (void **state); diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf index 70c6dd8b763..aabe64232fe 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf @@ -21,9 +21,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec - HostBasedUnitTestPkg/HostBasedUnitTestPkg.dec - CmockaHostUnitTestPkg/CmockaHostUnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Sources] UnitTestLib.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c index 86bacface25..aa5a3047d3c 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c @@ -21,9 +21,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. **/ #include -#include #include -//#include #include #include #include @@ -33,6 +31,9 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include +#include +#include + /** TODO: STUFF!! diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf index f5d56bde948..0b57b61fd84 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf @@ -43,7 +43,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec ShellPkg/ShellPkg.dec diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index fa65ad39462..93b3c0b0e43 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -19,7 +19,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. **/ #include -#include +#include #include #include diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf index 3230c4ea337..a39e99b43a8 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -41,4 +41,4 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c index 959ff50d240..21f88b6a599 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c @@ -6,7 +6,7 @@ Copyright (c) Microsoft **/ #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf index 3c18cc7ceba..644c6032a08 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf @@ -24,7 +24,7 @@ LIBRARY_CLASS = UnitTestResultReportLib [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c index a1ff5ae4130..efc6d2e5d71 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c @@ -6,7 +6,7 @@ Copyright (c) Microsoft **/ #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf index a5e70997c50..12a00f63814 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf @@ -27,7 +27,7 @@ LIBRARY_CLASS = UnitTestResultReportLib|DXE_DRIVER UEFI_APPLICATION [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h index 8d899f9cf70..ea40a8acf9b 100644 --- a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h +++ b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h @@ -11,9 +11,19 @@ #ifndef __UNIT_TEST_LIB_H__ #define __UNIT_TEST_LIB_H__ +typedef UINT32 UNIT_TEST_STATUS; +#define UNIT_TEST_PASSED (0) +#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) +#define UNIT_TEST_ERROR_TEST_FAILED (2) +#define UNIT_TEST_SKIPPED (0xFFFFFFFD) +#define UNIT_TEST_RUNNING (0xFFFFFFFE) +#define UNIT_TEST_PENDING (0xFFFFFFFF) + typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. typedef VOID* UNIT_TEST_CONTEXT; + + ///================================================================================================ ///================================================================================================ /// @@ -22,7 +32,6 @@ typedef VOID* UNIT_TEST_CONTEXT; ///================================================================================================ ///================================================================================================ - // // Unit-Test Function pointer type. // @@ -73,6 +82,14 @@ VOID ); +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST FUNCTION DEFINITIONS +/// +///================================================================================================ +///================================================================================================ + /* Method to Initialize the Unit Test framework @@ -109,8 +126,8 @@ Creates Unit Test Suite in the Unit Test Framework EFI_STATUS EFIAPI CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE **Suite, - IN UNIT_TEST_FRAMEWORK *Framework, + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN CHAR8 *Title, IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, @@ -134,31 +151,31 @@ Adds test case to Suite EFI_STATUS EFIAPI AddTestCase ( - IN UNIT_TEST_SUITE *Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL + IN UNIT_TEST_SUITE_HANDLE Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL ); EFI_STATUS EFIAPI RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_SUITE_HANDLE Framework ); EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_SUITE_HANDLE Framework ); EFI_STATUS EFIAPI SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, IN UINTN ContextToSaveSize ); diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c index b8dc0a865b4..152b9021f2d 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c @@ -6,7 +6,7 @@ Copyright (c) Microsoft **/ #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf index ff6360a0c47..1a822c48b0e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf @@ -28,7 +28,7 @@ LIBRARY_CLASS = UnitTestAssertLib [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 2e70f73217a..07a8f0a1ded 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -7,7 +7,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf index 86e6779c5c8..5c967546491 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf @@ -34,7 +34,7 @@ LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf index ced85aca3d1..cedfca0221a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -32,7 +32,7 @@ LIBRARY_CLASS = UnitTestLib|PEIM [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf index 093fa6575b8..37ec70edc74 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf @@ -33,7 +33,7 @@ LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c index e793a4e0d06..47f69d555d3 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -6,7 +6,7 @@ Copyright (c) Microsoft **/ #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf index 9726ad06eb0..a0996d59ea0 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf @@ -28,7 +28,7 @@ LIBRARY_CLASS = UnitTestLogLib [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Guids] diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 0cbef7fa2fd..fec429d831e 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -21,7 +21,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include +#include #include #include #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf index 9b7e0d9e6e3..f75d2a9bb71 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -22,7 +22,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 1ed0e462186..6b7ef5b1cbd 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -21,7 +21,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include +#include #include #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf index e9677d79bc1..7ae0b6b8361 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -22,7 +22,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index 89974cf25d9..31264eebfd2 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -21,7 +21,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include +#include #include #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf index 9fad2c994ce..4754173dc6b 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -23,7 +23,7 @@ [Packages] MdePkg/MdePkg.dec - UnitTestPkg/UnitTestPkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/UnitTestPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml similarity index 100% rename from UnitTestFrameworkPkg/UnitTestPkg.ci.yaml rename to UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml diff --git a/UnitTestFrameworkPkg/UnitTestPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec similarity index 94% rename from UnitTestFrameworkPkg/UnitTestPkg.dec rename to UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 17756c06eb2..825f8e11eec 100644 --- a/UnitTestFrameworkPkg/UnitTestPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -21,6 +21,8 @@ [Includes.Common.Private] FrameworkInclude + FrameworkLibrary/CmockaLib/cmocka/include + FrameworkLibrary/CmockaLib/cmocka/include/cmockery [LibraryClasses] ## @libraryclass Provide unit test assert helpers diff --git a/UnitTestFrameworkPkg/UnitTestPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc similarity index 100% rename from UnitTestFrameworkPkg/UnitTestPkg.dsc rename to UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc From 42cabb69b160bb70b9508e8c954e00e2a4439531 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 22:26:07 -0800 Subject: [PATCH 204/384] Clean up a few more interfaces. --- .../UnitTestLibcmocka/UnitTestLib.c | 60 ++------- .../Library/UnitTestLib/UnitTestLib.c | 123 ++---------------- 2 files changed, 28 insertions(+), 155 deletions(-) diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c index 1eb5f88aa2f..f05010886e2 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c @@ -180,10 +180,10 @@ Method to Initialize the Unit Test framework EFI_STATUS EFIAPI InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK **Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString ) { EFI_STATUS Status; @@ -247,8 +247,8 @@ InitUnitTestFramework ( EFI_STATUS EFIAPI CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE **Suite, - IN UNIT_TEST_FRAMEWORK *Framework, + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN CHAR8 *Title, IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, @@ -330,13 +330,13 @@ CreateUnitTestSuite ( EFI_STATUS EFIAPI AddTestCase ( - IN UNIT_TEST_SUITE *Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL + IN UNIT_TEST_SUITE_HANDLE Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL ) { EFI_STATUS Status; @@ -431,7 +431,7 @@ AddTestCase ( EFI_STATUS EFIAPI RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ) { EFI_STATUS Status; @@ -516,35 +516,3 @@ SaveFrameworkState ( { return EFI_UNSUPPORTED; } // SaveFrameworkState() - - -EFI_STATUS -EFIAPI -SaveFrameworkStateAndQuit ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - return EFI_UNSUPPORTED; -} // SaveFrameworkStateAndQuit() - - -/** - NOTE: Takes in a ResetType, but currently only supports EfiResetCold - and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. - If a more specific reset is required, use SaveFrameworkState() and - call gRT->ResetSystem() directly. - -**/ -EFI_STATUS -EFIAPI -SaveFrameworkStateAndReboot ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize, - IN EFI_RESET_TYPE ResetType - ) -{ - return EFI_UNSUPPORTED; -} // SaveFrameworkStateAndReboot() diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 07a8f0a1ded..cf46f008bc5 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -197,10 +197,10 @@ Method to Initialize the Unit Test framework EFI_STATUS EFIAPI InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK **Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString ) { EFI_STATUS Status = EFI_SUCCESS; @@ -283,8 +283,8 @@ InitUnitTestFramework ( EFI_STATUS EFIAPI CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE **Suite, - IN UNIT_TEST_FRAMEWORK *Framework, + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN CHAR8 *Title, IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, @@ -355,13 +355,13 @@ CreateUnitTestSuite ( EFI_STATUS EFIAPI AddTestCase ( - IN UNIT_TEST_SUITE *Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL + IN UNIT_TEST_SUITE_HANDLE Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL ) { EFI_STATUS Status = EFI_SUCCESS; @@ -534,7 +534,7 @@ RunTestSuite ( EFI_STATUS EFIAPI RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ) { UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; @@ -850,98 +850,3 @@ SaveFrameworkState ( return Status; } // SaveFrameworkState() - - -EFI_STATUS -EFIAPI -SaveFrameworkStateAndQuit ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - EFI_STATUS Status; - - // - // First, let's not make assumptions about the parameters. - if (FrameworkHandle == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Now, save all the data associated with this framework. - Status = SaveFrameworkState( FrameworkHandle, ContextToSave, ContextToSaveSize ); - - // - // If we're all good, let's book... - if (!EFI_ERROR( Status )) - { - // - // Free data that was used. - FreeUnitTestFramework( (UNIT_TEST_FRAMEWORK*)FrameworkHandle ); - - // - // Quit - FrameworkExit (); - DEBUG(( DEBUG_ERROR, "%a - Unit test failed to quit! Framework can no longer be used!\n", __FUNCTION__ )); - - // - // We REALLY shouldn't be here. - Status = EFI_ABORTED; - } - - return Status; -} // SaveFrameworkStateAndQuit() - - -/** - NOTE: Takes in a ResetType, but currently only supports EfiResetCold - and EfiResetWarm. All other types will return EFI_INVALID_PARAMETER. - If a more specific reset is required, use SaveFrameworkState() and - call gRT->ResetSystem() directly. - -**/ -EFI_STATUS -EFIAPI -SaveFrameworkStateAndReboot ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize, - IN EFI_RESET_TYPE ResetType - ) -{ - EFI_STATUS Status; - - // - // First, let's not make assumptions about the parameters. - if (FrameworkHandle == NULL || - (ResetType != EfiResetCold && ResetType != EfiResetWarm)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Now, save all the data associated with this framework. - Status = SaveFrameworkState( FrameworkHandle, ContextToSave, ContextToSaveSize ); - - // - // If we're all good, let's book... - if (!EFI_ERROR( Status )) - { - // - // Free data that was used. - FreeUnitTestFramework( (UNIT_TEST_FRAMEWORK*)FrameworkHandle ); - - // - // Reset - FrameworkResetSystem (ResetType); - DEBUG(( DEBUG_ERROR, "%a - Unit test failed to quit! Framework can no longer be used!\n", __FUNCTION__ )); - - // - // We REALLY shouldn't be here. - Status = EFI_ABORTED; - } - - return Status; -} // SaveFrameworkStateAndReboot() From af9d862cbfa2eb1e0a4fdfef0a5d4068c32d40c8 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 18 Dec 2019 22:54:12 -0800 Subject: [PATCH 205/384] DSC and DEC issues are resolved. Need to get build working. --- .pytool/CISettings.py | 2 +- .../UnitTestBootLibUsbClass.inf | 2 +- .../UnitTestFrameworkPkg.ci.yaml | 11 ++-- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 18 ++++-- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 63 ++++++++++--------- 5 files changed, 56 insertions(+), 40 deletions(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 21343e4b9a0..72e1feccf8b 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -50,7 +50,7 @@ def GetPackagesSupported(self): "ShellPkg", "FatPkg", "CryptoPkg", - "UnitTestPkg" + "UnitTestFrameworkPkg" ) def GetArchitecturesSupported(self): diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index 8480405599d..a4932f6e11f 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -16,7 +16,7 @@ INF_VERSION = 0x00010017 BASE_NAME = UnitTestBootLibUsbClass FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER +MODULE_TYPE = UEFI_APPLICATION LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 2a78b3211ad..2ac3fc15e4f 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -6,7 +6,7 @@ ## { "CompilerPlugin": { - "DscPath": "UnitTestPkg.dsc" + "DscPath": "UnitTestFrameworkPkg.dsc" }, "CharEncodingCheck": { "IgnoreFiles": [] @@ -14,16 +14,19 @@ "DependencyCheck": { "AcceptableDependencies": [ "MdePkg/MdePkg.dec", - "UnitTestPkg/UnitTestPkg.dec" + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" ], # For host based unit tests "AcceptableDependencies-HOST_APPLICATION":[], # For UEFI shell based apps - "AcceptableDependencies-UEFI_APPLICATION":[], + "AcceptableDependencies-UEFI_APPLICATION":[ + "MdeModulePkg/MdeModulePkg.dec", + "ShellPkg/ShellPkg.dec" + ], "IgnoreInf": [] }, "DscCompleteCheck": { - "DscPath": "UnitTestPkg.dsc", + "DscPath": "UnitTestFrameworkPkg.dsc", "IgnoreInf": [ ] }, diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 825f8e11eec..47207f0df32 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -37,19 +37,27 @@ # UnitTestLogLib|Include/Library/UnitTestLogLib.h + ## @libraryclass Abstracts the methods that a test could exit prematurely. + # Allows tests written for different contexts to handle Quit()/Reboot() differently. + # + UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h + [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state # - UnitTestPersistenceLib|Include/Library/UnitTestPersistenceLib.h + UnitTestPersistenceLib|FrameworkInclude/Library/UnitTestPersistenceLib.h ## @libraryclass Provides a unit test result report # - UnitTestResultReportLib|Include/Library/UnitTestResultReportLib.h + UnitTestResultReportLib|FrameworkInclude/Library/UnitTestResultReportLib.h - ## @libraryclass Abstracts the methods that a test could exit prematurely. - # Allows tests written for different contexts to handle Quit()/Reboot() differently. + ## @libraryclass Provides memory allocation routines specific to host-based tests. # - UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h + OsServiceLib|FrameworkInclude/Library/OsServiceLib.h + + ## @libraryclass Provides boot-option routines useful in shell-based tests. + # + UnitTestBootLib|FrameworkInclude/Library/UnitTestBootLib.h [Guids] gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index e18dee053f4..23f55971207 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -1,5 +1,5 @@ ## @file -# UnitTestPkg +# UnitTestFrameworkPkg # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# @@ -8,11 +8,11 @@ ## [Defines] - PLATFORM_NAME = UnitTestPkg + PLATFORM_NAME = UnitTestFrameworkPkg PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 PLATFORM_VERSION = 1.00 DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/UnitTestPkg + OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg SUPPORTED_ARCHITECTURES = IA32|IPF|X64|EBC|ARM|AARCH64 BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT @@ -152,42 +152,47 @@ NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf # - # UnitTestPkg + # UnitTestFrameworkPkg # [LibraryClasses] - UnitTestAssertLib|UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestLogLib|UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPersistenceLib|UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestLogLib|UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.PEIM] - UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf - UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_SMM_DRIVER] - UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf - UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - UnitTestLib|UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf - UnitTestResultReportLib|UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestTerminationLib|UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestTerminationLib|UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf [Components] - UnitTestPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestPkg/Library/UnitTestLib/UnitTestLibDxe.inf - UnitTestPkg/Library/UnitTestLib/UnitTestLibPei.inf - UnitTestPkg/Library/UnitTestLib/UnitTestLibSmm.inf - UnitTestPkg/Library/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf - UnitTestPkg/Library/UnitTestTerminationLibTbd/UnitTestTerminationLibTbd.inf - UnitTestPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf - UnitTestPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf - UnitTestPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf + UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf + UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf + UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf + UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 665afccc52e1a02ee329147e02f04b8e9cf1d571 Mon Sep 17 00:00:00 2001 From: Daniel Pawel Banaszek Date: Tue, 17 Dec 2019 14:39:25 +0100 Subject: [PATCH 206/384] MdePkg PciExpress21: PCI_REG_PCIE_DEVICE_CONTROL2 struct has 17 bits Device Control 2 Structure have an issue. LtrMechanism - there is 2 bits instead of 1. Signed-off-by: Daniel Pawel Banaszek Reviewed-by: Liming Gao Reviewed-by: Ray Ni --- MdePkg/Include/IndustryStandard/PciExpress21.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdePkg/Include/IndustryStandard/PciExpress21.h b/MdePkg/Include/IndustryStandard/PciExpress21.h index f17f5707755..2c07cb560e9 100644 --- a/MdePkg/Include/IndustryStandard/PciExpress21.h +++ b/MdePkg/Include/IndustryStandard/PciExpress21.h @@ -304,7 +304,7 @@ typedef union { UINT16 AtomicOpEgressBlocking : 1; UINT16 IdoRequest : 1; UINT16 IdoCompletion : 1; - UINT16 LtrMechanism : 2; + UINT16 LtrMechanism : 1; UINT16 EmergencyPowerReductionRequest : 1; UINT16 TenBitTagRequesterEnable : 1; UINT16 Obff : 2; From 16acc6179c0fa13f691bf7668855cf1e7e1b7b7d Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 19 Dec 2019 16:02:33 -0800 Subject: [PATCH 207/384] Everything builds again! Only a few things left to check. --- .../UnitTestPersistenceLibFileSystem.c | 26 +++++++++++++---- .../UnitTestPersistenceLibNull.c | 3 +- .../UnitTestResultReportLibDebug.c | 6 ++-- .../UnitTestResultReportLibPlainTextOutput.c | 6 ++-- .../UnitTestTerminationLibShell.c | 3 ++ .../UnitTestTerminationLibShell.inf | 4 ++- .../Include/Library/UnitTestLib.h | 1 + .../Include/Library/UnitTestLogLib.h | 11 +++++--- .../UnitTestAssertLib/UnitTestAssertLib.c | 6 ++-- .../Library/UnitTestLib/UnitTestLib.c | 28 +++++++++++++------ .../Library/UnitTestLib/UnitTestLibDxe.inf | 1 - .../Library/UnitTestLib/UnitTestLibPei.inf | 1 - .../Library/UnitTestLib/UnitTestLibSmm.inf | 1 - .../Library/UnitTestLogLib/UnitTestLogLib.c | 20 ++++++++----- .../SampleUnitTestApp/SampleUnitTestApp.c | 3 +- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 3 +- .../SampleUnitTestSmm/SampleUnitTestSmm.c | 3 +- .../UnitTestFrameworkPkg.ci.yaml | 6 ++++ UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 7 +---- 19 files changed, 94 insertions(+), 45 deletions(-) diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c index aa5a3047d3c..6c3f9867c99 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c @@ -21,7 +21,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. **/ #include -#include #include #include #include @@ -33,6 +32,7 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include +#include /** TODO: STUFF!! @@ -51,6 +51,7 @@ GetCacheFileDevicePath ( UNIT_TEST_FRAMEWORK *Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; CHAR16 *AppPath = NULL, *CacheFilePath = NULL; + CHAR16 *TestName = NULL; CHAR16 *FileSuffix = L"_Cache.dat"; UINTN DirectorySlashOffset, CacheFilePathLength; EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath = NULL; @@ -68,6 +69,14 @@ GetCacheFileDevicePath ( return NULL; } + // Before we can start, we should change our test name from ASCII to Unicode. + CacheFilePathLength = AsciiStrLen( Framework->ShortTitle ) + 1; + TestName = AllocatePool( CacheFilePathLength ); + if (!TestName) { + goto Exit; + } + AsciiStrToUnicodeStrS( Framework->ShortTitle, TestName, CacheFilePathLength ); + // // Now we should have the device path of the root device and a file path for the rest. // In order to target the directory for the test application, we must process @@ -109,17 +118,20 @@ GetCacheFileDevicePath ( // Now we know some things, we're ready to produce our output string, I think. // CacheFilePathLength = DirectorySlashOffset + 1; - CacheFilePathLength += StrLen( Framework->ShortTitle ); + CacheFilePathLength += StrLen( TestName ); CacheFilePathLength += StrLen( FileSuffix ); CacheFilePathLength += 1; // Don't forget the NULL terminator. CacheFilePath = AllocateZeroPool( CacheFilePathLength * sizeof( CHAR16 ) ); + if (!CacheFilePath) { + goto Exit; + } // // Let's produce our final path string, shall we? // - StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. - StrCatS( CacheFilePath, CacheFilePathLength, Framework->ShortTitle ); // Copy the base name for the test cache. - StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. + StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. + StrCatS( CacheFilePath, CacheFilePathLength, TestName ); // Copy the base name for the test cache. + StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. // // Finally, try to create the device path for the thing thing. @@ -136,6 +148,10 @@ GetCacheFileDevicePath ( { FreePool( CacheFilePath); } + if (TestName != NULL) + { + FreePool( TestName); + } return CacheFileDevicePath; } // GetCacheFileDevicePath() diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index 93b3c0b0e43..fff53b3f80f 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -19,8 +19,9 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. **/ #include -#include + #include +#include #include diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c index 21f88b6a599..3d74bc6dcfa 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c @@ -6,12 +6,14 @@ Copyright (c) Microsoft **/ #include -#include #include #include -#include #include +#include +#include +#include + struct _UNIT_TEST_STATUS_STRING diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c index efc6d2e5d71..33d37c4fbcb 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c @@ -6,13 +6,15 @@ Copyright (c) Microsoft **/ #include -#include #include #include #include -#include #include +#include +#include +#include + struct _UNIT_TEST_STATUS_STRING diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c index 57f66f1b0ab..6dfa3a0c357 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c @@ -7,6 +7,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include +#include + +#include /** diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf index b837b1a6df2..ef539b73518 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf @@ -12,7 +12,7 @@ BASE_NAME = UnitTestTerminationLibShell FILE_GUID = E5C189CF-CA58-45C0-9EA9-C30D04FB705D VERSION_STRING = 1.0 - MODULE_TYPE = DXE_DRIVER + MODULE_TYPE = UEFI_APPLICATION LIBRARY_CLASS = UnitTestTerminationLib|UEFI_APPLICATION # @@ -28,8 +28,10 @@ [Packages] MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] UefiBootServicesTableLib + UefiRuntimeServicesTableLib UnitTestBootLib diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h index ea40a8acf9b..77c7d088ee8 100644 --- a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h +++ b/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h @@ -21,6 +21,7 @@ typedef UINT32 UNIT_TEST_STATUS; typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. +typedef VOID* UNIT_TEST_HANDLE; // Same as a UNIT_TEST*, but with fewer build errors. typedef VOID* UNIT_TEST_CONTEXT; diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h b/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h index e83e3fb8b62..ce8b2af0935 100644 --- a/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h +++ b/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h @@ -43,14 +43,17 @@ UnitTestLog ( ... ); +// TODO: This header should not require the framework types. + VOID EFIAPI UnitTestLogInit ( -IN OUT UNIT_TEST *Test, -IN UINT8 *Buffer OPTIONAL, -IN UINTN BufferSize -); + IN OUT UNIT_TEST_HANDLE Test, + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize + ); +// TODO: Drop this from the lib interface. VOID EFIAPI UnitTestLogFailure( diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c index 152b9021f2d..1a98ae73408 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c @@ -6,12 +6,14 @@ Copyright (c) Microsoft **/ #include -#include -#include #include #include #include +#include +#include +#include + BOOLEAN EFIAPI diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index cf46f008bc5..9efb39a32e1 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -7,16 +7,16 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include -#include #include #include #include #include + #include +#include #include #include #include -#include // Prototyped here so that it can be included near the functions that @@ -284,7 +284,7 @@ EFI_STATUS EFIAPI CreateUnitTestSuite ( OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, IN CHAR8 *Title, IN CHAR8 *Package, IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, @@ -293,6 +293,9 @@ CreateUnitTestSuite ( { EFI_STATUS Status = EFI_SUCCESS; UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + UNIT_TEST_FRAMEWORK *Framework; + + Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; // // First, let's check to make sure that our parameters look good. @@ -355,7 +358,7 @@ CreateUnitTestSuite ( EFI_STATUS EFIAPI AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE Suite, + IN UNIT_TEST_SUITE_HANDLE SuiteHandle, IN CHAR8 *Description, IN CHAR8 *ClassName, IN UNIT_TEST_FUNCTION Func, @@ -366,7 +369,11 @@ AddTestCase ( { EFI_STATUS Status = EFI_SUCCESS; UNIT_TEST_LIST_ENTRY *NewTestEntry; - UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; + UNIT_TEST_FRAMEWORK *ParentFramework; + UNIT_TEST_SUITE *Suite; + + Suite = (UNIT_TEST_SUITE*)SuiteHandle; + ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; // // First, let's check to make sure that our parameters look good. @@ -533,12 +540,15 @@ RunTestSuite ( EFI_STATUS EFIAPI -RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework +RunAllTestSuites ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle ) { - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + EFI_STATUS Status; + + Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; if (Framework == NULL) { diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf index 5c967546491..3b4be9598ae 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf @@ -29,7 +29,6 @@ LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION UnitTestLogLib UnitTestPersistenceLib UnitTestResultReportLib - UnitTestTerminationLib [Packages] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf index cedfca0221a..15b34fb8b55 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -27,7 +27,6 @@ LIBRARY_CLASS = UnitTestLib|PEIM UnitTestLogLib UnitTestPersistenceLib UnitTestResultReportLib - UnitTestTerminationLib [Packages] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf index 37ec70edc74..ea0b475cafc 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf @@ -28,7 +28,6 @@ LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER UnitTestLogLib UnitTestPersistenceLib UnitTestResultReportLib - UnitTestTerminationLib [Packages] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c index 47f69d555d3..8516c9dac5c 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -6,8 +6,6 @@ Copyright (c) Microsoft **/ #include -#include -#include #include #include #include @@ -15,11 +13,14 @@ Copyright (c) Microsoft #include #include +#include +#include +#include + #define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) #define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) - struct _UNIT_TEST_LOG_PREFIX_STRING { UNIT_TEST_STATUS LogLevel; @@ -138,11 +139,15 @@ AddUnitTestFailure( VOID EFIAPI UnitTestLogInit ( -IN OUT UNIT_TEST *Test, -IN UINT8 *Buffer, -IN UINTN BufferSize -) + IN OUT UNIT_TEST_HANDLE TestHandle, + IN UINT8 *Buffer, + IN UINTN BufferSize + ) { + UNIT_TEST *Test; + + Test = (UNIT_TEST*)TestHandle; + // // Make sure that you're cooking with gas. // @@ -221,6 +226,7 @@ UnitTestLog ( return; } +// TODO: Move this function and all referenced functions to the Assert Lib that uses it. VOID EFIAPI UnitTestLogFailure( diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index fec429d831e..3a0ff1dab77 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -21,8 +21,9 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include + #include +#include #include #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 6b7ef5b1cbd..2512cbb4694 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -21,8 +21,9 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include + #include +#include #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index 31264eebfd2..1e1005c17a9 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -21,8 +21,9 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include #include -#include + #include +#include #include diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 2ac3fc15e4f..1e11bcd9822 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -28,6 +28,12 @@ "DscCompleteCheck": { "DscPath": "UnitTestFrameworkPkg.dsc", "IgnoreInf": [ + # Don't need to build these. + # These are host-based only. + "UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf", + "UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", + "UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf", + "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf" ] }, "GuidCheck": { diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 23f55971207..1e70f1e990a 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -101,8 +101,6 @@ DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf - ResetUtilityLib|MdeModulePkg/Library/ResetUtilityLib/ResetUtilityLib.inf ## MS_CHANGE - HwResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf ## MS_CHANGE SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf @@ -158,6 +156,7 @@ UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestLogLib|UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf UnitTestPersistenceLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + #UnitTestBootLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf [LibraryClasses.common.PEIM] UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -182,12 +181,8 @@ UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf - UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf - UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf From ec4bd558831a11e0a921dab84072c5ba8a4acd4f Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 19 Dec 2019 17:50:13 -0800 Subject: [PATCH 208/384] Clarify sizes and update the way the dynamic structure elements are done. --- .../FrameworkInclude/UnitTestFrameworkTypes.h | 6 +++--- .../UnitTestPersistenceLibFileSystem.c | 4 ++-- UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c | 6 +++--- 3 files changed, 8 insertions(+), 8 deletions(-) diff --git a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h index ab06d4f239f..03e55850c21 100644 --- a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h @@ -96,7 +96,7 @@ typedef struct { typedef struct { - UINT32 Size; + UINT32 Size; // Size of the UNIT_TEST_SAVE_TEST including Log[] UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; FAILURE_TYPE FailureType; @@ -106,7 +106,7 @@ typedef struct typedef struct { - UINT32 Size; + UINT32 Size; // Size of the UNIT_TEST_SAVE_CONTEXT including Data[] UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. UINT8 Data[]; // Actual data of the context. } UNIT_TEST_SAVE_CONTEXT; @@ -114,7 +114,7 @@ typedef struct typedef struct { UINT8 Version; - UINT32 BlobSize; + UINT32 SaveStateSize; // Size of the entire serialized buffer. UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. EFI_TIME StartTime; UINT32 TestCount; diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c index 6c3f9867c99..204552e8554 100644 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c +++ b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c @@ -274,13 +274,13 @@ SaveUnitTestCache ( // // Write the data to the file. // - WriteCount = SaveData->BlobSize; + WriteCount = SaveData->SaveStateSize; DEBUG(( DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount )); Status = ShellWriteFile( FileHandle, &WriteCount, SaveData ); - if (EFI_ERROR( Status ) || WriteCount != SaveData->BlobSize) + if (EFI_ERROR( Status ) || WriteCount != SaveData->SaveStateSize) { DEBUG(( DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status )); } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 9efb39a32e1..28bfea844f7 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -650,7 +650,7 @@ UpdateTestFromSave ( // fast and loose with data buffers. if (MatchingTest->Size > sizeof( UNIT_TEST_SAVE_TEST )) { - UnitTestLogInit(Test, ((UINT8*)MatchingTest + sizeof( UNIT_TEST_SAVE_TEST )), MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); + UnitTestLogInit(Test, (UINT8*)MatchingTest->Log, MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); } } @@ -668,7 +668,7 @@ UpdateTestFromSave ( CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) { // Override the test context with the saved context. - Test->Context = (VOID*)((UINT8*)SavedContext + sizeof( *SavedContext )); + Test->Context = (VOID*)SavedContext->Data; } } @@ -754,7 +754,7 @@ SerializeState ( // // Alright, let's start setting up some data. Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; - Header->BlobSize = TotalSize; + Header->SaveStateSize = TotalSize; CopyMem( &Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); CopyMem( &Header->StartTime, &Framework->StartTime, sizeof( EFI_TIME ) ); Header->TestCount = TestCount; From 796b380ca7d263ca504b82fe5317a78d3546d537 Mon Sep 17 00:00:00 2001 From: Alex James Date: Thu, 28 Nov 2019 13:56:45 +0800 Subject: [PATCH 209/384] MdePkg: Use __builtin_offset with CLANGPDB toolchain BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2393 CLANGPDB does not define __GNUC__, but it does define __clang__. Check for the __clang__ preprocessor definition to use __builtin_offsetof to implement the OFFSET_OF macro. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Alex James Reviewed-by: Liming Gao --- MdePkg/Include/Base.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/MdePkg/Include/Base.h b/MdePkg/Include/Base.h index 4680e641363..e0bcd0ae67a 100644 --- a/MdePkg/Include/Base.h +++ b/MdePkg/Include/Base.h @@ -781,11 +781,9 @@ typedef UINTN *BASE_LIST; @return Offset, in bytes, of field. **/ -#ifdef __GNUC__ -#if __GNUC__ >= 4 +#if (defined(__GNUC__) && __GNUC__ >= 4) || defined(__clang__) #define OFFSET_OF(TYPE, Field) ((UINTN) __builtin_offsetof(TYPE, Field)) #endif -#endif #ifndef OFFSET_OF #define OFFSET_OF(TYPE, Field) ((UINTN) &(((TYPE *)0)->Field)) From ec8c74e8bcc66a43ff766254e68b0504f68e024f Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Wed, 18 Dec 2019 15:13:07 +0800 Subject: [PATCH 210/384] MdePkg/Tcg: Add new definition in TCG PFP spec. The latest TCG PFP specification (TCG PC Client Platform Firmware Profile Specification, Revision 1.05) added new data structure. For example, the SPDM device measurement. This patch adds the new content. Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Jiewen Yao Reviewed-by: Liming Gao --- .../IndustryStandard/UefiTcgPlatform.h | 182 +++++++++++++++++- 1 file changed, 173 insertions(+), 9 deletions(-) diff --git a/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h b/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h index 3f1d444aed0..84023c43476 100644 --- a/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h +++ b/MdePkg/Include/IndustryStandard/UefiTcgPlatform.h @@ -1,7 +1,8 @@ /** @file - TCG EFI Platform Definition in TCG_EFI_Platform_1_20_Final + TCG EFI Platform Definition in TCG_EFI_Platform_1_20_Final and + TCG PC Client Platform Firmware Profile Specification, Revision 1.05 - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -21,6 +22,7 @@ #define EV_NO_ACTION ((TCG_EVENTTYPE) 0x00000003) #define EV_SEPARATOR ((TCG_EVENTTYPE) 0x00000004) #define EV_ACTION ((TCG_EVENTTYPE) 0x00000005) +#define EV_EVENT_TAG ((TCG_EVENTTYPE) 0x00000006) #define EV_S_CRTM_CONTENTS ((TCG_EVENTTYPE) 0x00000007) #define EV_S_CRTM_VERSION ((TCG_EVENTTYPE) 0x00000008) #define EV_CPU_MICROCODE ((TCG_EVENTTYPE) 0x00000009) @@ -45,8 +47,12 @@ #define EV_EFI_ACTION (EV_EFI_EVENT_BASE + 7) #define EV_EFI_PLATFORM_FIRMWARE_BLOB (EV_EFI_EVENT_BASE + 8) #define EV_EFI_HANDOFF_TABLES (EV_EFI_EVENT_BASE + 9) +#define EV_EFI_PLATFORM_FIRMWARE_BLOB2 (EV_EFI_EVENT_BASE + 0xA) +#define EV_EFI_HANDOFF_TABLES2 (EV_EFI_EVENT_BASE + 0xB) #define EV_EFI_HCRTM_EVENT (EV_EFI_EVENT_BASE + 0x10) #define EV_EFI_VARIABLE_AUTHORITY (EV_EFI_EVENT_BASE + 0xE0) +#define EV_EFI_SPDM_FIRMWARE_BLOB (EV_EFI_EVENT_BASE + 0xE1) +#define EV_EFI_SPDM_FIRMWARE_CONFIG (EV_EFI_EVENT_BASE + 0xE2) #define EFI_CALLING_EFI_APPLICATION \ "Calling EFI Application from Boot Option" @@ -78,6 +84,9 @@ #define EV_POSTCODE_INFO_OPROM "Embedded Option ROM" #define OPROM_LEN (sizeof(EV_POSTCODE_INFO_OPROM) - 1) +#define EV_POSTCODE_INFO_EMBEDDED_UEFI_DRIVER "Embedded UEFI Driver" +#define EMBEDDED_UEFI_DRIVER_LEN (sizeof(EV_POSTCODE_INFO_EMBEDDED_UEFI_DRIVER) - 1) + #define FIRMWARE_DEBUGGER_EVENT_STRING "UEFI Debug Mode" #define FIRMWARE_DEBUGGER_EVENT_STRING_LEN (sizeof(FIRMWARE_DEBUGGER_EVENT_STRING) - 1) @@ -123,6 +132,30 @@ typedef struct tdEFI_PLATFORM_FIRMWARE_BLOB { UINT64 BlobLength; } EFI_PLATFORM_FIRMWARE_BLOB; +/// +/// UEFI_PLATFORM_FIRMWARE_BLOB +/// +/// This structure is used in EV_EFI_PLATFORM_FIRMWARE_BLOB +/// event to facilitate the measurement of firmware volume. +/// +typedef struct tdUEFI_PLATFORM_FIRMWARE_BLOB { + EFI_PHYSICAL_ADDRESS BlobBase; + UINT64 BlobLength; +} UEFI_PLATFORM_FIRMWARE_BLOB; + +/// +/// UEFI_PLATFORM_FIRMWARE_BLOB2 +/// +/// This structure is used in EV_EFI_PLATFORM_FIRMWARE_BLOB2 +/// event to facilitate the measurement of firmware volume. +/// +typedef struct tdUEFI_PLATFORM_FIRMWARE_BLOB2 { + UINT8 BlobDescriptionSize; +//UINT8 BlobDescription[BlobDescriptionSize]; +//EFI_PHYSICAL_ADDRESS BlobBase; +//UINT64 BlobLength; +} UEFI_PLATFORM_FIRMWARE_BLOB2; + /// /// EFI_IMAGE_LOAD_EVENT /// @@ -137,6 +170,20 @@ typedef struct tdEFI_IMAGE_LOAD_EVENT { EFI_DEVICE_PATH_PROTOCOL DevicePath[1]; } EFI_IMAGE_LOAD_EVENT; +/// +/// UEFI_IMAGE_LOAD_EVENT +/// +/// This structure is used in EV_EFI_BOOT_SERVICES_APPLICATION, +/// EV_EFI_BOOT_SERVICES_DRIVER and EV_EFI_RUNTIME_SERVICES_DRIVER +/// +typedef struct tdUEFI_IMAGE_LOAD_EVENT { + EFI_PHYSICAL_ADDRESS ImageLocationInMemory; + UINT64 ImageLengthInMemory; + UINT64 ImageLinkTimeAddress; + UINT64 LengthOfDevicePath; + EFI_DEVICE_PATH_PROTOCOL DevicePath[1]; +} UEFI_IMAGE_LOAD_EVENT; + /// /// EFI_HANDOFF_TABLE_POINTERS /// @@ -148,6 +195,30 @@ typedef struct tdEFI_HANDOFF_TABLE_POINTERS { EFI_CONFIGURATION_TABLE TableEntry[1]; } EFI_HANDOFF_TABLE_POINTERS; +/// +/// UEFI_HANDOFF_TABLE_POINTERS +/// +/// This structure is used in EV_EFI_HANDOFF_TABLES event to facilitate +/// the measurement of given configuration tables. +/// +typedef struct tdUEFI_HANDOFF_TABLE_POINTERS { + UINT64 NumberOfTables; + EFI_CONFIGURATION_TABLE TableEntry[1]; +} UEFI_HANDOFF_TABLE_POINTERS; + +/// +/// UEFI_HANDOFF_TABLE_POINTERS2 +/// +/// This structure is used in EV_EFI_HANDOFF_TABLES2 event to facilitate +/// the measurement of given configuration tables. +/// +typedef struct tdUEFI_HANDOFF_TABLE_POINTERS2 { + UINT8 TableDescriptionSize; +//UINT8 TableDescription[TableDescriptionSize]; +//UINT64 NumberOfTables; +//EFI_CONFIGURATION_TABLE TableEntry[1]; +} UEFI_HANDOFF_TABLE_POINTERS2; + /// /// EFI_VARIABLE_DATA /// @@ -197,6 +268,66 @@ typedef struct tdEFI_GPT_DATA { EFI_PARTITION_ENTRY Partitions[1]; } EFI_GPT_DATA; +typedef struct tdUEFI_GPT_DATA { + EFI_PARTITION_TABLE_HEADER EfiPartitionHeader; + UINT64 NumberOfPartitions; + EFI_PARTITION_ENTRY Partitions[1]; +} UEFI_GPT_DATA; + +#define TCG_DEVICE_SECURITY_EVENT_DATA_SIGNATURE "SPDM Device Sec" +#define TCG_DEVICE_SECURITY_EVENT_DATA_VERSION 0 + +#define TCG_DEVICE_SECURITY_EVENT_DATA_DEVICE_TYPE_NULL 0 +#define TCG_DEVICE_SECURITY_EVENT_DATA_DEVICE_TYPE_PCI 1 +#define TCG_DEVICE_SECURITY_EVENT_DATA_DEVICE_TYPE_USB 2 + +/// +/// TCG_DEVICE_SECURITY_EVENT_DATA_HEADER +/// This is the header of TCG_DEVICE_SECURITY_EVENT_DATA, which is +/// used in EV_EFI_SPDM_FIRMWARE_BLOB and EV_EFI_SPDM_FIRMWARE_CONFIG. +/// +typedef struct { + UINT8 Signature[16]; + UINT16 Version; + UINT16 Length; + UINT32 SpdmHashAlgo; + UINT32 DeviceType; +//SPDM_MEASUREMENT_BLOCK SpdmMeasurementBlock; +} TCG_DEVICE_SECURITY_EVENT_DATA_HEADER; + +#define TCG_DEVICE_SECURITY_EVENT_DATA_PCI_CONTEXT_VERSION 0 + +/// +/// TCG_DEVICE_SECURITY_EVENT_DATA_PCI_CONTEXT +/// This is the PCI context data of TCG_DEVICE_SECURITY_EVENT_DATA, which is +/// used in EV_EFI_SPDM_FIRMWARE_BLOB and EV_EFI_SPDM_FIRMWARE_CONFIG. +/// +typedef struct { + UINT16 Version; + UINT16 Length; + UINT16 VendorId; + UINT16 DeviceId; + UINT8 RevisionID; + UINT8 ClassCode[3]; + UINT16 SubsystemVendorID; + UINT16 SubsystemID; +} TCG_DEVICE_SECURITY_EVENT_DATA_PCI_CONTEXT; + +#define TCG_DEVICE_SECURITY_EVENT_DATA_USB_CONTEXT_VERSION 0 + +/// +/// TCG_DEVICE_SECURITY_EVENT_DATA_USB_CONTEXT +/// This is the USB context data of TCG_DEVICE_SECURITY_EVENT_DATA, which is +/// used in EV_EFI_SPDM_FIRMWARE_BLOB and EV_EFI_SPDM_FIRMWARE_CONFIG. +/// +typedef struct { + UINT16 Version; + UINT16 Length; +//UINT8 DeviceDescriptor[DescLen]; +//UINT8 BodDescriptor[DescLen]; +//UINT8 ConfigurationDescriptor[DescLen][NumOfConfiguration]; +} TCG_DEVICE_SECURITY_EVENT_DATA_USB_CONTEXT; + // // Crypto Agile Log Entry Format // @@ -243,6 +374,7 @@ typedef struct { #define TCG_EfiSpecIDEventStruct_SPEC_VERSION_MAJOR_TPM2 2 #define TCG_EfiSpecIDEventStruct_SPEC_VERSION_MINOR_TPM2 0 #define TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2 0 +#define TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2_REV_105 105 typedef struct { UINT8 signature[16]; @@ -299,20 +431,52 @@ typedef struct { //UINT8 vendorInfo[vendorInfoSize]; } TCG_EfiSpecIDEventStruct; +typedef struct tdTCG_PCClientTaggedEvent { + UINT32 taggedEventID; + UINT32 taggedEventDataSize; +//UINT8 taggedEventData[taggedEventDataSize]; +} TCG_PCClientTaggedEvent; + +#define TCG_Sp800_155_PlatformId_Event_SIGNATURE "SP800-155 Event" +#define TCG_Sp800_155_PlatformId_Event2_SIGNATURE "SP800-155 Event2" +typedef struct tdTCG_Sp800_155_PlatformId_Event2 { + UINT8 Signature[16]; + // + // Where Vendor ID is an integer defined + // at http://www.iana.org/assignments/enterprisenumbers + // + UINT32 VendorId; + // + // 16-byte identifier of a given platform's static configuration of code + // + EFI_GUID ReferenceManifestGuid; + // + // Below structure is newly added in TCG_Sp800_155_PlatformId_Event2. + // +//UINT8 PlatformManufacturerStrSize; +//UINT8 PlatformManufacturerStr[PlatformManufacturerStrSize]; +//UINT8 PlatformModelSize; +//UINT8 PlatformModel[PlatformModelSize]; +//UINT8 PlatformVersionSize; +//UINT8 PlatformVersion[PlatformVersionSize]; +//UINT8 PlatformModelSize; +//UINT8 PlatformModel[PlatformModelSize]; +//UINT8 FirmwareManufacturerStrSize; +//UINT8 FirmwareManufacturerStr[FirmwareManufacturerStrSize]; +//UINT32 FirmwareManufacturerId; +//UINT8 FirmwareVersion; +//UINT8 FirmwareVersion[FirmwareVersionSize]]; +} TCG_Sp800_155_PlatformId_Event2; #define TCG_EfiStartupLocalityEvent_SIGNATURE "StartupLocality" // -// PC Client PTP spec Table 8 Relationship between Locality and Locality Attribute +// The Locality Indicator which sent the TPM2_Startup command // -#define LOCALITY_0_INDICATOR 0x01 -#define LOCALITY_1_INDICATOR 0x02 -#define LOCALITY_2_INDICATOR 0x03 -#define LOCALITY_3_INDICATOR 0x04 -#define LOCALITY_4_INDICATOR 0x05 - +#define LOCALITY_0_INDICATOR 0x00 +#define LOCALITY_3_INDICATOR 0x03 // // Startup Locality Event From 33daa3cde4f6a4855935679d029376fddde639bc Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 20 Dec 2019 09:04:06 -0800 Subject: [PATCH 211/384] Move the public files into the public. --- .../Include/Library/UnitTestAssertLib.h | 0 .../Include/Library/UnitTestLib.h | 0 .../Include/Library/UnitTestLogLib.h | 0 .../Include/Library/UnitTestTerminationLib.h | 0 .../SampleUnitTestApp/SampleUnitTestApp.inf | 1 - .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 1 - .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 1 - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 21 ------------------- 8 files changed, 24 deletions(-) rename {UnitTestFrameworkPkg => MdePkg}/Include/Library/UnitTestAssertLib.h (100%) rename {UnitTestFrameworkPkg => MdePkg}/Include/Library/UnitTestLib.h (100%) rename {UnitTestFrameworkPkg => MdePkg}/Include/Library/UnitTestLogLib.h (100%) rename {UnitTestFrameworkPkg => MdePkg}/Include/Library/UnitTestTerminationLib.h (100%) diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestAssertLib.h b/MdePkg/Include/Library/UnitTestAssertLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestAssertLib.h rename to MdePkg/Include/Library/UnitTestAssertLib.h diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestLib.h rename to MdePkg/Include/Library/UnitTestLib.h diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h b/MdePkg/Include/Library/UnitTestLogLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestLogLib.h rename to MdePkg/Include/Library/UnitTestLogLib.h diff --git a/UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h b/MdePkg/Include/Library/UnitTestTerminationLib.h similarity index 100% rename from UnitTestFrameworkPkg/Include/Library/UnitTestTerminationLib.h rename to MdePkg/Include/Library/UnitTestTerminationLib.h diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf index f75d2a9bb71..aa45b88ea41 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -22,7 +22,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf index 7ae0b6b8361..06e1729a1cc 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -22,7 +22,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf index 4754173dc6b..f61165ee22b 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -23,7 +23,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [Protocols] diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 47207f0df32..dc2254887da 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -16,32 +16,11 @@ PACKAGE_VERSION = 1.00 -[Includes] - Include - [Includes.Common.Private] FrameworkInclude FrameworkLibrary/CmockaLib/cmocka/include FrameworkLibrary/CmockaLib/cmocka/include/cmockery -[LibraryClasses] - ## @libraryclass Provide unit test assert helpers - # - UnitTestAssertLib|Include/Library/UnitTestAssertLib.h - - ## @libraryclass Provides a unit test framework - # - UnitTestLib|Include/Library/UnitTestLib.h - - ## @libraryclass Provide unit test logging - # - UnitTestLogLib|Include/Library/UnitTestLogLib.h - - ## @libraryclass Abstracts the methods that a test could exit prematurely. - # Allows tests written for different contexts to handle Quit()/Reboot() differently. - # - UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h - [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state # From c315c5273ab5bc0e8e97b5a9159b528eb844f7f4 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 20 Dec 2019 09:26:15 -0800 Subject: [PATCH 212/384] Expose the LogLib dependency. --- .../Sample/SampleUnitTestApp/SampleUnitTestApp.c | 7 +++---- .../Sample/SampleUnitTestPeim/SampleUnitTestPeim.c | 7 +++---- .../Sample/SampleUnitTestSmm/SampleUnitTestSmm.c | 7 +++---- 3 files changed, 9 insertions(+), 12 deletions(-) diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 3a0ff1dab77..647b88801f8 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -23,7 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include #include #include @@ -157,9 +156,9 @@ SampleUnitTestApp ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Framework = NULL; - UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 2512cbb4694..2d8c762531a 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -23,7 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include #include @@ -157,9 +156,9 @@ SampleUnitTestPeim ( IN CONST EFI_PEI_SERVICES **PeiServices ) { - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Framework = NULL; - UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index 1e1005c17a9..c1d79d141bc 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -23,7 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include #include @@ -155,9 +154,9 @@ SampleUnitTestSmm ( IN EFI_SYSTEM_TABLE *SystemTable ) { - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Framework = NULL; - UNIT_TEST_SUITE *SimpleMathTests, *GlobalVarTests; + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); From 09cf3346d3e2208160b702845138fb3ea1434227 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 20 Dec 2019 09:31:04 -0800 Subject: [PATCH 213/384] Fix the LogLib dependency. --- MdePkg/Include/Library/UnitTestLogLib.h | 10 ---- .../UnitTestAssertLib/UnitTestAssertLib.c | 53 +++++++++++++++++++ .../UnitTestAssertLib/UnitTestAssertLib.inf | 1 + .../Library/UnitTestLogLib/UnitTestLogLib.c | 52 ------------------ 4 files changed, 54 insertions(+), 62 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLogLib.h b/MdePkg/Include/Library/UnitTestLogLib.h index ce8b2af0935..c3690716a9e 100644 --- a/MdePkg/Include/Library/UnitTestLogLib.h +++ b/MdePkg/Include/Library/UnitTestLogLib.h @@ -53,14 +53,4 @@ UnitTestLogInit ( IN UINTN BufferSize ); -// TODO: Drop this from the lib interface. -VOID -EFIAPI -UnitTestLogFailure( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - FAILURE_TYPE FailureType, - IN CONST CHAR8 *Format, - ... -); - #endif \ No newline at end of file diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c index 1a98ae73408..065da737814 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c @@ -9,12 +9,65 @@ Copyright (c) Microsoft #include #include #include +#include #include #include #include +STATIC +EFI_STATUS +AddUnitTestFailure( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR8 *FailureMessage, + IN FAILURE_TYPE FailureType + ) +{ + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || FailureMessage == NULL) + { + return EFI_INVALID_PARAMETER; + } + + UnitTest->FailureType = FailureType; + AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + + return EFI_SUCCESS; +} // AddUnitTestFailure() + + +STATIC +VOID +UnitTestLogFailure( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + VA_LIST Marker; + + + // + // Convert the message to an ASCII String + // + VA_START(Marker, Format); + AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); + VA_END(Marker); + + // + // Finally, add the string to the log. + // + AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); + + return; +} // UnitTestLogFailure() + + BOOLEAN EFIAPI UnitTestAssertTrue ( diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf index 1a822c48b0e..6ba5d177f33 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf @@ -24,6 +24,7 @@ LIBRARY_CLASS = UnitTestAssertLib BaseLib BaseMemoryLib UnitTestLogLib + PrintLib [Packages] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c index 8516c9dac5c..f94b5000035 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -108,28 +108,6 @@ AddStringToUnitTestLog ( return EFI_SUCCESS; } -STATIC -EFI_STATUS -AddUnitTestFailure( - IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR8 *FailureMessage, - IN FAILURE_TYPE FailureType -) -{ - // - // Make sure that you're cooking with gas. - // - if (UnitTest == NULL || FailureMessage == NULL) - { - return EFI_INVALID_PARAMETER; - } - - UnitTest->FailureType = FailureType; - AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); - - return EFI_SUCCESS; -} - //============================================================================= // @@ -225,33 +203,3 @@ UnitTestLog ( return; } - -// TODO: Move this function and all referenced functions to the Assert Lib that uses it. -VOID -EFIAPI -UnitTestLogFailure( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN FAILURE_TYPE FailureType, - IN CONST CHAR8 *Format, - ... -) -{ - CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - VA_LIST Marker; - - - // - // Convert the message to an ASCII String - // - VA_START(Marker, Format); - AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); - VA_END(Marker); - - // - // Finally, add the string to the log. - // - AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); - - return; -} - From bf921298a761ab8aef6b4047def178ec0bc7ef7e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 20 Dec 2019 09:31:21 -0800 Subject: [PATCH 214/384] Clean up one last thing about how the Size works. --- UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 28bfea844f7..c30785a8c6a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -658,13 +658,10 @@ UpdateTestFromSave ( // If the saved context exists and matches this test, grab it, too. if (SavedState->HasSavedContext) { - // TODO: Reconcile the difference between the way "size" works for Test Saves - // and the way it works for Context Saves. Too confusing to use it different ways. - // If there was a saved context, the "matching test" loop will have placed the FloatingPointer // at the beginning of the context structure. SavedContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - if (SavedContext->Size > 0 && + if ((SavedContext->Size - sizeof(UNIT_TEST_SAVE_CONTEXT)) > 0 && CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) { // Override the test context with the saved context. @@ -808,7 +805,7 @@ SerializeState ( if (ContextToSave != NULL && Framework->CurrentTest != NULL) { TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - TestSaveContext->Size = (UINT32)ContextToSaveSize; + TestSaveContext->Size = (UINT32)ContextToSaveSize + sizeof(UNIT_TEST_SAVE_CONTEXT); CopyMem( &TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); CopyMem( ((UINT8*)TestSaveContext + sizeof( UNIT_TEST_SAVE_CONTEXT )), ContextToSave, ContextToSaveSize ); Header->HasSavedContext = TRUE; From 6e9c3b050c8e4568136753b6d0fef3caa535d41c Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 20 Dec 2019 09:42:09 -0800 Subject: [PATCH 215/384] Add documentation for building a single test. --- UnitTestFrameworkPkg/ReadMe.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 5a5dcad94f1..b83a59212d9 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -222,6 +222,16 @@ _Note_ that this early return can have implications for memory leakage. At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. +## Development + +When using the EDK2 Pytools for CI testing, the host-based unit tests will be built and run on any build that includes the `NOOPT` build target. + +If you are trying to iterate on a single test, a convenient pattern is to build only that test module. For example, the following command will build only the SafeIntLib host-based test from the MdePkg... + +```bash +stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +``` + ## Copyright Copyright (c) Microsoft Corporation. From caa917491a4bfb295d2afad86e4c34fd48e1f7b5 Mon Sep 17 00:00:00 2001 From: "Park, Aiden" Date: Sat, 21 Dec 2019 02:24:37 +0800 Subject: [PATCH 216/384] edksetup.bat stuck on unicode locale Windows This issue happens under two conditions. 1. Unicode language environment in Windows 2. Python2 (Not reproducible with Python3) Step to reproduce C:\edk2>edksetup.bat forcerebuild The edksetup.bat stuck at 'nmake cleanall'. Signed-off-by: Aiden Park Reviewed-by: Bob Feng --- BaseTools/Source/C/Makefiles/NmakeSubdirs.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Source/C/Makefiles/NmakeSubdirs.py b/BaseTools/Source/C/Makefiles/NmakeSubdirs.py index 356f5aca638..9b699ea086e 100644 --- a/BaseTools/Source/C/Makefiles/NmakeSubdirs.py +++ b/BaseTools/Source/C/Makefiles/NmakeSubdirs.py @@ -38,7 +38,7 @@ def RunCommand(WorkDir=None, *Args, **kwargs): stdout, stderr = p.communicate() message = "" if stdout is not None: - message = stdout.decode(encoding='utf-8', errors='ignore') #for compatibility in python 2 and 3 + message = stdout.decode(errors='ignore') #for compatibility in python 2 and 3 if p.returncode != 0: raise RuntimeError("Error while execute command \'{0}\' in direcotry {1}\n{2}".format(" ".join(Args), WorkDir, message)) From a457823f27e5410d00c1f47b5f841b5a88a926e4 Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Mon, 23 Dec 2019 14:15:04 +0800 Subject: [PATCH 217/384] UefiCpuPkg/PiSmmCpuDxeSmm: Remove dependence between APs REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2268 In current implementation, when check whether APs called by StartUpAllAPs or StartUpThisAp, it checks the Tokens value used by other APs. Also the AP will update the Token value for itself if its task finished. In this case, the potential race condition issues happens for the tokens. Because of this, system may trig ASSERT during cycling test. This change enhance the code logic, add new attributes for the token to remove the reference for the tokens belongs to other APs. Reviewed-by: Ray Ni Cc: Laszlo Ersek Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 125 +++++++-------------- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 5 +- 2 files changed, 45 insertions(+), 85 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 757f1056f78..35951cc43e1 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -402,38 +402,6 @@ IsPresentAp ( *(mSmmMpSyncData->CpuData[CpuIndex].Present)); } -/** - Check whether execute in single AP or all APs. - - Compare two Tokens used by different APs to know whether in StartAllAps call. - - Whether is an valid AP base on AP's Present flag. - - @retval TRUE IN StartAllAps call. - @retval FALSE Not in StartAllAps call. - -**/ -BOOLEAN -InStartAllApsCall ( - VOID - ) -{ - UINTN ApIndex; - UINTN ApIndex2; - - for (ApIndex = mMaxNumberOfCpus; ApIndex-- > 0;) { - if (IsPresentAp (ApIndex) && (mSmmMpSyncData->CpuData[ApIndex].Token != NULL)) { - for (ApIndex2 = ApIndex; ApIndex2-- > 0;) { - if (IsPresentAp (ApIndex2) && (mSmmMpSyncData->CpuData[ApIndex2].Token != NULL)) { - return mSmmMpSyncData->CpuData[ApIndex2].Token == mSmmMpSyncData->CpuData[ApIndex].Token; - } - } - } - } - - return FALSE; -} - /** Clean up the status flags used during executing the procedure. @@ -445,40 +413,15 @@ ReleaseToken ( IN UINTN CpuIndex ) { - UINTN Index; - BOOLEAN Released; + PROCEDURE_TOKEN *Token; - if (InStartAllApsCall ()) { - // - // In Start All APs mode, make sure all APs have finished task. - // - if (WaitForAllAPsNotBusy (FALSE)) { - // - // Clean the flags update in the function call. - // - Released = FALSE; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { - // - // Only In SMM APs need to be clean up. - // - if (mSmmMpSyncData->CpuData[Index].Present && mSmmMpSyncData->CpuData[Index].Token != NULL) { - if (!Released) { - ReleaseSpinLock (mSmmMpSyncData->CpuData[Index].Token); - Released = TRUE; - } - mSmmMpSyncData->CpuData[Index].Token = NULL; - } - } - } - } else { - // - // In single AP mode. - // - if (mSmmMpSyncData->CpuData[CpuIndex].Token != NULL) { - ReleaseSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Token); - mSmmMpSyncData->CpuData[CpuIndex].Token = NULL; - } + Token = mSmmMpSyncData->CpuData[CpuIndex].Token; + + if (InterlockedDecrement (&Token->RunningApCount) == 0) { + ReleaseSpinLock (Token->SpinLock); } + + mSmmMpSyncData->CpuData[CpuIndex].Token = NULL; } /** @@ -912,12 +855,14 @@ APHandler ( *mSmmMpSyncData->CpuData[CpuIndex].Status = ProcedureStatus; } + if (mSmmMpSyncData->CpuData[CpuIndex].Token != NULL) { + ReleaseToken (CpuIndex); + } + // // Release BUSY // ReleaseSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy); - - ReleaseToken (CpuIndex); } if (SmmCpuFeaturesNeedConfigureMtrrs()) { @@ -1111,7 +1056,7 @@ IsTokenInUse ( while (!IsNull (&gSmmCpuPrivate->TokenList, Link)) { ProcToken = PROCEDURE_TOKEN_FROM_LINK (Link); - if (ProcToken->ProcedureToken == Token) { + if (ProcToken->SpinLock == Token) { return TRUE; } @@ -1124,16 +1069,18 @@ IsTokenInUse ( /** create token and save it to the maintain list. + @param RunningApCount Input running AP count. + @retval return the spin lock used as token. **/ -SPIN_LOCK * +PROCEDURE_TOKEN * CreateToken ( - VOID + IN UINT32 RunningApCount ) { PROCEDURE_TOKEN *ProcToken; - SPIN_LOCK *CpuToken; + SPIN_LOCK *SpinLock; UINTN SpinLockSize; TOKEN_BUFFER *TokenBuf; UINT32 TokenCountPerChunk; @@ -1160,20 +1107,21 @@ CreateToken ( gSmmCpuPrivate->UsedTokenNum = 0; } - CpuToken = (SPIN_LOCK *)(gSmmCpuPrivate->CurrentTokenBuf + SpinLockSize * gSmmCpuPrivate->UsedTokenNum); + SpinLock = (SPIN_LOCK *)(gSmmCpuPrivate->CurrentTokenBuf + SpinLockSize * gSmmCpuPrivate->UsedTokenNum); gSmmCpuPrivate->UsedTokenNum++; - InitializeSpinLock (CpuToken); - AcquireSpinLock (CpuToken); + InitializeSpinLock (SpinLock); + AcquireSpinLock (SpinLock); ProcToken = AllocatePool (sizeof (PROCEDURE_TOKEN)); ASSERT (ProcToken != NULL); ProcToken->Signature = PROCEDURE_TOKEN_SIGNATURE; - ProcToken->ProcedureToken = CpuToken; + ProcToken->SpinLock = SpinLock; + ProcToken->RunningApCount = RunningApCount; InsertTailList (&gSmmCpuPrivate->TokenList, &ProcToken->Link); - return CpuToken; + return ProcToken; } /** @@ -1246,6 +1194,8 @@ InternalSmmStartupThisAp ( IN OUT EFI_STATUS *CpuStatus ) { + PROCEDURE_TOKEN *ProcToken; + if (CpuIndex >= gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus) { DEBUG((DEBUG_ERROR, "CpuIndex(%d) >= gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus(%d)\n", CpuIndex, gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus)); return EFI_INVALID_PARAMETER; @@ -1278,14 +1228,12 @@ InternalSmmStartupThisAp ( AcquireSpinLock (mSmmMpSyncData->CpuData[CpuIndex].Busy); - if (Token != NULL) { - *Token = (MM_COMPLETION) CreateToken (); - } - mSmmMpSyncData->CpuData[CpuIndex].Procedure = Procedure; mSmmMpSyncData->CpuData[CpuIndex].Parameter = ProcArguments; if (Token != NULL) { - mSmmMpSyncData->CpuData[CpuIndex].Token = (SPIN_LOCK *)(*Token); + ProcToken= CreateToken (1); + mSmmMpSyncData->CpuData[CpuIndex].Token = ProcToken; + *Token = (MM_COMPLETION)ProcToken->SpinLock; } mSmmMpSyncData->CpuData[CpuIndex].Status = CpuStatus; if (mSmmMpSyncData->CpuData[CpuIndex].Status != NULL) { @@ -1343,6 +1291,7 @@ InternalSmmStartupAllAPs ( { UINTN Index; UINTN CpuCount; + PROCEDURE_TOKEN *ProcToken; if ((TimeoutInMicroseconds != 0) && ((mSmmMp.Attributes & EFI_MM_MP_TIMEOUT_SUPPORTED) == 0)) { return EFI_INVALID_PARAMETER; @@ -1371,7 +1320,10 @@ InternalSmmStartupAllAPs ( } if (Token != NULL) { - *Token = (MM_COMPLETION) CreateToken (); + ProcToken = CreateToken ((UINT32)mMaxNumberOfCpus); + *Token = (MM_COMPLETION)ProcToken->SpinLock; + } else { + ProcToken = NULL; } // @@ -1391,8 +1343,8 @@ InternalSmmStartupAllAPs ( if (IsPresentAp (Index)) { mSmmMpSyncData->CpuData[Index].Procedure = (EFI_AP_PROCEDURE2) Procedure; mSmmMpSyncData->CpuData[Index].Parameter = ProcedureArguments; - if (Token != NULL) { - mSmmMpSyncData->CpuData[Index].Token = (SPIN_LOCK *)(*Token); + if (ProcToken != NULL) { + mSmmMpSyncData->CpuData[Index].Token = ProcToken; } if (CPUStatus != NULL) { mSmmMpSyncData->CpuData[Index].Status = &CPUStatus[Index]; @@ -1408,6 +1360,13 @@ InternalSmmStartupAllAPs ( if (CPUStatus != NULL) { CPUStatus[Index] = EFI_NOT_STARTED; } + + // + // Decrease the count to mark this processor(AP or BSP) as finished. + // + if (ProcToken != NULL) { + WaitForSemaphore (&ProcToken->RunningApCount); + } } } diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 5c1a01e42bf..5c98494e2c5 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -212,7 +212,8 @@ typedef struct { UINTN Signature; LIST_ENTRY Link; - SPIN_LOCK *ProcedureToken; + SPIN_LOCK *SpinLock; + volatile UINT32 RunningApCount; } PROCEDURE_TOKEN; #define PROCEDURE_TOKEN_FROM_LINK(a) CR (a, PROCEDURE_TOKEN, Link, PROCEDURE_TOKEN_SIGNATURE) @@ -407,7 +408,7 @@ typedef struct { volatile VOID *Parameter; volatile UINT32 *Run; volatile BOOLEAN *Present; - SPIN_LOCK *Token; + PROCEDURE_TOKEN *Token; EFI_STATUS *Status; } SMM_CPU_DATA_BLOCK; From 123b720eeb371e0a31eb727bcf59255b584e355f Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Mon, 23 Dec 2019 14:37:28 +0800 Subject: [PATCH 218/384] UefiCpuPkg/PiSmmCpuDxeSmm: Fix buffer overflow issue. The size for the array of mSmmMpSyncData->CpuData[] is 0 ~ mMaxNumberOfCpus -1. But current code may use mSmmMpSyncData->CpuData[mMaxNumberOfCpus]. This patch fixed this issue. Reviewed-by: Ray Ni Cc: Laszlo Ersek Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 35951cc43e1..4808045f71a 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -137,7 +137,7 @@ ReleaseAllAPs ( { UINTN Index; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { ReleaseSemaphore (mSmmMpSyncData->CpuData[Index].Run); } @@ -170,7 +170,7 @@ AllCpusInSmmWithExceptions ( CpuData = mSmmMpSyncData->CpuData; ProcessorInfo = gSmmCpuPrivate->ProcessorInfo; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (!(*(CpuData[Index].Present)) && ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { if (((Exceptions & ARRIVAL_EXCEPTION_DELAYED) != 0) && SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed) != 0) { continue; @@ -305,7 +305,7 @@ SmmWaitForApArrival ( // // Send SMI IPIs to bring outside processors in // - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (!(*(mSmmMpSyncData->CpuData[Index].Present)) && gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId); } @@ -361,7 +361,7 @@ WaitForAllAPsNotBusy ( { UINTN Index; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { // // Ignore BSP and APs which not call in SMM. // @@ -617,7 +617,7 @@ BSPHandler ( // while (TRUE) { PresentCount = 0; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (*(mSmmMpSyncData->CpuData[Index].Present)) { PresentCount ++; } @@ -1301,7 +1301,7 @@ InternalSmmStartupAllAPs ( } CpuCount = 0; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { CpuCount ++; @@ -1333,13 +1333,13 @@ InternalSmmStartupAllAPs ( // Here code always use AcquireSpinLock instead of AcquireSpinLockOrFail for not // block mode. // - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { AcquireSpinLock (mSmmMpSyncData->CpuData[Index].Busy); } } - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { mSmmMpSyncData->CpuData[Index].Procedure = (EFI_AP_PROCEDURE2) Procedure; mSmmMpSyncData->CpuData[Index].Parameter = ProcedureArguments; From a5abd9cc2cebe7fac001f7bb7b647c47cf54af1a Mon Sep 17 00:00:00 2001 From: "Desimone, Nathaniel L" Date: Sat, 7 Dec 2019 02:15:22 +0800 Subject: [PATCH 219/384] BaseTools/Scripts: Add sendemail.transferEncoding to SetupGit.py If git finds a '\r' character in the message, then it converts the entire message content into Quoted-Printable encoding. It appears that when groups.io converts the QP encoding back to text format, the '\r' characters somehow become '\n'. To workaround this, the SetupGit.py script will now explicitly set the sendemail.transferEncoding git config option to '8bit' Signed-off-by: Nate DeSimone Cc: Bob Feng Cc: Liming Gao Cc: Leif Lindholm Reviewed-by: Bob Feng --- BaseTools/Scripts/SetupGit.py | 38 ++++++++++++++++++----------------- 1 file changed, 20 insertions(+), 18 deletions(-) diff --git a/BaseTools/Scripts/SetupGit.py b/BaseTools/Scripts/SetupGit.py index 3d39d3b35fd..514f1c4d42d 100644 --- a/BaseTools/Scripts/SetupGit.py +++ b/BaseTools/Scripts/SetupGit.py @@ -2,6 +2,7 @@ # Set up the git configuration for contributing to TianoCore projects # # Copyright (c) 2019, Linaro Ltd. All rights reserved.
+# Copyright (c) 2019, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -53,29 +54,30 @@ # Set of options to be set identically for all repositories OPTIONS = [ - {'section': 'am', 'option': 'keepcr', 'value': True}, - {'section': 'am', 'option': 'signoff', 'value': True}, - {'section': 'cherry-pick', 'option': 'signoff', 'value': True}, - {'section': 'color', 'option': 'diff', 'value': True}, - {'section': 'color', 'option': 'grep', 'value': 'auto'}, - {'section': 'commit', 'option': 'signoff', 'value': True}, - {'section': 'core', 'option': 'abbrev', 'value': 12}, + {'section': 'am', 'option': 'keepcr', 'value': True}, + {'section': 'am', 'option': 'signoff', 'value': True}, + {'section': 'cherry-pick', 'option': 'signoff', 'value': True}, + {'section': 'color', 'option': 'diff', 'value': True}, + {'section': 'color', 'option': 'grep', 'value': 'auto'}, + {'section': 'commit', 'option': 'signoff', 'value': True}, + {'section': 'core', 'option': 'abbrev', 'value': 12}, {'section': 'core', 'option': 'attributesFile', 'value': os.path.join(CONFDIR, 'gitattributes').replace('\\', '/')}, - {'section': 'core', 'option': 'whitespace', 'value': 'cr-at-eol'}, - {'section': 'diff', 'option': 'algorithm', 'value': 'patience'}, + {'section': 'core', 'option': 'whitespace', 'value': 'cr-at-eol'}, + {'section': 'diff', 'option': 'algorithm', 'value': 'patience'}, {'section': 'diff', 'option': 'orderFile', 'value': os.path.join(CONFDIR, 'diff.order').replace('\\', '/')}, - {'section': 'diff', 'option': 'renames', 'value': 'copies'}, - {'section': 'diff', 'option': 'statGraphWidth', 'value': '20'}, - {'section': 'diff "ini"', 'option': 'xfuncname', + {'section': 'diff', 'option': 'renames', 'value': 'copies'}, + {'section': 'diff', 'option': 'statGraphWidth', 'value': '20'}, + {'section': 'diff "ini"', 'option': 'xfuncname', 'value': '^\\\\[[A-Za-z0-9_., ]+]'}, - {'section': 'format', 'option': 'coverLetter', 'value': True}, - {'section': 'format', 'option': 'numbered', 'value': True}, - {'section': 'format', 'option': 'signoff', 'value': False}, - {'section': 'notes', 'option': 'rewriteRef', 'value': 'refs/notes/commits'}, - {'section': 'sendemail', 'option': 'chainreplyto', 'value': False}, - {'section': 'sendemail', 'option': 'thread', 'value': True}, + {'section': 'format', 'option': 'coverLetter', 'value': True}, + {'section': 'format', 'option': 'numbered', 'value': True}, + {'section': 'format', 'option': 'signoff', 'value': False}, + {'section': 'notes', 'option': 'rewriteRef', 'value': 'refs/notes/commits'}, + {'section': 'sendemail', 'option': 'chainreplyto', 'value': False}, + {'section': 'sendemail', 'option': 'thread', 'value': True}, + {'section': 'sendemail', 'option': 'transferEncoding', 'value': '8bit'}, ] From 0d6df2c50ca53a8ae5f8777b9875f10e1d10478a Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 30 Dec 2019 16:03:13 -0800 Subject: [PATCH 220/384] Move the Cmocka implementations of UnitTestLib and UnitTestAssertLib to the public folder. --- MdePkg/Test/MdePkgTest.dsc | 4 ++-- .../UnitTestAssertLibcmocka/UnitTestAssertLib.c | 0 .../UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf | 0 .../UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm | 0 .../UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm | 0 .../UnitTestLibcmocka/UnitTestLib.c | 0 .../UnitTestLibcmocka/UnitTestLibcmocka.inf | 0 .../UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm | 0 .../UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm | 0 UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml | 4 ++-- 10 files changed, 4 insertions(+), 4 deletions(-) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestAssertLibcmocka/UnitTestAssertLib.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/UnitTestLib.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/UnitTestLibcmocka.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm (100%) diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 6a33a9b09a7..7ccc42f6aa2 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -30,8 +30,8 @@ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - UnitTestAssertLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf - UnitTestLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf [Components] diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLib.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf rename to UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLib.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLib.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm rename to UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 1e11bcd9822..ae57f1163f0 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,8 +30,8 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/FrameworkLibrary/UnitTestLibcmocka/UnitTestLibcmocka.inf", - "UnitTestFrameworkPkg/FrameworkLibrary/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", + "UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf", + "UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", "UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf", "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf" ] From 3e3b28bca5209753baece410a62fb729e1fb46a2 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 30 Dec 2019 16:03:25 -0800 Subject: [PATCH 221/384] Clean up a couple CI errors. --- MdePkg/MdePkg.ci.yaml | 2 +- MdePkg/MdePkg.dec | 17 +++++++++++++++++ 2 files changed, 18 insertions(+), 1 deletion(-) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index fc8e5678db0..e827946fc0b 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -27,7 +27,7 @@ ], # For host based unit tests "AcceptableDependencies-HOST_APPLICATION":[ - "UnitTestPkg/UnitTestPkg.dec" + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" ], # For UEFI shell based apps "AcceptableDependencies-UEFI_APPLICATION":[], diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index d022cc5e3ef..38a7e30750d 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -244,6 +244,23 @@ ## @libraryclass Module entry point library for standalone MM drivers. StandaloneMmDriverEntryPoint|Include/Library/StandaloneMmDriverEntryPoint.h + ## @libraryclass Provide unit test assert helpers + # + UnitTestAssertLib|Include/Library/UnitTestAssertLib.h + + ## @libraryclass Provides a unit test framework + # + UnitTestLib|Include/Library/UnitTestLib.h + + ## @libraryclass Provide unit test logging + # + UnitTestLogLib|Include/Library/UnitTestLogLib.h + + ## @libraryclass Abstracts the methods that a test could exit prematurely. + # Allows tests written for different contexts to handle Quit()/Reboot() differently. + # + UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h + [LibraryClasses.IA32, LibraryClasses.X64] ## @libraryclass Abstracts both S/W SMI generation and detection. ## From 999463c865d3768a8432a89508096ae6a43873a5 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Thu, 19 Dec 2019 13:36:24 +0800 Subject: [PATCH 222/384] UefiCpuPkg/MpInitLib: Collect processors' CPUID & Platform ID info REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2429 This commit will collect the CPUID and Platform ID information for each processor within system. They will be stored in the CPU_AP_DATA structure. These information will be used in the next commit to decide whether a microcode patch will be loaded into memory. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Ray Ni Reviewed-by: Eric Dong --- UefiCpuPkg/Library/MpInitLib/MpLib.c | 14 +++++++++++++- UefiCpuPkg/Library/MpInitLib/MpLib.h | 2 ++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index d32adf0780b..d5077e080e4 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -548,7 +548,8 @@ InitializeApData ( IN UINT64 ApTopOfStack ) { - CPU_INFO_IN_HOB *CpuInfoInHob; + CPU_INFO_IN_HOB *CpuInfoInHob; + MSR_IA32_PLATFORM_ID_REGISTER PlatformIdMsr; CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob; CpuInfoInHob[ProcessorNumber].InitialApicId = GetInitialApicId (); @@ -559,6 +560,17 @@ InitializeApData ( CpuMpData->CpuData[ProcessorNumber].Waiting = FALSE; CpuMpData->CpuData[ProcessorNumber].CpuHealthy = (BistData == 0) ? TRUE : FALSE; + PlatformIdMsr.Uint64 = AsmReadMsr64 (MSR_IA32_PLATFORM_ID); + CpuMpData->CpuData[ProcessorNumber].PlatformId = (UINT8) PlatformIdMsr.Bits.PlatformId; + + AsmCpuid ( + CPUID_VERSION_INFO, + &CpuMpData->CpuData[ProcessorNumber].ProcessorSignature, + NULL, + NULL, + NULL + ); + InitializeSpinLock(&CpuMpData->CpuData[ProcessorNumber].ApLock); SetApState (&CpuMpData->CpuData[ProcessorNumber], CpuStateIdle); } diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 8fa07b12c5e..4440dc2701f 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -122,6 +122,8 @@ typedef struct { UINT64 CurrentTime; UINT64 TotalTime; EFI_EVENT WaitEvent; + UINT32 ProcessorSignature; + UINT8 PlatformId; } CPU_AP_DATA; // From d786a1723203e91c92615c58d217e35b0d894004 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Thu, 19 Dec 2019 14:33:44 +0800 Subject: [PATCH 223/384] UefiCpuPkg/MpInitLib: Reduce the size when loading microcode patches REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2429 This commit will attempt to reduce the copy size when loading the microcode patches data from flash into memory. Such optimization is done by a pre-process of the microcode patch headers (on flash). A microcode patch will be loaded into memory only when the below 3 criteria are met: A. With a microcode patch header (which means the data is not padding data between microcode patches); B. The 'ProcessorSignature' & 'ProcessorFlags' fields in the header match at least one processor within system; C. If the Extended Signature Table exists in a microcode patch, the 'ProcessorSignature' & 'ProcessorFlag' fields in the table entries match at least one processor within system. Criterion B and C will require all the processors to be woken up once to collect their CPUID and Platform ID information. Hence, this commit will move the copy, detect and apply of microcode patch on BSP and APs after all the processors have been woken up. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Eric Dong Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/Microcode.c | 288 +++++++++++++++++++++++ UefiCpuPkg/Library/MpInitLib/MpLib.c | 90 +++---- UefiCpuPkg/Library/MpInitLib/MpLib.h | 24 ++ 3 files changed, 340 insertions(+), 62 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index 199b1f23ce3..330fd996233 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -331,3 +331,291 @@ MicrocodeDetect ( MicroData [0x%08x], Revision [0x%08x]\n", Eax.Uint32, ProcessorFlags, (UINTN) MicrocodeData, LatestRevision)); } } + +/** + Determine if a microcode patch will be loaded into memory. + + @param[in] CpuMpData The pointer to CPU MP Data structure. + @param[in] ProcessorSignature The processor signature field value + supported by a microcode patch. + @param[in] ProcessorFlags The prcessor flags field value supported by + a microcode patch. + + @retval TRUE The specified microcode patch will be loaded. + @retval FALSE The specified microcode patch will not be loaded. +**/ +BOOLEAN +IsMicrocodePatchNeedLoad ( + IN CPU_MP_DATA *CpuMpData, + IN UINT32 ProcessorSignature, + IN UINT32 ProcessorFlags + ) +{ + UINTN Index; + CPU_AP_DATA *CpuData; + + for (Index = 0; Index < CpuMpData->CpuCount; Index++) { + CpuData = &CpuMpData->CpuData[Index]; + if ((ProcessorSignature == CpuData->ProcessorSignature) && + (ProcessorFlags & (1 << CpuData->PlatformId)) != 0) { + return TRUE; + } + } + + return FALSE; +} + +/** + Actual worker function that loads the required microcode patches into memory. + + @param[in, out] CpuMpData The pointer to CPU MP Data structure. + @param[in] Patches The pointer to an array of information on + the microcode patches that will be loaded + into memory. + @param[in] PatchCount The number of microcode patches that will + be loaded into memory. + @param[in] TotalLoadSize The total size of all the microcode patches + to be loaded. +**/ +VOID +LoadMicrocodePatchWorker ( + IN OUT CPU_MP_DATA *CpuMpData, + IN MICROCODE_PATCH_INFO *Patches, + IN UINTN PatchCount, + IN UINTN TotalLoadSize + ) +{ + UINTN Index; + VOID *MicrocodePatchInRam; + UINT8 *Walker; + + ASSERT ((Patches != NULL) && (PatchCount != 0)); + + MicrocodePatchInRam = AllocatePages (EFI_SIZE_TO_PAGES (TotalLoadSize)); + if (MicrocodePatchInRam == NULL) { + return; + } + + // + // Load all the required microcode patches into memory + // + for (Walker = MicrocodePatchInRam, Index = 0; Index < PatchCount; Index++) { + CopyMem ( + Walker, + (VOID *) Patches[Index].Address, + Patches[Index].Size + ); + + // + // Zero-fill the padding area + // Please note that AlignedSize will be no less than Size + // + ZeroMem ( + Walker + Patches[Index].Size, + Patches[Index].AlignedSize - Patches[Index].Size + ); + + Walker += Patches[Index].AlignedSize; + } + + // + // Update the microcode patch related fields in CpuMpData + // + CpuMpData->MicrocodePatchAddress = (UINTN) MicrocodePatchInRam; + CpuMpData->MicrocodePatchRegionSize = TotalLoadSize; + + DEBUG (( + DEBUG_INFO, + "%a: Required microcode patches have been loaded at 0x%lx, with size 0x%lx.\n", + __FUNCTION__, CpuMpData->MicrocodePatchAddress, CpuMpData->MicrocodePatchRegionSize + )); + + return; +} + +/** + Load the required microcode patches data into memory. + + @param[in, out] CpuMpData The pointer to CPU MP Data structure. +**/ +VOID +LoadMicrocodePatch ( + IN OUT CPU_MP_DATA *CpuMpData + ) +{ + CPU_MICROCODE_HEADER *MicrocodeEntryPoint; + UINTN MicrocodeEnd; + UINTN DataSize; + UINTN TotalSize; + CPU_MICROCODE_EXTENDED_TABLE_HEADER *ExtendedTableHeader; + UINT32 ExtendedTableCount; + CPU_MICROCODE_EXTENDED_TABLE *ExtendedTable; + MICROCODE_PATCH_INFO *PatchInfoBuffer; + UINTN MaxPatchNumber; + UINTN PatchCount; + UINTN TotalLoadSize; + UINTN Index; + BOOLEAN NeedLoad; + + // + // Initialize the microcode patch related fields in CpuMpData as the values + // specified by the PCD pair. If the microcode patches are loaded into memory, + // these fields will be updated. + // + CpuMpData->MicrocodePatchAddress = PcdGet64 (PcdCpuMicrocodePatchAddress); + CpuMpData->MicrocodePatchRegionSize = PcdGet64 (PcdCpuMicrocodePatchRegionSize); + + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (UINTN) CpuMpData->MicrocodePatchAddress; + MicrocodeEnd = (UINTN) MicrocodeEntryPoint + + (UINTN) CpuMpData->MicrocodePatchRegionSize; + if ((MicrocodeEntryPoint == NULL) || ((UINTN) MicrocodeEntryPoint == MicrocodeEnd)) { + // + // There is no microcode patches + // + return; + } + + PatchCount = 0; + MaxPatchNumber = DEFAULT_MAX_MICROCODE_PATCH_NUM; + TotalLoadSize = 0; + PatchInfoBuffer = AllocatePool (MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO)); + if (PatchInfoBuffer == NULL) { + return; + } + + // + // Process the header of each microcode patch within the region. + // The purpose is to decide which microcode patch(es) will be loaded into memory. + // + do { + if (MicrocodeEntryPoint->HeaderVersion != 0x1) { + // + // Padding data between the microcode patches, skip 1KB to check next entry. + // + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); + continue; + } + + DataSize = MicrocodeEntryPoint->DataSize; + TotalSize = (DataSize == 0) ? 2048 : MicrocodeEntryPoint->TotalSize; + if ( (UINTN)MicrocodeEntryPoint > (MAX_ADDRESS - TotalSize) || + ((UINTN)MicrocodeEntryPoint + TotalSize) > MicrocodeEnd || + (DataSize & 0x3) != 0 || + (TotalSize & (SIZE_1KB - 1)) != 0 || + TotalSize < DataSize + ) { + // + // Not a valid microcode header, skip 1KB to check next entry. + // + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + SIZE_1KB); + continue; + } + + // + // Check the 'ProcessorSignature' and 'ProcessorFlags' of the microcode + // patch header with the CPUID and PlatformID of the processors within + // system to decide if it will be copied into memory + // + NeedLoad = IsMicrocodePatchNeedLoad ( + CpuMpData, + MicrocodeEntryPoint->ProcessorSignature.Uint32, + MicrocodeEntryPoint->ProcessorFlags + ); + + // + // If the Extended Signature Table exists, check if the processor is in the + // support list + // + if ((!NeedLoad) && (DataSize != 0) && + (TotalSize - DataSize > sizeof (CPU_MICROCODE_HEADER) + + sizeof (CPU_MICROCODE_EXTENDED_TABLE_HEADER))) { + ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *) ((UINT8 *) (MicrocodeEntryPoint) + + DataSize + sizeof (CPU_MICROCODE_HEADER)); + ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount; + ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *) (ExtendedTableHeader + 1); + + for (Index = 0; Index < ExtendedTableCount; Index ++) { + // + // Avoid access content beyond MicrocodeEnd + // + if ((UINTN) ExtendedTable > MicrocodeEnd - sizeof (CPU_MICROCODE_EXTENDED_TABLE)) { + break; + } + + // + // Check the 'ProcessorSignature' and 'ProcessorFlag' of the Extended + // Signature Table entry with the CPUID and PlatformID of the processors + // within system to decide if it will be copied into memory + // + NeedLoad = IsMicrocodePatchNeedLoad ( + CpuMpData, + ExtendedTable->ProcessorSignature.Uint32, + ExtendedTable->ProcessorFlag + ); + if (NeedLoad) { + break; + } + ExtendedTable ++; + } + } + + if (NeedLoad) { + PatchCount++; + if (PatchCount > MaxPatchNumber) { + // + // Current 'PatchInfoBuffer' cannot hold the information, double the size + // and allocate a new buffer. + // + if (MaxPatchNumber > MAX_UINTN / 2 / sizeof (MICROCODE_PATCH_INFO)) { + // + // Overflow check for MaxPatchNumber + // + goto OnExit; + } + + PatchInfoBuffer = ReallocatePool ( + MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO), + 2 * MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO), + PatchInfoBuffer + ); + if (PatchInfoBuffer == NULL) { + goto OnExit; + } + MaxPatchNumber = MaxPatchNumber * 2; + } + + // + // Store the information of this microcode patch + // + if (TotalSize > ALIGN_VALUE (TotalSize, SIZE_1KB) || + ALIGN_VALUE (TotalSize, SIZE_1KB) > MAX_UINTN - TotalLoadSize) { + goto OnExit; + } + PatchInfoBuffer[PatchCount - 1].Address = (UINTN) MicrocodeEntryPoint; + PatchInfoBuffer[PatchCount - 1].Size = TotalSize; + PatchInfoBuffer[PatchCount - 1].AlignedSize = ALIGN_VALUE (TotalSize, SIZE_1KB); + TotalLoadSize += PatchInfoBuffer[PatchCount - 1].AlignedSize; + } + + // + // Process the next microcode patch + // + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (((UINTN) MicrocodeEntryPoint) + TotalSize); + } while (((UINTN) MicrocodeEntryPoint < MicrocodeEnd)); + + if (PatchCount != 0) { + DEBUG (( + DEBUG_INFO, + "%a: 0x%x microcode patches will be loaded into memory, with size 0x%x.\n", + __FUNCTION__, PatchCount, TotalLoadSize + )); + + LoadMicrocodePatchWorker (CpuMpData, PatchInfoBuffer, PatchCount, TotalLoadSize); + } + +OnExit: + if (PatchInfoBuffer != NULL) { + FreePool (PatchInfoBuffer); + } + return; +} diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index d5077e080e4..c72bf3c9eec 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -628,10 +628,6 @@ ApWakeupFunction ( ApTopOfStack = CpuMpData->Buffer + (ProcessorNumber + 1) * CpuMpData->CpuApStackSize; BistData = *(UINT32 *) ((UINTN) ApTopOfStack - sizeof (UINTN)); // - // Do some AP initialize sync - // - ApInitializeSync (CpuMpData); - // // CpuMpData->CpuData[0].VolatileRegisters is initialized based on BSP environment, // to initialize AP in InitConfig path. // NOTE: IDTR.BASE stored in CpuMpData->CpuData[0].VolatileRegisters points to a different IDT shared by all APs. @@ -1615,7 +1611,6 @@ MpInitLibInitialize ( UINTN ApResetVectorSize; UINTN BackupBufferAddr; UINTN ApIdtBase; - VOID *MicrocodePatchInRam; OldCpuMpData = GetCpuMpDataFromGuidedHob (); if (OldCpuMpData == NULL) { @@ -1683,39 +1678,7 @@ MpInitLibInitialize ( CpuMpData->SwitchBspFlag = FALSE; CpuMpData->CpuData = (CPU_AP_DATA *) (CpuMpData + 1); CpuMpData->CpuInfoInHob = (UINT64) (UINTN) (CpuMpData->CpuData + MaxLogicalProcessorNumber); - if (OldCpuMpData == NULL) { - CpuMpData->MicrocodePatchRegionSize = PcdGet64 (PcdCpuMicrocodePatchRegionSize); - // - // If platform has more than one CPU, relocate microcode to memory to reduce - // loading microcode time. - // - MicrocodePatchInRam = NULL; - if (MaxLogicalProcessorNumber > 1) { - MicrocodePatchInRam = AllocatePages ( - EFI_SIZE_TO_PAGES ( - (UINTN)CpuMpData->MicrocodePatchRegionSize - ) - ); - } - if (MicrocodePatchInRam == NULL) { - // - // there is only one processor, or no microcode patch is available, or - // memory allocation failed - // - CpuMpData->MicrocodePatchAddress = PcdGet64 (PcdCpuMicrocodePatchAddress); - } else { - // - // there are multiple processors, and a microcode patch is available, and - // memory allocation succeeded - // - CopyMem ( - MicrocodePatchInRam, - (VOID *)(UINTN)PcdGet64 (PcdCpuMicrocodePatchAddress), - (UINTN)CpuMpData->MicrocodePatchRegionSize - ); - CpuMpData->MicrocodePatchAddress = (UINTN)MicrocodePatchInRam; - } - }else { + if (OldCpuMpData != NULL) { CpuMpData->MicrocodePatchRegionSize = OldCpuMpData->MicrocodePatchRegionSize; CpuMpData->MicrocodePatchAddress = OldCpuMpData->MicrocodePatchAddress; } @@ -1762,14 +1725,6 @@ MpInitLibInitialize ( (UINT32 *)(MonitorBuffer + MonitorFilterSize * Index); } // - // Load Microcode on BSP - // - MicrocodeDetect (CpuMpData, TRUE); - // - // Store BSP's MTRR setting - // - MtrrGetAllMtrrs (&CpuMpData->MtrrTable); - // // Enable the local APIC for Virtual Wire Mode. // ProgramVirtualWireMode (); @@ -1781,6 +1736,11 @@ MpInitLibInitialize ( // CollectProcessorCount (CpuMpData); } + + // + // Load required microcode patches data into memory + // + LoadMicrocodePatch (CpuMpData); } else { // // APs have been wakeup before, just get the CPU Information @@ -1788,7 +1748,6 @@ MpInitLibInitialize ( // CpuMpData->CpuCount = OldCpuMpData->CpuCount; CpuMpData->BspNumber = OldCpuMpData->BspNumber; - CpuMpData->InitFlag = ApInitReconfig; CpuMpData->CpuInfoInHob = OldCpuMpData->CpuInfoInHob; CpuInfoInHob = (CPU_INFO_IN_HOB *) (UINTN) CpuMpData->CpuInfoInHob; for (Index = 0; Index < CpuMpData->CpuCount; Index++) { @@ -1797,21 +1756,28 @@ MpInitLibInitialize ( CpuMpData->CpuData[Index].ApFunction = 0; CopyMem (&CpuMpData->CpuData[Index].VolatileRegisters, &VolatileRegisters, sizeof (CPU_VOLATILE_REGISTERS)); } - if (MaxLogicalProcessorNumber > 1) { - // - // Wakeup APs to do some AP initialize sync - // - WakeUpAP (CpuMpData, TRUE, 0, ApInitializeSync, CpuMpData, TRUE); - // - // Wait for all APs finished initialization - // - while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) { - CpuPause (); - } - CpuMpData->InitFlag = ApInitDone; - for (Index = 0; Index < CpuMpData->CpuCount; Index++) { - SetApState (&CpuMpData->CpuData[Index], CpuStateIdle); - } + } + + // + // Detect and apply Microcode on BSP + // + MicrocodeDetect (CpuMpData, TRUE); + // + // Store BSP's MTRR setting + // + MtrrGetAllMtrrs (&CpuMpData->MtrrTable); + + // + // Wakeup APs to do some AP initialize sync (Microcode & MTRR) + // + if (CpuMpData->CpuCount > 1) { + WakeUpAP (CpuMpData, TRUE, 0, ApInitializeSync, CpuMpData, TRUE); + while (CpuMpData->FinishedCount < (CpuMpData->CpuCount - 1)) { + CpuPause (); + } + + for (Index = 0; Index < CpuMpData->CpuCount; Index++) { + SetApState (&CpuMpData->CpuData[Index], CpuStateIdle); } } diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 4440dc2701f..56b0df664a7 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -43,6 +43,20 @@ #define CPU_SWITCH_STATE_STORED 1 #define CPU_SWITCH_STATE_LOADED 2 +// +// Default maximum number of entries to store the microcode patches information +// +#define DEFAULT_MAX_MICROCODE_PATCH_NUM 8 + +// +// Data structure for microcode patch information +// +typedef struct { + UINTN Address; + UINTN Size; + UINTN AlignedSize; +} MICROCODE_PATCH_INFO; + // // CPU exchange information for switch BSP // @@ -575,6 +589,16 @@ MicrocodeDetect ( IN BOOLEAN IsBspCallIn ); +/** + Load the required microcode patches data into memory. + + @param[in, out] CpuMpData The pointer to CPU MP Data structure. +**/ +VOID +LoadMicrocodePatch ( + IN OUT CPU_MP_DATA *CpuMpData + ); + /** Detect whether Mwait-monitor feature is supported. From 253909974a0e2e9c60fa78e57c0c46fef2877332 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Mon, 23 Dec 2019 10:52:14 +0800 Subject: [PATCH 224/384] UefiCpuPkg: Add definitions for EDKII microcode patch HOB REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2430 This commit will add the definitions for EDKII microcode patch HOB. The intention of adding this HOB is to provide a scheme to store the below information: A. The base address and size of the microcode patches that are being loaded (from flash) into memory; B. The information of detected microcode patch for each processor within the system. The producer of the HOB will be the UefiCpuPkg/MpInitLib (where the load, detect and apply of the microcode happen). The consumer of the HOB can be modules that want to detect/apply the microcode patch by themselves again later during the boot flow. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Ray Ni Reviewed-by: Eric Dong --- UefiCpuPkg/Include/Guid/MicrocodePatchHob.h | 44 +++++++++++++++++++++ UefiCpuPkg/UefiCpuPkg.dec | 3 ++ 2 files changed, 47 insertions(+) create mode 100644 UefiCpuPkg/Include/Guid/MicrocodePatchHob.h diff --git a/UefiCpuPkg/Include/Guid/MicrocodePatchHob.h b/UefiCpuPkg/Include/Guid/MicrocodePatchHob.h new file mode 100644 index 00000000000..2d307fbffbf --- /dev/null +++ b/UefiCpuPkg/Include/Guid/MicrocodePatchHob.h @@ -0,0 +1,44 @@ +/** @file + The microcode patch HOB is used to store the information of: + A. Base address and size of the loaded microcode patches data; + B. Detected microcode patch for each processor within system. + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _MICROCODE_PATCH_HOB_H_ +#define _MICROCODE_PATCH_HOB_H_ + +extern EFI_GUID gEdkiiMicrocodePatchHobGuid; + +// +// The EDKII microcode patch HOB will be produced by MpInitLib and it can be +// consumed by modules that want to detect/apply microcode patches. +// +typedef struct { + // + // The base address of the microcode patches data after being loaded into + // memory. + // + UINT64 MicrocodePatchAddress; + // + // The total size of the loaded microcode patches. + // + UINT64 MicrocodePatchRegionSize; + // + // The number of processors within the system. + // + UINT32 ProcessorCount; + // + // An array with 'ProcessorCount' elements that stores the offset (with + // regard to 'MicrocodePatchAddress') of the detected microcode patch + // (including the CPU_MICROCODE_HEADER data structure) for each processor. + // If no microcode patch is detected for certain processor, the relating + // element will be set to MAX_UINT64. + // + UINT64 ProcessorSpecificPatchOffset[0]; +} EDKII_MICROCODE_PATCH_HOB; + +#endif diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 797f9486315..45b267ac61d 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -63,6 +63,9 @@ ## Include/Guid/CpuFeaturesInitDone.h gEdkiiCpuFeaturesInitDoneGuid = { 0xc77c3a41, 0x61ab, 0x4143, { 0x98, 0x3e, 0x33, 0x39, 0x28, 0x6, 0x28, 0xe5 }} + ## Include/Guid/MicrocodePatchHob.h + gEdkiiMicrocodePatchHobGuid = { 0xd178f11d, 0x8716, 0x418e, { 0xa1, 0x31, 0x96, 0x7d, 0x2a, 0xc4, 0x28, 0x43 }} + [Protocols] ## Include/Protocol/SmmCpuService.h gEfiSmmCpuServiceProtocolGuid = { 0x1d202cab, 0xc8ab, 0x4d5c, { 0x94, 0xf7, 0x3c, 0xfc, 0xc0, 0xd3, 0xd3, 0x35 }} From e1ed55738ec30db364a00d0ddac50dbbf3671795 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Mon, 23 Dec 2019 14:32:49 +0800 Subject: [PATCH 225/384] UefiCpuPkg/MpInitLib: Produce EDKII microcode patch HOB REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2430 This commit will update the MpInitLib to: A. Collect the base address and size information after microcode patches being loaded into memory; B. Collect the detected microcode patch for each processor within system; C. Based on the collected information, produce the EDKII microcode patch HOB. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Eric Dong Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/Microcode.c | 20 ++++++- UefiCpuPkg/Library/MpInitLib/MpLib.c | 8 ++- UefiCpuPkg/Library/MpInitLib/MpLib.h | 24 +++++++- UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 1 + UefiCpuPkg/Library/MpInitLib/PeiMpLib.c | 55 +++++++++++++++++++ 5 files changed, 100 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index 330fd996233..4162b4a8dcf 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -65,13 +65,15 @@ GetCurrentMicrocodeSignature ( It does not guarantee that the data has not been modified. CPU has its own mechanism to verify Microcode Binary part. - @param[in] CpuMpData The pointer to CPU MP Data structure. - @param[in] IsBspCallIn Indicate whether the caller is BSP or not. + @param[in] CpuMpData The pointer to CPU MP Data structure. + @param[in] ProcessorNumber The handle number of the processor. The range is + from 0 to the total number of logical processors + minus 1. **/ VOID MicrocodeDetect ( IN CPU_MP_DATA *CpuMpData, - IN BOOLEAN IsBspCallIn + IN UINTN ProcessorNumber ) { UINT32 ExtendedTableLength; @@ -93,6 +95,7 @@ MicrocodeDetect ( MSR_IA32_PLATFORM_ID_REGISTER PlatformIdMsr; UINT32 ProcessorFlags; UINT32 ThreadId; + BOOLEAN IsBspCallIn; // // set ProcessorFlags to suppress incorrect compiler/analyzer warnings @@ -107,6 +110,7 @@ MicrocodeDetect ( } CurrentRevision = GetCurrentMicrocodeSignature (); + IsBspCallIn = (ProcessorNumber == (UINTN)CpuMpData->BspNumber) ? TRUE : FALSE; if (CurrentRevision != 0 && !IsBspCallIn) { // // Skip loading microcode if it has been loaded successfully @@ -295,6 +299,16 @@ MicrocodeDetect ( } while (((UINTN) MicrocodeEntryPoint < MicrocodeEnd)); Done: + if (LatestRevision != 0) { + // + // Save the detected microcode patch entry address (including the + // microcode patch header) for each processor. + // It will be used when building the microcode patch cache HOB. + // + CpuMpData->CpuData[ProcessorNumber].MicrocodeEntryAddr = + (UINTN) MicrocodeData - sizeof (CPU_MICROCODE_HEADER); + } + if (LatestRevision > CurrentRevision) { // // BIOS only authenticate updates that contain a numerically larger revision diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index c72bf3c9eec..e611a8ca406 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -399,12 +399,16 @@ ApInitializeSync ( ) { CPU_MP_DATA *CpuMpData; + UINTN ProcessorNumber; + EFI_STATUS Status; CpuMpData = (CPU_MP_DATA *) Buffer; + Status = GetProcessorNumber (CpuMpData, &ProcessorNumber); + ASSERT_EFI_ERROR (Status); // // Load microcode on AP // - MicrocodeDetect (CpuMpData, FALSE); + MicrocodeDetect (CpuMpData, ProcessorNumber); // // Sync BSP's MTRR table to AP // @@ -1761,7 +1765,7 @@ MpInitLibInitialize ( // // Detect and apply Microcode on BSP // - MicrocodeDetect (CpuMpData, TRUE); + MicrocodeDetect (CpuMpData, CpuMpData->BspNumber); // // Store BSP's MTRR setting // diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 56b0df664a7..885656900c5 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -138,6 +138,7 @@ typedef struct { EFI_EVENT WaitEvent; UINT32 ProcessorSignature; UINT8 PlatformId; + UINT64 MicrocodeEntryAddr; } CPU_AP_DATA; // @@ -580,13 +581,15 @@ CheckAndUpdateApsStatus ( /** Detect whether specified processor can find matching microcode patch and load it. - @param[in] CpuMpData The pointer to CPU MP Data structure. - @param[in] IsBspCallIn Indicate whether the caller is BSP or not. + @param[in] CpuMpData The pointer to CPU MP Data structure. + @param[in] ProcessorNumber The handle number of the processor. The range is + from 0 to the total number of logical processors + minus 1. **/ VOID MicrocodeDetect ( IN CPU_MP_DATA *CpuMpData, - IN BOOLEAN IsBspCallIn + IN UINTN ProcessorNumber ); /** @@ -619,5 +622,20 @@ EnableDebugAgent ( VOID ); +/** + Find the current Processor number by APIC ID. + + @param[in] CpuMpData Pointer to PEI CPU MP Data + @param[out] ProcessorNumber Return the pocessor number found + + @retval EFI_SUCCESS ProcessorNumber is found and returned. + @retval EFI_NOT_FOUND ProcessorNumber is not found. +**/ +EFI_STATUS +GetProcessorNumber ( + IN CPU_MP_DATA *CpuMpData, + OUT UINTN *ProcessorNumber + ); + #endif diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf index 1538185ef99..326703cc9ad 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf @@ -63,3 +63,4 @@ [Guids] gEdkiiS3SmmInitDoneGuid + gEdkiiMicrocodePatchHobGuid diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c index 3999603c3ef..06e3f5d0d3d 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpLib.c @@ -9,6 +9,7 @@ #include "MpLib.h" #include #include +#include /** S3 SMM Init Done notification function. @@ -290,6 +291,59 @@ CheckAndUpdateApsStatus ( { } +/** + Build the microcode patch HOB that contains the base address and size of the + microcode patch stored in the memory. + + @param[in] CpuMpData Pointer to the CPU_MP_DATA structure. + +**/ +VOID +BuildMicrocodeCacheHob ( + IN CPU_MP_DATA *CpuMpData + ) +{ + EDKII_MICROCODE_PATCH_HOB *MicrocodeHob; + UINTN HobDataLength; + UINT32 Index; + + HobDataLength = sizeof (EDKII_MICROCODE_PATCH_HOB) + + sizeof (UINT64) * CpuMpData->CpuCount; + + MicrocodeHob = AllocatePool (HobDataLength); + if (MicrocodeHob == NULL) { + ASSERT (FALSE); + return; + } + + // + // Store the information of the memory region that holds the microcode patches. + // + MicrocodeHob->MicrocodePatchAddress = CpuMpData->MicrocodePatchAddress; + MicrocodeHob->MicrocodePatchRegionSize = CpuMpData->MicrocodePatchRegionSize; + + // + // Store the detected microcode patch for each processor as well. + // + MicrocodeHob->ProcessorCount = CpuMpData->CpuCount; + for (Index = 0; Index < CpuMpData->CpuCount; Index++) { + if (CpuMpData->CpuData[Index].MicrocodeEntryAddr != 0) { + MicrocodeHob->ProcessorSpecificPatchOffset[Index] = + CpuMpData->CpuData[Index].MicrocodeEntryAddr - CpuMpData->MicrocodePatchAddress; + } else { + MicrocodeHob->ProcessorSpecificPatchOffset[Index] = MAX_UINT64; + } + } + + BuildGuidDataHob ( + &gEdkiiMicrocodePatchHobGuid, + MicrocodeHob, + HobDataLength + ); + + return; +} + /** Initialize global data for MP support. @@ -302,6 +356,7 @@ InitMpGlobalData ( { EFI_STATUS Status; + BuildMicrocodeCacheHob (CpuMpData); SaveCpuMpData (CpuMpData); /// From 88bd06616617ef2569f093f7b51893c11ad78e26 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Wed, 25 Dec 2019 10:50:19 +0800 Subject: [PATCH 226/384] UefiCpuPkg/MpInitLib: Relocate microcode patch fields in CPU_MP_DATA The below 2 microcode patch related fields in structure CPU_MP_DATA: UINT64 MicrocodePatchAddress; UINT64 MicrocodePatchRegionSize; They will be passed from PEI phase and be reused DXE phase. Previously, these 2 fields were placed after some fields with type 'UINTN', this will lead to different field offset in different architecture for them. This commit will move them before the fields with different size in different architecture to ensure they can be properly used in DXE phase. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Ray Ni Reviewed-by: Eric Dong --- UefiCpuPkg/Library/MpInitLib/MpLib.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 885656900c5..5f50e79744c 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -217,6 +217,8 @@ struct _CPU_MP_DATA { UINT64 CpuInfoInHob; UINT32 CpuCount; UINT32 BspNumber; + UINT64 MicrocodePatchAddress; + UINT64 MicrocodePatchRegionSize; // // The above fields data will be passed from PEI to DXE // Please make sure the fields offset same in the different @@ -260,8 +262,6 @@ struct _CPU_MP_DATA { UINT8 Vector; BOOLEAN PeriodicMode; BOOLEAN TimerInterruptState; - UINT64 MicrocodePatchAddress; - UINT64 MicrocodePatchRegionSize; UINT32 ProcessorSignature; UINT32 ProcessorFlags; From fd30b0070773ac4ac5f49abca8f5b3afbeece158 Mon Sep 17 00:00:00 2001 From: Hao A Wu Date: Tue, 24 Dec 2019 15:02:23 +0800 Subject: [PATCH 227/384] UefiCpuPkg/MpInitLib: Remove redundant microcode fields in CPU_MP_DATA Previous commits have introduced below fields in structure CPU_AP_DATA: UINT32 ProcessorSignature; UINT8 PlatformId; UINT64 MicrocodeEntryAddr; which store the information of: A. CPUID B. Platform ID C. Detected microcode patch entry address (including the microcode patch header) for each processor within system. Therefore, the below fields in structure CPU_MP_DATA: UINT32 ProcessorSignature; UINT32 ProcessorFlags; UINT64 MicrocodeDataAddress; UINT32 MicrocodeRevision; which store the BSP's information of: A. CPUID B. Platform ID C. The address and revision of detected microcode patch are redundant and can be removed. Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Cc: Star Zeng Cc: Siyuan Fu Cc: Michael D Kinney Signed-off-by: Hao A Wu Reviewed-by: Eric Dong Reviewed-by: Ray Ni --- UefiCpuPkg/Library/MpInitLib/Microcode.c | 51 +++++++----------------- UefiCpuPkg/Library/MpInitLib/MpLib.h | 5 --- 2 files changed, 14 insertions(+), 42 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index 4162b4a8dcf..3da5bfb9cf2 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -85,6 +85,7 @@ MicrocodeDetect ( UINTN Index; UINT8 PlatformId; CPUID_VERSION_INFO_EAX Eax; + CPU_AP_DATA *CpuData; UINT32 CurrentRevision; UINT32 LatestRevision; UINTN TotalSize; @@ -92,16 +93,9 @@ MicrocodeDetect ( UINT32 InCompleteCheckSum32; BOOLEAN CorrectMicrocode; VOID *MicrocodeData; - MSR_IA32_PLATFORM_ID_REGISTER PlatformIdMsr; - UINT32 ProcessorFlags; UINT32 ThreadId; BOOLEAN IsBspCallIn; - // - // set ProcessorFlags to suppress incorrect compiler/analyzer warnings - // - ProcessorFlags = 0; - if (CpuMpData->MicrocodePatchRegionSize == 0) { // // There is no microcode patches @@ -127,28 +121,25 @@ MicrocodeDetect ( } ExtendedTableLength = 0; - // - // Here data of CPUID leafs have not been collected into context buffer, so - // GetProcessorCpuid() cannot be used here to retrieve CPUID data. - // - AsmCpuid (CPUID_VERSION_INFO, &Eax.Uint32, NULL, NULL, NULL); - - // - // The index of platform information resides in bits 50:52 of MSR IA32_PLATFORM_ID - // - PlatformIdMsr.Uint64 = AsmReadMsr64 (MSR_IA32_PLATFORM_ID); - PlatformId = (UINT8) PlatformIdMsr.Bits.PlatformId; + Eax.Uint32 = CpuMpData->CpuData[ProcessorNumber].ProcessorSignature; + PlatformId = CpuMpData->CpuData[ProcessorNumber].PlatformId; // // Check whether AP has same processor with BSP. // If yes, direct use microcode info saved by BSP. // if (!IsBspCallIn) { - if ((CpuMpData->ProcessorSignature == Eax.Uint32) && - (CpuMpData->ProcessorFlags & (1 << PlatformId)) != 0) { - MicrocodeData = (VOID *)(UINTN) CpuMpData->MicrocodeDataAddress; - LatestRevision = CpuMpData->MicrocodeRevision; - goto Done; + // + // Get the CPU data for BSP + // + CpuData = &(CpuMpData->CpuData[CpuMpData->BspNumber]); + if ((CpuData->ProcessorSignature == Eax.Uint32) && + (CpuData->PlatformId == PlatformId) && + (CpuData->MicrocodeEntryAddr != 0)) { + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *)(UINTN) CpuData->MicrocodeEntryAddr; + MicrocodeData = (VOID *) (MicrocodeEntryPoint + 1); + LatestRevision = MicrocodeEntryPoint->UpdateRevision; + goto Done; } } @@ -216,7 +207,6 @@ MicrocodeDetect ( CheckSum32 += MicrocodeEntryPoint->Checksum; if (CheckSum32 == 0) { CorrectMicrocode = TRUE; - ProcessorFlags = MicrocodeEntryPoint->ProcessorFlags; } } else if ((MicrocodeEntryPoint->DataSize != 0) && (MicrocodeEntryPoint->UpdateRevision > LatestRevision)) { @@ -260,7 +250,6 @@ MicrocodeDetect ( // Find one // CorrectMicrocode = TRUE; - ProcessorFlags = ExtendedTable->ProcessorFlag; break; } } @@ -332,18 +321,6 @@ MicrocodeDetect ( ReleaseSpinLock(&CpuMpData->MpLock); } } - - if (IsBspCallIn && (LatestRevision != 0)) { - // - // Save BSP processor info and microcode info for later AP use. - // - CpuMpData->ProcessorSignature = Eax.Uint32; - CpuMpData->ProcessorFlags = ProcessorFlags; - CpuMpData->MicrocodeDataAddress = (UINTN) MicrocodeData; - CpuMpData->MicrocodeRevision = LatestRevision; - DEBUG ((DEBUG_INFO, "BSP Microcode:: signature [0x%08x], ProcessorFlags [0x%08x], \ - MicroData [0x%08x], Revision [0x%08x]\n", Eax.Uint32, ProcessorFlags, (UINTN) MicrocodeData, LatestRevision)); - } } /** diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 5f50e79744c..6609c958ce8 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -263,11 +263,6 @@ struct _CPU_MP_DATA { BOOLEAN PeriodicMode; BOOLEAN TimerInterruptState; - UINT32 ProcessorSignature; - UINT32 ProcessorFlags; - UINT64 MicrocodeDataAddress; - UINT32 MicrocodeRevision; - // // Whether need to use Init-Sipi-Sipi to wake up the APs. // Two cases need to set this value to TRUE. One is in HLT From 33a32936510ecff00d0b6aeaeb9c8b2bf5430b8b Mon Sep 17 00:00:00 2001 From: "Dong, Guo" Date: Wed, 18 Dec 2019 08:12:17 +0800 Subject: [PATCH 228/384] UefiPayloadPkg/BootManager: Add PS2 keyboard support Add PS2 keyboard support. REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2316 This patch adds PS2 keyboard support in boot manager, and add a build flag PS2_KEYBOARD_ENABLE for PS2 keyboard to build PS2 keyboard driver and SIO driver. Be default the build flag is not enabled since PS2 keyboard is not common used. could use -DPS2_KEYBOARD_ENABLE to enable build it if need this feature. Signed-off-by: Guo Dong Reviewed-by: Maurice Ma Reviewed-by: Benjamin You --- .../PlatformBootManagerLib/PlatformConsole.c | 25 +++++++++++++++---- UefiPayloadPkg/UefiPayloadPkg.fdf | 4 +++ UefiPayloadPkg/UefiPayloadPkgIa32.dsc | 4 +++ UefiPayloadPkg/UefiPayloadPkgIa32X64.dsc | 5 ++++ 4 files changed, 33 insertions(+), 5 deletions(-) diff --git a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformConsole.c b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformConsole.c index ee2d8c8d1ed..a27cc552ab8 100644 --- a/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformConsole.c +++ b/UefiPayloadPkg/Library/PlatformBootManagerLib/PlatformConsole.c @@ -44,6 +44,9 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #define gPnp16550ComPort \ PNPID_DEVICE_PATH_NODE(0x0501) +#define gPnpPs2Keyboard \ + PNPID_DEVICE_PATH_NODE(0x0303) + #define gUartVendor \ { \ { \ @@ -87,7 +90,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent DEVICE_PATH_MESSAGING_PC_ANSI \ } - +ACPI_HID_DEVICE_PATH gPnpPs2KeyboardDeviceNode = gPnpPs2Keyboard; ACPI_HID_DEVICE_PATH gPnp16550ComPortDeviceNode = gPnp16550ComPort; UART_DEVICE_PATH gUartDeviceNode = gUart; VENDOR_DEVICE_PATH gTerminalTypeDeviceNode = gPcAnsiTerminal; @@ -109,12 +112,15 @@ EFI_DEVICE_PATH_PROTOCOL *gPlatformRootBridges[] = { BOOLEAN mDetectVgaOnly; /** - Add UART to ConOut, ConIn, ErrOut. + Add IsaKeyboard to ConIn; add IsaSerial to ConOut, ConIn, ErrOut. - @param[in] DeviceHandle - LPC device path. + @param[in] DeviceHandle Handle of the LPC Bridge device. - @retval EFI_SUCCESS - Serial console is added to ConOut, ConIn, and ErrOut. - @retval EFI_STATUS - No serial console is added. + @retval EFI_SUCCESS Console devices on the LPC bridge have been added to + ConOut, ConIn, and ErrOut. + + @return Error codes, due to EFI_DEVICE_PATH_PROTOCOL missing + from DeviceHandle. **/ EFI_STATUS PrepareLpcBridgeDevicePath ( @@ -123,6 +129,7 @@ PrepareLpcBridgeDevicePath ( { EFI_STATUS Status; EFI_DEVICE_PATH_PROTOCOL *DevicePath; + EFI_DEVICE_PATH_PROTOCOL *TempDevicePath; DevicePath = NULL; Status = gBS->HandleProtocol ( @@ -133,10 +140,18 @@ PrepareLpcBridgeDevicePath ( if (EFI_ERROR (Status)) { return Status; } + TempDevicePath = DevicePath; + + // + // Register Keyboard + // + DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&gPnpPs2KeyboardDeviceNode); + EfiBootManagerUpdateConsoleVariable (ConIn, DevicePath, NULL); // // Register COM1 // + DevicePath = TempDevicePath; DevicePath = AppendDevicePathNode ((EFI_DEVICE_PATH_PROTOCOL *)NULL, (EFI_DEVICE_PATH_PROTOCOL *)&gUartDeviceVendorNode); DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&gUartDeviceNode); DevicePath = AppendDevicePathNode (DevicePath, (EFI_DEVICE_PATH_PROTOCOL *)&gTerminalTypeDeviceNode); diff --git a/UefiPayloadPkg/UefiPayloadPkg.fdf b/UefiPayloadPkg/UefiPayloadPkg.fdf index 4cd88a3f855..dfbcde56684 100644 --- a/UefiPayloadPkg/UefiPayloadPkg.fdf +++ b/UefiPayloadPkg/UefiPayloadPkg.fdf @@ -120,6 +120,10 @@ INF MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf # ISA Support # INF MdeModulePkg/Universal/SerialDxe/SerialDxe.inf +!if $(PS2_KEYBOARD_ENABLE) == TRUE +INF OvmfPkg/SioBusDxe/SioBusDxe.inf +INF MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf +!endif # # Console Support diff --git a/UefiPayloadPkg/UefiPayloadPkgIa32.dsc b/UefiPayloadPkg/UefiPayloadPkgIa32.dsc index 11cf17ca064..d52945442e0 100644 --- a/UefiPayloadPkg/UefiPayloadPkgIa32.dsc +++ b/UefiPayloadPkg/UefiPayloadPkgIa32.dsc @@ -491,6 +491,10 @@ # ISA Support # MdeModulePkg/Universal/SerialDxe/SerialDxe.inf +!if $(PS2_KEYBOARD_ENABLE) == TRUE + OvmfPkg/SioBusDxe/SioBusDxe.inf + MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf +!endif # # Console Support diff --git a/UefiPayloadPkg/UefiPayloadPkgIa32X64.dsc b/UefiPayloadPkg/UefiPayloadPkgIa32X64.dsc index 5b7994a62cd..0736cd99547 100644 --- a/UefiPayloadPkg/UefiPayloadPkgIa32X64.dsc +++ b/UefiPayloadPkg/UefiPayloadPkgIa32X64.dsc @@ -25,6 +25,7 @@ FLASH_DEFINITION = UefiPayloadPkg/UefiPayloadPkg.fdf DEFINE SOURCE_DEBUG_ENABLE = FALSE + DEFINE PS2_KEYBOARD_ENABLE = FALSE # # SBL: UEFI payload for Slim Bootloader @@ -492,6 +493,10 @@ # ISA Support # MdeModulePkg/Universal/SerialDxe/SerialDxe.inf +!if $(PS2_KEYBOARD_ENABLE) == TRUE + OvmfPkg/SioBusDxe/SioBusDxe.inf + MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KeyboardDxe.inf +!endif # # Console Support From b948a496150f4ae4f656c0f0ab672608723c80e6 Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Fri, 27 Dec 2019 15:30:27 +0800 Subject: [PATCH 229/384] UefiCpuPkg/PiSmmCpuDxeSmm: Pre-allocate PROCEDURE_TOKEN buffer REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2388 Token is new introduced by MM MP Protocol. Current logic allocate Token every time when need to use it. The logic caused SMI latency raised to very high. Update logic to allocate Token buffer at driver's entry point. Later use the token from the allocated token buffer. Only when all the buffer have been used, then need to allocate new buffer. Former change (9caaa79dd7e078ebb4012dde3b3d3a5d451df609) missed PROCEDURE_TOKEN part, this change covers it. Reviewed-by: Ray Ni Cc: Laszlo Ersek Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 190 ++++++++++++--------- UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h | 6 +- 2 files changed, 109 insertions(+), 87 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 4808045f71a..870250b0c55 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -429,38 +429,29 @@ ReleaseToken ( **/ VOID -FreeTokens ( +ResetTokens ( VOID ) { LIST_ENTRY *Link; PROCEDURE_TOKEN *ProcToken; - TOKEN_BUFFER *TokenBuf; - // - // Only free the token buffer recorded in the OldTOkenBufList - // upon exiting SMI. Current token buffer stays allocated so - // next SMI doesn't need to re-allocate. - // - gSmmCpuPrivate->UsedTokenNum = 0; - - Link = GetFirstNode (&gSmmCpuPrivate->OldTokenBufList); - while (!IsNull (&gSmmCpuPrivate->OldTokenBufList, Link)) { - TokenBuf = TOKEN_BUFFER_FROM_LINK (Link); - - Link = RemoveEntryList (&TokenBuf->Link); - - FreePool (TokenBuf->Buffer); - FreePool (TokenBuf); - } - - while (!IsListEmpty (&gSmmCpuPrivate->TokenList)) { - Link = GetFirstNode (&gSmmCpuPrivate->TokenList); + Link = GetFirstNode (&gSmmCpuPrivate->TokenList); + while (!IsNull (&gSmmCpuPrivate->TokenList, Link)) { ProcToken = PROCEDURE_TOKEN_FROM_LINK (Link); - RemoveEntryList (&ProcToken->Link); + ProcToken->RunningApCount = 0; + ProcToken->Used = FALSE; + + // + // Check the spinlock status and release it if not released yet. + // + if (!AcquireSpinLockOrFail(ProcToken->SpinLock)) { + DEBUG((DEBUG_ERROR, "Risk::SpinLock still not released!")); + } + ReleaseSpinLock (ProcToken->SpinLock); - FreePool (ProcToken); + Link = GetNextNode (&gSmmCpuPrivate->TokenList, Link); } } @@ -685,9 +676,9 @@ BSPHandler ( WaitForAllAPs (ApCount); // - // Clean the tokens buffer. + // Reset the tokens buffer. // - FreeTokens (); + ResetTokens (); // // Reset BspIndex to -1, meaning BSP has not been elected. @@ -1056,7 +1047,7 @@ IsTokenInUse ( while (!IsNull (&gSmmCpuPrivate->TokenList, Link)) { ProcToken = PROCEDURE_TOKEN_FROM_LINK (Link); - if (ProcToken->SpinLock == Token) { + if (ProcToken->Used && ProcToken->SpinLock == Token) { return TRUE; } @@ -1067,61 +1058,112 @@ IsTokenInUse ( } /** - create token and save it to the maintain list. - - @param RunningApCount Input running AP count. - - @retval return the spin lock used as token. + Allocate buffer for the SPIN_LOCK and PROCEDURE_TOKEN. **/ -PROCEDURE_TOKEN * -CreateToken ( - IN UINT32 RunningApCount +VOID +AllocateTokenBuffer ( + VOID ) { - PROCEDURE_TOKEN *ProcToken; - SPIN_LOCK *SpinLock; UINTN SpinLockSize; - TOKEN_BUFFER *TokenBuf; UINT32 TokenCountPerChunk; + UINTN ProcTokenSize; + UINTN Index; + PROCEDURE_TOKEN *ProcToken; + SPIN_LOCK *SpinLock; + UINT8 *SpinLockBuffer; + UINT8 *ProcTokenBuffer; SpinLockSize = GetSpinLockProperties (); + ProcTokenSize = sizeof (PROCEDURE_TOKEN); + TokenCountPerChunk = FixedPcdGet32 (PcdCpuSmmMpTokenCountPerChunk); + ASSERT (TokenCountPerChunk != 0); + if (TokenCountPerChunk == 0) { + DEBUG ((DEBUG_ERROR, "PcdCpuSmmMpTokenCountPerChunk should not be Zero!\n")); + CpuDeadLoop (); + } + DEBUG ((DEBUG_INFO, "CpuSmm: SpinLock Size = 0x%x, PcdCpuSmmMpTokenCountPerChunk = 0x%x\n", SpinLockSize, TokenCountPerChunk)); - if (gSmmCpuPrivate->UsedTokenNum == TokenCountPerChunk) { - DEBUG ((DEBUG_VERBOSE, "CpuSmm: No free token buffer, allocate new buffer!\n")); + // + // Separate the Spin_lock and Proc_token because the alignment requires by Spin_Lock. + // + SpinLockBuffer = AllocatePool (SpinLockSize * TokenCountPerChunk); + ASSERT (SpinLockBuffer != NULL); - // - // Record current token buffer for later free action usage. - // Current used token buffer not in this list. - // - TokenBuf = AllocatePool (sizeof (TOKEN_BUFFER)); - ASSERT (TokenBuf != NULL); - TokenBuf->Signature = TOKEN_BUFFER_SIGNATURE; - TokenBuf->Buffer = gSmmCpuPrivate->CurrentTokenBuf; + ProcTokenBuffer = AllocatePool (ProcTokenSize * TokenCountPerChunk); + ASSERT (ProcTokenBuffer != NULL); + + for (Index = 0; Index < TokenCountPerChunk; Index++) { + SpinLock = (SPIN_LOCK *)(SpinLockBuffer + SpinLockSize * Index); + InitializeSpinLock (SpinLock); + + ProcToken = (PROCEDURE_TOKEN *)(ProcTokenBuffer + ProcTokenSize * Index); + ProcToken->Signature = PROCEDURE_TOKEN_SIGNATURE; + ProcToken->SpinLock = SpinLock; + ProcToken->Used = FALSE; + ProcToken->RunningApCount = 0; + + InsertTailList (&gSmmCpuPrivate->TokenList, &ProcToken->Link); + } +} - InsertTailList (&gSmmCpuPrivate->OldTokenBufList, &TokenBuf->Link); +/** + Find first free token in the allocated token list. + + @retval return the first free PROCEDURE_TOKEN. + +**/ +PROCEDURE_TOKEN * +FindFirstFreeToken ( + VOID + ) +{ + LIST_ENTRY *Link; + PROCEDURE_TOKEN *ProcToken; - gSmmCpuPrivate->CurrentTokenBuf = AllocatePool (SpinLockSize * TokenCountPerChunk); - ASSERT (gSmmCpuPrivate->CurrentTokenBuf != NULL); - gSmmCpuPrivate->UsedTokenNum = 0; + Link = GetFirstNode (&gSmmCpuPrivate->TokenList); + while (!IsNull (&gSmmCpuPrivate->TokenList, Link)) { + ProcToken = PROCEDURE_TOKEN_FROM_LINK (Link); + + if (!ProcToken->Used) { + return ProcToken; + } + + Link = GetNextNode (&gSmmCpuPrivate->TokenList, Link); } - SpinLock = (SPIN_LOCK *)(gSmmCpuPrivate->CurrentTokenBuf + SpinLockSize * gSmmCpuPrivate->UsedTokenNum); - gSmmCpuPrivate->UsedTokenNum++; + return NULL; +} + +/** + Get the free token. + + If no free token, allocate new tokens then return the free one. + + @retval return the first free PROCEDURE_TOKEN. - InitializeSpinLock (SpinLock); - AcquireSpinLock (SpinLock); +**/ +PROCEDURE_TOKEN * +GetFreeToken ( + IN UINT32 RunningApsCount + ) +{ + PROCEDURE_TOKEN *NewToken; - ProcToken = AllocatePool (sizeof (PROCEDURE_TOKEN)); - ASSERT (ProcToken != NULL); - ProcToken->Signature = PROCEDURE_TOKEN_SIGNATURE; - ProcToken->SpinLock = SpinLock; - ProcToken->RunningApCount = RunningApCount; + NewToken = FindFirstFreeToken (); + if (NewToken == NULL) { + AllocateTokenBuffer (); + NewToken = FindFirstFreeToken (); + } + ASSERT (NewToken != NULL); - InsertTailList (&gSmmCpuPrivate->TokenList, &ProcToken->Link); + NewToken->Used = TRUE; + NewToken->RunningApCount = RunningApsCount; + AcquireSpinLock (NewToken->SpinLock); - return ProcToken; + return NewToken; } /** @@ -1231,7 +1273,7 @@ InternalSmmStartupThisAp ( mSmmMpSyncData->CpuData[CpuIndex].Procedure = Procedure; mSmmMpSyncData->CpuData[CpuIndex].Parameter = ProcArguments; if (Token != NULL) { - ProcToken= CreateToken (1); + ProcToken= GetFreeToken (1); mSmmMpSyncData->CpuData[CpuIndex].Token = ProcToken; *Token = (MM_COMPLETION)ProcToken->SpinLock; } @@ -1320,7 +1362,7 @@ InternalSmmStartupAllAPs ( } if (Token != NULL) { - ProcToken = CreateToken ((UINT32)mMaxNumberOfCpus); + ProcToken = GetFreeToken ((UINT32)mMaxNumberOfCpus); *Token = (MM_COMPLETION)ProcToken->SpinLock; } else { ProcToken = NULL; @@ -1732,28 +1774,12 @@ InitializeDataForMmMp ( VOID ) { - UINTN SpinLockSize; - UINT32 TokenCountPerChunk; - - SpinLockSize = GetSpinLockProperties (); - TokenCountPerChunk = FixedPcdGet32 (PcdCpuSmmMpTokenCountPerChunk); - ASSERT (TokenCountPerChunk != 0); - if (TokenCountPerChunk == 0) { - DEBUG ((DEBUG_ERROR, "PcdCpuSmmMpTokenCountPerChunk should not be Zero!\n")); - CpuDeadLoop (); - } - DEBUG ((DEBUG_INFO, "CpuSmm: SpinLock Size = 0x%x, PcdCpuSmmMpTokenCountPerChunk = 0x%x\n", SpinLockSize, TokenCountPerChunk)); - - gSmmCpuPrivate->CurrentTokenBuf = AllocatePool (SpinLockSize * TokenCountPerChunk); - ASSERT (gSmmCpuPrivate->CurrentTokenBuf != NULL); - - gSmmCpuPrivate->UsedTokenNum = 0; - gSmmCpuPrivate->ApWrapperFunc = AllocatePool (sizeof (PROCEDURE_WRAPPER) * gSmmCpuPrivate->SmmCoreEntryContext.NumberOfCpus); ASSERT (gSmmCpuPrivate->ApWrapperFunc != NULL); InitializeListHead (&gSmmCpuPrivate->TokenList); - InitializeListHead (&gSmmCpuPrivate->OldTokenBufList); + + AllocateTokenBuffer (); } /** diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h index 5c98494e2c5..33b3dd140ea 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/PiSmmCpuDxeSmm.h @@ -214,6 +214,7 @@ typedef struct { SPIN_LOCK *SpinLock; volatile UINT32 RunningApCount; + BOOLEAN Used; } PROCEDURE_TOKEN; #define PROCEDURE_TOKEN_FROM_LINK(a) CR (a, PROCEDURE_TOKEN, Link, PROCEDURE_TOKEN_SIGNATURE) @@ -254,11 +255,6 @@ typedef struct { PROCEDURE_WRAPPER *ApWrapperFunc; LIST_ENTRY TokenList; - - LIST_ENTRY OldTokenBufList; - - UINT8 *CurrentTokenBuf; - UINT32 UsedTokenNum; // Only record tokens used in CurrentTokenBuf. } SMM_CPU_PRIVATE_DATA; extern SMM_CPU_PRIVATE_DATA *gSmmCpuPrivate; From 1014f94a4c085e6ac4ec6a646cfb10c7da716705 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 2 Jan 2020 13:06:14 -0800 Subject: [PATCH 230/384] Combine all external headers into a single UnitTestLib.h header. --- MdePkg/Include/Library/UnitTestAssertLib.h | 136 ---------------- MdePkg/Include/Library/UnitTestLib.h | 150 ++++++++++++++++++ MdePkg/Include/Library/UnitTestLogLib.h | 56 ------- .../Include/Library/UnitTestTerminationLib.h | 43 ----- MdePkg/MdePkg.dec | 13 -- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 1 - .../FrameworkInclude/UnitTestFrameworkTypes.h | 19 +++ .../UnitTestTerminationLibShell.c | 53 ------- .../UnitTestTerminationLibShell.inf | 37 ----- .../UnitTestAssertLib/UnitTestAssertLib.c | 1 - .../Library/UnitTestLib/UnitTestLib.c | 1 - .../Library/UnitTestLogLib/UnitTestLogLib.c | 19 ++- .../UnitTestTerminationLibDxe.c | 46 ------ .../UnitTestTerminationLibDxe.inf | 35 ---- UnitTestFrameworkPkg/ReadMe.md | 1 - .../SampleUnitTestApp/SampleUnitTestApp.c | 2 - .../SampleUnitTestPeim/SampleUnitTestPeim.c | 1 - .../SampleUnitTestSmm/SampleUnitTestSmm.c | 1 - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 4 - 19 files changed, 184 insertions(+), 435 deletions(-) delete mode 100644 MdePkg/Include/Library/UnitTestAssertLib.h delete mode 100644 MdePkg/Include/Library/UnitTestLogLib.h delete mode 100644 MdePkg/Include/Library/UnitTestTerminationLib.h delete mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c delete mode 100644 UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf delete mode 100644 UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c delete mode 100644 UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf diff --git a/MdePkg/Include/Library/UnitTestAssertLib.h b/MdePkg/Include/Library/UnitTestAssertLib.h deleted file mode 100644 index 83162e6b73d..00000000000 --- a/MdePkg/Include/Library/UnitTestAssertLib.h +++ /dev/null @@ -1,136 +0,0 @@ -/** @file - Provides a unit test assert helpers. This allows tests to focus on testing logic - and the library to handle common assertions. - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_ASSERT_LIB_H__ -#define __UNIT_TEST_ASSERT_LIB_H__ - - -#define UT_ASSERT_TRUE(Expression) \ - if(!UnitTestAssertTrue( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_FALSE(Expression) \ - if(!UnitTestAssertFalse( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ - if(!UnitTestAssertMemEqual( Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError( Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual( Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull(Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { return UNIT_TEST_ERROR_TEST_FAILED; } - - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ); - -#endif \ No newline at end of file diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 77c7d088ee8..04ce936ea7f 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -91,6 +91,7 @@ VOID ///================================================================================================ ///================================================================================================ + /* Method to Initialize the Unit Test framework @@ -181,4 +182,153 @@ SaveFrameworkState ( IN UINTN ContextToSaveSize ); + +///================================================================================================ +///================================================================================================ +/// +/// LOGGING AND ASSERTION DEFINITIONS/DECLARATIONS +/// +///================================================================================================ +///================================================================================================ + + +#define UT_ASSERT_TRUE(Expression) \ + if(!UnitTestAssertTrue( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_FALSE(Expression) \ + if(!UnitTestAssertFalse( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ + if(!UnitTestAssertMemEqual( Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertNotEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_EFI_ERROR(Status) \ + if(!UnitTestAssertNotEfiError( Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ + if(!UnitTestAssertStatusEqual( Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} + +#define UT_ASSERT_NOT_NULL(Pointer) \ + if(!UnitTestAssertNotNull(Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { return UNIT_TEST_ERROR_TEST_FAILED; } + + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ); + +#define UT_LOG_ERROR(Format, ...) \ + UnitTestLog( Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); +#define UT_LOG_WARNING(Format, ...) \ + UnitTestLog( Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); +#define UT_LOG_INFO(Format, ...) \ + UnitTestLog( Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); +#define UT_LOG_VERBOSE(Format, ...) \ + UnitTestLog( Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ); + #endif \ No newline at end of file diff --git a/MdePkg/Include/Library/UnitTestLogLib.h b/MdePkg/Include/Library/UnitTestLogLib.h deleted file mode 100644 index c3690716a9e..00000000000 --- a/MdePkg/Include/Library/UnitTestLogLib.h +++ /dev/null @@ -1,56 +0,0 @@ -/** @file - Provides a unit test framework logging. This allows tests to focus on testing logic - and the library to handle unit test specific logging. - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_LOG_LIB_H__ -#define __UNIT_TEST_LOG_LIB_H__ - - - -///================================================================================================ -///================================================================================================ -/// -/// UNIT TEST LOGGING DEFINITIONS AND FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// IMPORTANT NOTE: These macros should ONLY be used in a Unit Test. -// They will consume the Framework Handle and update the Framework->CurrentTest. - -#define UT_LOG_ERROR(Format, ...) \ - UnitTestLog( Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); -#define UT_LOG_WARNING(Format, ...) \ - UnitTestLog( Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); -#define UT_LOG_INFO(Format, ...) \ - UnitTestLog( Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); -#define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog( Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); - -VOID -EFIAPI -UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - ... - ); - -// TODO: This header should not require the framework types. - -VOID -EFIAPI -UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE Test, - IN UINT8 *Buffer OPTIONAL, - IN UINTN BufferSize - ); - -#endif \ No newline at end of file diff --git a/MdePkg/Include/Library/UnitTestTerminationLib.h b/MdePkg/Include/Library/UnitTestTerminationLib.h deleted file mode 100644 index c22de0ca842..00000000000 --- a/MdePkg/Include/Library/UnitTestTerminationLib.h +++ /dev/null @@ -1,43 +0,0 @@ -/** @file -- UnitTestTerminationLib.h -This library abstracts the methods that a test could exit prematurely. -It allows tests written for different contexts to handle Quit()/Reboot() differently. - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef _UNIT_TEST_TERMINATION_LIB_H_ -#define _UNIT_TEST_TERMINATION_LIB_H_ - - -/** - Specific function to take steps to quit the test in progress immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkExit ( - VOID - ); - -/** - Specific function to take steps to reboot the test machine immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ); - - -#endif // _UNIT_TEST_TERMINATION_LIB_H_ diff --git a/MdePkg/MdePkg.dec b/MdePkg/MdePkg.dec index 38a7e30750d..ac1f5339af0 100644 --- a/MdePkg/MdePkg.dec +++ b/MdePkg/MdePkg.dec @@ -244,23 +244,10 @@ ## @libraryclass Module entry point library for standalone MM drivers. StandaloneMmDriverEntryPoint|Include/Library/StandaloneMmDriverEntryPoint.h - ## @libraryclass Provide unit test assert helpers - # - UnitTestAssertLib|Include/Library/UnitTestAssertLib.h - ## @libraryclass Provides a unit test framework # UnitTestLib|Include/Library/UnitTestLib.h - ## @libraryclass Provide unit test logging - # - UnitTestLogLib|Include/Library/UnitTestLogLib.h - - ## @libraryclass Abstracts the methods that a test could exit prematurely. - # Allows tests written for different contexts to handle Quit()/Reboot() differently. - # - UnitTestTerminationLib|Include/Library/UnitTestTerminationLib.h - [LibraryClasses.IA32, LibraryClasses.X64] ## @libraryclass Abstracts both S/W SMI generation and detection. ## diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index 93bbe899254..38d1664088e 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -36,7 +36,6 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include #include -#include #include UNIT_TEST_STATUS diff --git a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h index 03e55850c21..d161db61aa8 100644 --- a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h @@ -124,4 +124,23 @@ typedef struct // CHAR8 Log[]; // NOTE: Not yet implemented!! } UNIT_TEST_SAVE_HEADER; +/** + This function is responsible for initializing the log buffer for a single test. It can + be used internally, but may also be consumed by the test framework to add pre-existing + data to a log before it's used. + + @param[in,out] TestHandle A handle to the test being initialized. + @param[in] Buffer [Optional] A pointer to pre-existing log data that should + be used to initialize the log. Should include a NULL terminator. + @param[in] BufferSize [Optional] The size of the pre-existing log data. + +**/ +VOID +EFIAPI +UnitTestLogInit ( + IN OUT UNIT_TEST_HANDLE TestHandle, + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize OPTIONAL + ); + #endif \ No newline at end of file diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c deleted file mode 100644 index 6dfa3a0c357..00000000000 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.c +++ /dev/null @@ -1,53 +0,0 @@ -/** @file -- UnitTestTerminationLibShell.c -DXE Driver-/Application-specific methods of exiting a test. - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -#include - - -/** - Specific function to take steps to quit the test in progress immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkExit ( - VOID - ) -{ - gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); -} // FrameworkExit() - -/** - Specific function to take steps to reboot the test machine immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - // - // Next, we want to update the BootNext variable to the device - // so that we have a fighting chance of coming back here. - // - SetBootNextDevice(); - - gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); -} // FrameworkResetSystem() diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf b/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf deleted file mode 100644 index ef539b73518..00000000000 --- a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf +++ /dev/null @@ -1,37 +0,0 @@ -## @file UnitTestTerminationLibShell.inf -# DXE Driver-/Application-specific methods of exiting a test. -# -## -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestTerminationLibShell - FILE_GUID = E5C189CF-CA58-45C0-9EA9-C30D04FB705D - VERSION_STRING = 1.0 - MODULE_TYPE = UEFI_APPLICATION - LIBRARY_CLASS = UnitTestTerminationLib|UEFI_APPLICATION - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - - -[Sources] - UnitTestTerminationLibShell.c - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[LibraryClasses] - UefiBootServicesTableLib - UefiRuntimeServicesTableLib - UnitTestBootLib diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c index 065da737814..0473cb6fdcb 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c @@ -13,7 +13,6 @@ Copyright (c) Microsoft #include #include -#include STATIC diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index c30785a8c6a..47800b5fc4e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -14,7 +14,6 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include -#include #include #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c index f94b5000035..7daac4950ab 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c @@ -15,7 +15,6 @@ Copyright (c) Microsoft #include #include -#include #define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) #define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) @@ -114,12 +113,24 @@ AddStringToUnitTestLog ( // ---------------- PUBLIC FUNCTIONS ------------------------------------ // //============================================================================= + +/** + This function is responsible for initializing the log buffer for a single test. It can + be used internally, but may also be consumed by the test framework to add pre-existing + data to a log before it's used. + + @param[in,out] TestHandle A handle to the test being initialized. + @param[in] Buffer [Optional] A pointer to pre-existing log data that should + be used to initialize the log. Should include a NULL terminator. + @param[in] BufferSize [Optional] The size of the pre-existing log data. + +**/ VOID EFIAPI UnitTestLogInit ( IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer, - IN UINTN BufferSize + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize OPTIONAL ) { UNIT_TEST *Test; @@ -152,7 +163,7 @@ UnitTestLogInit ( { CopyMem(Test->Log, Buffer, BufferSize); } -} +} // UnitTestLogInit() VOID EFIAPI diff --git a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c deleted file mode 100644 index eb051c57889..00000000000 --- a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.c +++ /dev/null @@ -1,46 +0,0 @@ -/** @file -- UnitTestTerminationLibDxe.c -DXE Driver-/Application-specific methods of exiting a test. - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - - -/** - Specific function to take steps to quit the test in progress immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkExit ( - VOID - ) -{ - gBS->Exit( gImageHandle, EFI_SUCCESS, 0, NULL ); -} // FrameworkExit() - -/** - Specific function to take steps to reboot the test machine immediately - without proceeding through the remaining test cases. This may be used because - a test case specifically needs to hand of execution and re-enter to - complete a test. - - NOTE: If this function returns, test harness will assume something has gone wrong. - -**/ -VOID -FrameworkResetSystem ( - IN EFI_RESET_TYPE ResetType - ) -{ - gRT->ResetSystem( ResetType, EFI_SUCCESS, 0, NULL ); -} // FrameworkResetSystem() diff --git a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf b/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf deleted file mode 100644 index f6dd569a7fb..00000000000 --- a/UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf +++ /dev/null @@ -1,35 +0,0 @@ -## @file UnitTestTerminationLibDxe.inf -# DXE Driver-/Application-specific methods of exiting a test. -# -## -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestTerminationLibDxe - FILE_GUID = 85A01B72-6270-42B0-A349-7170CC6AC2AF - VERSION_STRING = 1.0 - MODULE_TYPE = DXE_DRIVER - LIBRARY_CLASS = UnitTestTerminationLib|DXE_DRIVER UEFI_APPLICATION - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - - -[Sources] - UnitTestTerminationLibDxe.c - - -[Packages] - MdePkg/MdePkg.dec - - -[LibraryClasses] - UefiBootServicesTableLib - UefiRuntimeServicesTableLib diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index b83a59212d9..abd3cbf295f 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -90,7 +90,6 @@ Not to state the obvious, but let's make sure we have the following includes bef ```c #include -#include ``` Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 647b88801f8..877d7af0b4e 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -23,8 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include -#include #define UNIT_TEST_APP_NAME "Sample Unit Test Library Application" diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 2d8c762531a..e4b9f637b42 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -23,7 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include #define UNIT_TEST_PEIM_NAME "Sample Unit Test Library PEIM" diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index c1d79d141bc..d4ae0261705 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -23,7 +23,6 @@ Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. #include #include -#include #define UNIT_TEST_SMM_NAME "Sample Unit Test Library SMM" diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 1e70f1e990a..de0ff57a7ad 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -156,7 +156,6 @@ UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestLogLib|UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf UnitTestPersistenceLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - #UnitTestBootLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf [LibraryClasses.common.PEIM] UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf @@ -169,7 +168,6 @@ [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestTerminationLib|UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf [Components] UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf @@ -180,11 +178,9 @@ UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestFrameworkPkg/Library/UnitTestTerminationLibDxe/UnitTestTerminationLibDxe.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestTerminationLibShell/UnitTestTerminationLibShell.inf UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf From 1f66b1797dfeafab15a94f59bdb5b8612121e927 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 2 Jan 2020 13:08:13 -0800 Subject: [PATCH 231/384] Drop the Cmocka submodule to prepare for library moving. --- .gitmodules | 3 --- UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka | 1 - 2 files changed, 4 deletions(-) delete mode 160000 UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka diff --git a/.gitmodules b/.gitmodules index 279eccadc52..508f0c18287 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,6 +4,3 @@ [submodule "SoftFloat"] path = ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 url = https://github.com/ucb-bar/berkeley-softfloat-3.git -[submodule "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka"] - path = UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka - url = https://git.cryptomilk.org/projects/cmocka.git diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka b/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka deleted file mode 160000 index 1cc9cde3448..00000000000 --- a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka +++ /dev/null @@ -1 +0,0 @@ -Subproject commit 1cc9cde3448cdd2e000886a26acf1caac2db7cf1 From cbcd13517f22ca7ff5e08114ffbe17782f7a7d13 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 2 Jan 2020 13:09:11 -0800 Subject: [PATCH 232/384] Combine FrameworkLibrary and Library directories. --- .../{FrameworkLibrary => Library}/CmockaLib/CmockaLib.inf | 0 .../{FrameworkLibrary => Library}/CmockaLib/CmockaLib.uni | 0 .../OsServiceLibHost/OsServiceLibGcc.c | 0 .../OsServiceLibHost/OsServiceLibHost.inf | 0 .../OsServiceLibHost/OsServiceLibMsvc.c | 0 .../{FrameworkLibrary => Library}/OsServiceLibHost/WinNTInclude.h | 0 .../UnitTestBootLibNull/UnitTestBootLibNull.c | 0 .../UnitTestBootLibNull/UnitTestBootLibNull.inf | 0 .../UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c | 0 .../UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf | 0 .../UnitTestPersistenceLibFileSystem.c | 0 .../UnitTestPersistenceLibFileSystem.inf | 0 .../UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c | 0 .../UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf | 0 .../UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c | 0 .../UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf | 0 .../UnitTestResultReportLibPlainTextOutput.c | 0 .../UnitTestResultReportLibPlainTextOutput.inf | 0 18 files changed, 0 insertions(+), 0 deletions(-) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/CmockaLib/CmockaLib.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/CmockaLib/CmockaLib.uni (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/OsServiceLibHost/OsServiceLibGcc.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/OsServiceLibHost/OsServiceLibHost.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/OsServiceLibHost/OsServiceLibMsvc.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/OsServiceLibHost/WinNTInclude.h (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestBootLibNull/UnitTestBootLibNull.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestBootLibNull/UnitTestBootLibNull.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c (100%) rename UnitTestFrameworkPkg/{FrameworkLibrary => Library}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf (100%) diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf rename to UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.uni rename to UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c b/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibGcc.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibGcc.c rename to UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibGcc.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf b/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibHost.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf rename to UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibHost.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c b/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibMsvc.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibMsvc.c rename to UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibMsvc.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h b/UnitTestFrameworkPkg/Library/OsServiceLibHost/WinNTInclude.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/WinNTInclude.h rename to UnitTestFrameworkPkg/Library/OsServiceLibHost/WinNTInclude.h diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.c rename to UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf rename to UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c rename to UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf rename to UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf similarity index 100% rename from UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf rename to UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf From 073958500f665e06e07d51f44f9aac1616eba2ad Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 2 Jan 2020 13:35:12 -0800 Subject: [PATCH 233/384] Consolidate and reorganize Framework Libraries. --- .gitmodules | 3 ++ .pytool/CISettings.py | 2 +- MdePkg/Test/MdePkgTest.dsc | 10 ++--- .../{ => HostCMocka}/CmockaLib/CmockaLib.inf | 0 .../{ => HostCMocka}/CmockaLib/CmockaLib.uni | 0 .../Library/HostCMocka/CmockaLib/cmocka | 1 + .../UnitTestAssertLib.c | 0 .../UnitTestAssertLibcmocka.inf | 0 .../IA32/cmockaFuncTemplateGcc.nasm | 0 .../IA32/cmockaFuncTemplateMsvc.nasm | 0 .../UnitTestLibcmocka/UnitTestLib.c | 0 .../UnitTestLibcmocka/UnitTestLibcmocka.inf | 0 .../X64/cmockaFuncTemplateGcc.nasm | 0 .../X64/cmockaFuncTemplateMsvc.nasm | 0 .../OsServiceLibHost/OsServiceLibGcc.c | 0 .../OsServiceLibHost/OsServiceLibHost.inf | 0 .../OsServiceLibHost/OsServiceLibMsvc.c | 0 .../OsServiceLibHost/WinNTInclude.h | 0 .../UnitTestAssertLib/UnitTestAssertLib.c | 0 .../UnitTestAssertLib/UnitTestAssertLib.inf | 0 .../UnitTestBootLibNull/UnitTestBootLibNull.c | 0 .../UnitTestBootLibNull.inf | 0 .../{ => UEFI}/UnitTestLib/UnitTestLib.c | 0 .../{ => UEFI}/UnitTestLib/UnitTestLibDxe.inf | 0 .../{ => UEFI}/UnitTestLib/UnitTestLibPei.inf | 0 .../{ => UEFI}/UnitTestLib/UnitTestLibSmm.inf | 0 .../UnitTestLogLib/UnitTestLogLib.c | 0 .../UnitTestLogLib/UnitTestLogLib.inf | 0 .../UnitTestPersistenceLibNull.c | 0 .../UnitTestPersistenceLibNull.inf | 0 .../UnitTestResultReportLibDebug.c | 0 .../UnitTestResultReportLibDebug.inf | 0 .../UnitTestBootLibUsbClass.c | 0 .../UnitTestBootLibUsbClass.inf | 0 .../UnitTestPersistenceLibFileSystem.c | 0 .../UnitTestPersistenceLibFileSystem.inf | 0 .../UnitTestResultReportLibPlainTextOutput.c | 0 ...UnitTestResultReportLibPlainTextOutput.inf | 0 .../UnitTestFrameworkPkg.ci.yaml | 8 ++-- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 4 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 40 +++++++++---------- 41 files changed, 36 insertions(+), 32 deletions(-) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/CmockaLib/CmockaLib.inf (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/CmockaLib/CmockaLib.uni (100%) create mode 160000 UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestAssertLibcmocka/UnitTestAssertLib.c (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/UnitTestLib.c (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/UnitTestLibcmocka.inf (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm (100%) rename UnitTestFrameworkPkg/Library/{ => HostCMocka}/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm (100%) rename UnitTestFrameworkPkg/Library/{ => HostCRT}/OsServiceLibHost/OsServiceLibGcc.c (100%) rename UnitTestFrameworkPkg/Library/{ => HostCRT}/OsServiceLibHost/OsServiceLibHost.inf (100%) rename UnitTestFrameworkPkg/Library/{ => HostCRT}/OsServiceLibHost/OsServiceLibMsvc.c (100%) rename UnitTestFrameworkPkg/Library/{ => HostCRT}/OsServiceLibHost/WinNTInclude.h (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestAssertLib/UnitTestAssertLib.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestAssertLib/UnitTestAssertLib.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestBootLibNull/UnitTestBootLibNull.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestBootLibNull/UnitTestBootLibNull.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLib/UnitTestLib.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLib/UnitTestLibDxe.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLib/UnitTestLibPei.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLib/UnitTestLibSmm.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLogLib/UnitTestLogLib.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestLogLib/UnitTestLogLib.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c (100%) rename UnitTestFrameworkPkg/Library/{ => UEFI}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c (100%) rename UnitTestFrameworkPkg/Library/{ => UefiShell}/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf (100%) diff --git a/.gitmodules b/.gitmodules index 508f0c18287..8226463f64b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,3 +4,6 @@ [submodule "SoftFloat"] path = ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 url = https://github.com/ucb-bar/berkeley-softfloat-3.git +[submodule "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka"] + path = UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka + url = https://git.cryptomilk.org/projects/cmocka.git diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 72e1feccf8b..0ab142f8660 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -144,7 +144,7 @@ def GetRequiredSubmodules(self): rs.append(RequiredSubmodule( "CryptoPkg/Library/OpensslLib/openssl", False)) rs.append(RequiredSubmodule( - "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/cmocka", False)) + "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka", False)) return rs def GetName(self): diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 7ccc42f6aa2..f81d7a72b5c 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -16,13 +16,13 @@ SKUID_IDENTIFIER = DEFAULT [LibraryClasses] - CmockaLib|UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf + CmockaLib|UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf BaseLib|MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf BaseMemoryLib|MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - OsServiceLib|UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf + OsServiceLib|UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf @@ -30,12 +30,12 @@ PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf + UnitTestLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf [Components] - UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf { + UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf { MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf rename to UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.uni similarity index 100% rename from UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni rename to UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.uni diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka b/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka new file mode 160000 index 00000000000..1cc9cde3448 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka @@ -0,0 +1 @@ +Subproject commit 1cc9cde3448cdd2e000886a26acf1caac2db7cf1 diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm diff --git a/UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm rename to UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm diff --git a/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibGcc.c b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c similarity index 100% rename from UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibGcc.c rename to UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c diff --git a/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibHost.inf b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibHost.inf rename to UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf diff --git a/UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibMsvc.c b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c similarity index 100% rename from UnitTestFrameworkPkg/Library/OsServiceLibHost/OsServiceLibMsvc.c rename to UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c diff --git a/UnitTestFrameworkPkg/Library/OsServiceLibHost/WinNTInclude.h b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h similarity index 100% rename from UnitTestFrameworkPkg/Library/OsServiceLibHost/WinNTInclude.h rename to UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf rename to UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf rename to UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index ae57f1163f0..c62b7e205c2 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,10 +30,10 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/Library/UnitTestLibcmocka/UnitTestLibcmocka.inf", - "UnitTestFrameworkPkg/Library/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", - "UnitTestFrameworkPkg/FrameworkLibrary/OsServiceLibHost/OsServiceLibHost.inf", - "UnitTestFrameworkPkg/FrameworkLibrary/CmockaLib/CmockaLib.inf" + "UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf", + "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf", + "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", + "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf" ] }, "GuidCheck": { diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index dc2254887da..ae801ed60e0 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -18,8 +18,8 @@ [Includes.Common.Private] FrameworkInclude - FrameworkLibrary/CmockaLib/cmocka/include - FrameworkLibrary/CmockaLib/cmocka/include/cmockery + Library/HostCMocka/CmockaLib/cmocka/include + Library/HostCMocka/CmockaLib/cmocka/include/cmockery [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index de0ff57a7ad..3ed3ce5ec83 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -153,34 +153,34 @@ # UnitTestFrameworkPkg # [LibraryClasses] - UnitTestAssertLib|UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestLogLib|UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPersistenceLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestLogLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.PEIM] - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_SMM_DRIVER] - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf [Components] - UnitTestFrameworkPkg/Library/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibDxe.inf - UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibPei.inf - UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibSmm.inf - UnitTestFrameworkPkg/Library/UnitTestLogLib/UnitTestLogLib.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestFrameworkPkg/FrameworkLibrary/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf From 571a88c52b4dd0477974cf733693f2fcd82f5e73 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:49:39 -0800 Subject: [PATCH 234/384] UnitTestFrameworkPkg/UnitTestAssertLibcomcka: Use snprintf() Replace sprintf() with Use snprintf() that is considered safe for both VS20xx and GCCx tool chains. Signed-off-by: Michael D Kinney --- .../UnitTestAssertLibcmocka/UnitTestAssertLib.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c index bfd5593c200..d56fdee15f7 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c @@ -35,7 +35,7 @@ UnitTestAssertTrue ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_TRUE(%s:%x)", Description, Expression); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); _assert_true (Expression, Description, FileName, (INT32)LineNumber); return Expression; @@ -55,7 +55,7 @@ UnitTestAssertFalse ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_FALSE(%s:%x)", Description, Expression); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); _assert_true (!Expression, Description, FileName, (INT32)LineNumber); return !Expression; @@ -75,7 +75,7 @@ UnitTestAssertNotEfiError ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); return !EFI_ERROR (Status); @@ -97,7 +97,7 @@ UnitTestAssertEqual ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); return (ValueA == ValueB); @@ -122,7 +122,7 @@ UnitTestAssertMemEqual( Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); - sprintf (TempStr, "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); _assert_true (Result, TempStr, FileName, (INT32)LineNumber); return Result; @@ -144,7 +144,7 @@ UnitTestAssertNotEqual ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); return (ValueA != ValueB); @@ -165,7 +165,7 @@ UnitTestAssertStatusEqual ( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); return (Status == Expected); @@ -184,7 +184,7 @@ UnitTestAssertNotNull( { CHAR8 TempStr[MAX_STRING_SIZE]; - sprintf (TempStr, "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); return (Pointer != NULL); From 1525c7dec3bb9c3dcf5c0176944bcac01f27f3d8 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:50:42 -0800 Subject: [PATCH 235/384] UnitTestFrameworkPkg/OsServiceLibHost: Fix GCC build issue Add missing include for getpagesize(). Signed-off-by: Michael D Kinney --- .../Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c | 1 + 1 file changed, 1 insertion(+) diff --git a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c index 2bea976c685..a10bed71542 100644 --- a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c +++ b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c @@ -6,6 +6,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include +#include VOID * AllocateExecutableMemory ( From 2275128cd3e85deaea4fb9c133f3be73892e4a1a Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:52:04 -0800 Subject: [PATCH 236/384] UnitTestFrameworkPkg/UniTestLib: Fix GCC build issue Use correct parameter type for FreeUnitTestFramework() Signed-off-by: Michael D Kinney --- UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c index 47800b5fc4e..a47f4a59aac 100644 --- a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c @@ -150,7 +150,7 @@ CompareFingerprints ( EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ) { // TODO: Finish this function. @@ -272,7 +272,7 @@ InitUnitTestFramework ( // Otherwise, we need to undo this horrible thing that we've done. else { - FreeUnitTestFramework( NewFramework ); + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); } return Status; From dc5f1d254eb7c30859ce42cc53845c7ed4f9da4f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:53:21 -0800 Subject: [PATCH 237/384] UnitTestFrameworkPkg/UniTestLibcmocha: Fix GCC build issue * Use correct parameter type for FreeUnitTestFramework() * Disable use of assembly trampoline logic that breaks GCC X64. * Remove *ParentFramework local variable that is set but not used. Signed-off-by: Michael D Kinney --- .../HostCMocka/UnitTestLibcmocka/UnitTestLib.c | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c index f05010886e2..1e241dfe439 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c @@ -133,7 +133,7 @@ AllocateAndCopyString ( EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK *Framework + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ) { // TODO: Finish this function. @@ -238,7 +238,7 @@ InitUnitTestFramework ( // Otherwise, we need to undo this horrible thing that we've done. else { - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK *)NewFramework); + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); } return Status; @@ -309,6 +309,9 @@ CreateUnitTestSuite ( CopyMem ((VOID *)(UINTN)NewSuiteEntry->UTS.GroupTeardown, (VOID *)(UINTN)GroupTeardownTemplate, mGroupTeardownTemplateSize); *(UINTN *)((UINTN)NewSuiteEntry->UTS.GroupTeardown + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewSuiteEntry->UTS; + NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)Sup; + NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)Tdn; + Exit: // // If everything is going well, add the new suite to the tail list for the framework. @@ -342,12 +345,10 @@ AddTestCase ( EFI_STATUS Status; MY_UNIT_TEST_SUITE *MySuite; MY_UNIT_TEST_LIST_ENTRY *NewTestEntry; - MY_UNIT_TEST_FRAMEWORK *ParentFramework; UINTN TestNameSize; Status = EFI_SUCCESS; MySuite = (MY_UNIT_TEST_SUITE *)Suite; - ParentFramework = (MY_UNIT_TEST_FRAMEWORK*)MySuite->ParentFramework; // // First, let's check to make sure that our parameters look good. @@ -396,6 +397,10 @@ AddTestCase ( CopyMem ((VOID *)(UINTN)NewTestEntry->UT.TeardownFunc, (VOID *)(UINTN)TeardownFuncTemplate, mTeardownFuncTemplateSize); *(UINTN *)((UINTN)NewTestEntry->UT.TeardownFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; + NewTestEntry->UT.TestFunc = (CMUnitTestFunction)Func; + NewTestEntry->UT.SetupFunc = (CMFixtureFunction)PreReq; + NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)CleanUp; + TestNameSize = AsciiStrLen (Description) + 1; NewTestEntry->UT.TestName = AllocatePool (TestNameSize); ASSERT (NewTestEntry->UT.TestName != NULL); From cccd10a98b8896fd2b8afb2b9a945dd4e09f933f Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:55:13 -0800 Subject: [PATCH 238/384] UnitTestFrameworkPkg/UnitTestAssertLibcmocha: Remove [BuildOptions] With the change to use snprintf() instead of sprintf(), the [BuildOptions] that override the MSFT specific CC_FLAGS are no longer required. Signed-off-by: Michael D Kinney --- .../UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf | 3 --- 1 file changed, 3 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf index a75a03312e5..79ed139d006 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf @@ -23,6 +23,3 @@ [Sources] UnitTestAssertLib.c - -[BuildOptions] - MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF From 52f355842ffd7dc839043898cc3b9a221ae14c48 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 15:58:20 -0800 Subject: [PATCH 239/384] MdePkg/Test: Improve MdePkgTest.dsc compiler compatibility Add compatibility with VS2015, VS2015x86, VS2017, GCC5, CLANG9, XCODE. NOTE: VS2015, CLANG9, XCODE not tested yet. Cleanup lib mappings for all components and reduce use of host specific libraries. Signed-off-by: Michael D Kinney --- MdePkg/Test/MdePkgTest.dsc | 96 +++++++++++++++++++++++++------------- 1 file changed, 63 insertions(+), 33 deletions(-) diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index f81d7a72b5c..caad0b62e87 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -16,53 +16,83 @@ SKUID_IDENTIFIER = DEFAULT [LibraryClasses] - CmockaLib|UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf - - BaseLib|MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf - BaseMemoryLib|MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf - DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf - MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - OsServiceLib|UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf - + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf +[LibraryClasses.common.HOST_APPLICATION] + OsServiceLib|UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf + CmockaLib|UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf UnitTestLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf -[Components] - - UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf { - - MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF - - GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H - GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H - } - - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf - + DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf + MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - #compile all host application components - MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf - MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf - MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf +[Components] + # + # Build HostLibrary componments + # MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + # + # Build HOST_APPLICATION that tests the SafeIntLib + # + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf [BuildOptions] - MSFT:*_*_IA32_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /Gm /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /DHOST_DEBUG_MESSAGE=1 - MSFT:*_*_X64_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /Gm /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /DHOST_DEBUG_MESSAGE=1 + GCC:*_*_*_CC_FLAGS = -fno-pie [BuildOptions.common.EDKII.HOST_APPLICATION] - MSFT:*_*_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /MAP /OPT:REF /DEBUG /MACHINE:I386 /LTCG Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib - MSFT:*_*_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB:libcmt.lib /IGNORE:4001 /MAP /OPT:REF /DEBUG /MACHINE:x86 Kernel32.lib MSVCRTD.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib - - MSFT:*_*_IA32_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE /wd4305 - - MSFT:*_*_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB:libcmt.lib /IGNORE:4001 /MAP /OPT:REF /DEBUG /MACHINE:X64 MSVCRTD.lib Kernel32.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib - MSFT:*_*_X64_CC_FLAGS == /nologo /W4 /WX /Gy /c /D UNICODE /Od /FIAutoGen.h /EHs-c- /GF /Gs8192 /Zi /D _CRT_SECURE_NO_WARNINGS /D _CRT_SECURE_NO_DEPRECATE + # + # MSFT + # + MSFT:*_*_*_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /IGNORE:4001 /NOLOGO /SUBSYSTEM:CONSOLE /DEBUG /NODEFAULTLIB:libcmt.lib libcmtd.lib + MSFT:*_*_IA32_DLINK_FLAGS = /MACHINE:I386 + MSFT:*_*_X64_DLINK_FLAGS = /MACHINE:AMD64 + + MSFT:*_VS2015_IA32_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%Lib" /LIBPATH:"%VS2015_PREFIX%VC\Lib" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" + MSFT:*_VS2015x86_IA32_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%Lib" /LIBPATH:"%VS2015_PREFIX%VC\Lib" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" + MSFT:*_VS2017_IA32_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" + MSFT:*_VS2019_IA32_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x86" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" + + MSFT:*_VS2015_X64_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%VC\Lib\AMD64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" + MSFT:*_VS2015x86_X64_DLINK_FLAGS = /LIBPATH:"%VS2015_PREFIX%VC\Lib\AMD64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" + MSFT:*_VS2017_X64_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" + MSFT:*_VS2019_X64_DLINK_FLAGS = /LIBPATH:"%VCToolsInstallDir%lib\x64" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" + + # + # GCC + # + GCC:*_*_IA32_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m32 + GCC:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m64 + GCC:*_*_*_DLINK2_FLAGS == -lgcov + + # + # GCC CLANG9 + # + GCC:*_CLANG9_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /LIBPATH:"%VCToolsInstallDir%lib\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:AMD64 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint + GCC:*_CLANG9_X64_CC_FLAGS == -m64 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE + + GCC:*_CLANG9_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /LIBPATH:"%VCToolsInstallDir%ib\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:I386 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint + GCC:*_CLANG9_IA32_CC_FLAGS == -m32 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE + + # + # Need to do this link via gcc and not ld as the pathing to libraries changes from OS version to OS version + # + XCODE:*_*_IA32_DLINK_PATH == gcc + XCODE:*_*_IA32_CC_FLAGS = -I$(WORKSPACE)/EmulatorPkg/Unix/Host/X11IncludeHack + XCODE:*_*_IA32_DLINK_FLAGS == -arch i386 -o $(BIN_DIR)/Host -L/usr/X11R6/lib -lXext -lX11 -framework Carbon + XCODE:*_*_IA32_ASM_FLAGS == -arch i386 -g + + XCODE:*_*_X64_DLINK_PATH == gcc + XCODE:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/Host -L/usr/X11R6/lib -lXext -lX11 -framework Carbon -Wl,-no_pie + XCODE:*_*_X64_ASM_FLAGS == -g + XCODE:*_*_X64_CC_FLAGS = -O0 -target x86_64-apple-darwin -I$(WORKSPACE)/EmulatorPkg/Unix/Host/X11IncludeHack "-DEFIAPI=__attribute__((ms_abi))" From c8de68b7829243b733d161a3cec9d9c0ac53fe66 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 16:26:42 -0800 Subject: [PATCH 240/384] Remove OsServiceLib class and instance Also remove assembly trampline code. Signed-off-by: Michael D Kinney --- MdePkg/Test/MdePkgTest.dsc | 1 - .../FrameworkInclude/Library/OsServiceLib.h | 24 --- .../IA32/cmockaFuncTemplateGcc.nasm | 165 --------------- .../IA32/cmockaFuncTemplateMsvc.nasm | 165 --------------- .../UnitTestLibcmocka/UnitTestLib.c | 26 --- .../UnitTestLibcmocka/UnitTestLibcmocka.inf | 11 - .../X64/cmockaFuncTemplateGcc.nasm | 172 ---------------- .../X64/cmockaFuncTemplateMsvc.nasm | 192 ------------------ .../OsServiceLibHost/OsServiceLibGcc.c | 46 ----- .../OsServiceLibHost/OsServiceLibHost.inf | 26 --- .../OsServiceLibHost/OsServiceLibMsvc.c | 41 ---- .../HostCRT/OsServiceLibHost/WinNTInclude.h | 74 ------- .../UnitTestFrameworkPkg.ci.yaml | 1 - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 4 - 14 files changed, 948 deletions(-) delete mode 100644 UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h delete mode 100644 UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm delete mode 100644 UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm delete mode 100644 UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm delete mode 100644 UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm delete mode 100644 UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c delete mode 100644 UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf delete mode 100644 UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c delete mode 100644 UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index caad0b62e87..34b24bf5ca0 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -27,7 +27,6 @@ SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf [LibraryClasses.common.HOST_APPLICATION] - OsServiceLib|UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf CmockaLib|UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf UnitTestLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h b/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h deleted file mode 100644 index 7672c09d8d3..00000000000 --- a/UnitTestFrameworkPkg/FrameworkInclude/Library/OsServiceLib.h +++ /dev/null @@ -1,24 +0,0 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#ifndef _OS_SERVICE_LIB_H_ -#define _OS_SERVICE_LIB_H_ - -#include - -VOID * -AllocateExecutableMemory ( - IN UINTN Size - ); - -VOID -FreeExecutableMemory ( - IN VOID *Buffer, - IN UINTN Size - ); - -#endif diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm deleted file mode 100644 index 70c0aeae0db..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateGcc.nasm +++ /dev/null @@ -1,165 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2019, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;------------------------------------------------------------------------------ - -SECTION .text - -; This must be aligned to MY_UNIT_TEST_SUITE -%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (4 * 5) -%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (4 * 6) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (4 * 9) - -; This must be aligned to MY_UNIT_TEST -%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (4 * 6) -%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (4 * 7) -%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (4 * 8) -%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (4 * 9) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (4 * 11) - -;------------------------------------------------------------------------------ -; int GroupSetupTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupSetupTemplate) -ASM_PFX(GroupSetupTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] - test eax, eax - jz GroupSetupDone - push ecx - call eax - add esp, 4 -GroupSetupDone: - - pop ebx - xor eax, eax - ret - -global ASM_PFX(mGroupSetupTemplateSize) -ASM_PFX(mGroupSetupTemplateSize) DD $ - ASM_PFX(GroupSetupTemplate) - -;------------------------------------------------------------------------------ -; int GroupTeardownTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupTeardownTemplate) -ASM_PFX(GroupTeardownTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] - test eax, eax - jz GroupTeardownDone - push ecx - call eax - add esp, 4 -GroupTeardownDone: - - pop ebx - xor eax, eax - ret - -global ASM_PFX(mGroupTeardownTemplateSize) -ASM_PFX(mGroupTeardownTemplateSize) DD $ - ASM_PFX(GroupTeardownTemplate) - -;------------------------------------------------------------------------------ -; void TestFuncTemplate (void); -;------------------------------------------------------------------------------ -global ASM_PFX(TestFuncTemplate) -ASM_PFX(TestFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] - test eax, eax - jz DeadLoop - push edx - push ecx - call eax - add esp, 8 - - pop ebx - ret - -DeadLoop: - jmp $ - ret -global ASM_PFX(mTestFuncTemplateSize) -ASM_PFX(mTestFuncTemplateSize) DD $ - ASM_PFX(TestFuncTemplate) - -;------------------------------------------------------------------------------ -; int SetupFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(SetupFuncTemplate) -ASM_PFX(SetupFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] - test eax, eax - jz SetupDone - push edx - push ecx - call eax - add esp, 8 -SetupDone: - - pop ebx - ret -global ASM_PFX(mSetupFuncTemplateSize) -ASM_PFX(mSetupFuncTemplateSize) DD $ - ASM_PFX(SetupFuncTemplate) - -;------------------------------------------------------------------------------ -; int TeardownFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(TeardownFuncTemplate) -ASM_PFX(TeardownFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] - test eax, eax - jz TeardownDone - push edx - push ecx - call eax - add esp, 8 -TeardownDone: - - pop ebx - xor eax, eax - ret -global ASM_PFX(mTeardownFuncTemplateSize) -ASM_PFX(mTeardownFuncTemplateSize) DD $ - ASM_PFX(TeardownFuncTemplate) - diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm deleted file mode 100644 index 70c0aeae0db..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/IA32/cmockaFuncTemplateMsvc.nasm +++ /dev/null @@ -1,165 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2019, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;------------------------------------------------------------------------------ - -SECTION .text - -; This must be aligned to MY_UNIT_TEST_SUITE -%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (4 * 5) -%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (4 * 6) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (4 * 9) - -; This must be aligned to MY_UNIT_TEST -%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (4 * 6) -%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (4 * 7) -%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (4 * 8) -%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (4 * 9) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (4 * 11) - -;------------------------------------------------------------------------------ -; int GroupSetupTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupSetupTemplate) -ASM_PFX(GroupSetupTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] - test eax, eax - jz GroupSetupDone - push ecx - call eax - add esp, 4 -GroupSetupDone: - - pop ebx - xor eax, eax - ret - -global ASM_PFX(mGroupSetupTemplateSize) -ASM_PFX(mGroupSetupTemplateSize) DD $ - ASM_PFX(GroupSetupTemplate) - -;------------------------------------------------------------------------------ -; int GroupTeardownTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupTeardownTemplate) -ASM_PFX(GroupTeardownTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] - test eax, eax - jz GroupTeardownDone - push ecx - call eax - add esp, 4 -GroupTeardownDone: - - pop ebx - xor eax, eax - ret - -global ASM_PFX(mGroupTeardownTemplateSize) -ASM_PFX(mGroupTeardownTemplateSize) DD $ - ASM_PFX(GroupTeardownTemplate) - -;------------------------------------------------------------------------------ -; void TestFuncTemplate (void); -;------------------------------------------------------------------------------ -global ASM_PFX(TestFuncTemplate) -ASM_PFX(TestFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] - test eax, eax - jz DeadLoop - push edx - push ecx - call eax - add esp, 8 - - pop ebx - ret - -DeadLoop: - jmp $ - ret -global ASM_PFX(mTestFuncTemplateSize) -ASM_PFX(mTestFuncTemplateSize) DD $ - ASM_PFX(TestFuncTemplate) - -;------------------------------------------------------------------------------ -; int SetupFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(SetupFuncTemplate) -ASM_PFX(SetupFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] - test eax, eax - jz SetupDone - push edx - push ecx - call eax - add esp, 8 -SetupDone: - - pop ebx - ret -global ASM_PFX(mSetupFuncTemplateSize) -ASM_PFX(mSetupFuncTemplateSize) DD $ - ASM_PFX(SetupFuncTemplate) - -;------------------------------------------------------------------------------ -; int TeardownFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(TeardownFuncTemplate) -ASM_PFX(TeardownFuncTemplate): - ; mov eax, - DB 0xB8 - DD 0x0 ; to be patched - push ebx - mov ebx, eax - - ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov ecx, [ebx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov edx, [ebx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov eax, [ebx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] - test eax, eax - jz TeardownDone - push edx - push ecx - call eax - add esp, 8 -TeardownDone: - - pop ebx - xor eax, eax - ret -global ASM_PFX(mTeardownFuncTemplateSize) -ASM_PFX(mTeardownFuncTemplateSize) DD $ - ASM_PFX(TeardownFuncTemplate) - diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c index 1e241dfe439..80d3f87d072 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c @@ -17,7 +17,6 @@ #include #include #include -#include #include #include @@ -299,16 +298,6 @@ CreateUnitTestSuite ( goto Exit; } - NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mGroupSetupTemplateSize); - ASSERT(NewSuiteEntry->UTS.GroupSetup != NULL); - CopyMem ((VOID *)(UINTN)NewSuiteEntry->UTS.GroupSetup, (VOID *)(UINTN)GroupSetupTemplate, mGroupSetupTemplateSize); - *(UINTN *)((UINTN)NewSuiteEntry->UTS.GroupSetup + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewSuiteEntry->UTS; - - NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mGroupTeardownTemplateSize); - ASSERT(NewSuiteEntry->UTS.GroupTeardown != NULL); - CopyMem ((VOID *)(UINTN)NewSuiteEntry->UTS.GroupTeardown, (VOID *)(UINTN)GroupTeardownTemplate, mGroupTeardownTemplateSize); - *(UINTN *)((UINTN)NewSuiteEntry->UTS.GroupTeardown + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewSuiteEntry->UTS; - NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)Sup; NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)Tdn; @@ -382,21 +371,6 @@ AddTestCase ( goto Exit; } - NewTestEntry->UT.TestFunc = (CMUnitTestFunction)(UINTN)AllocateExecutableMemory (mTestFuncTemplateSize); - ASSERT(NewTestEntry->UT.TestFunc != NULL); - CopyMem ((VOID *)(UINTN)NewTestEntry->UT.TestFunc, (VOID *)(UINTN)TestFuncTemplate, mTestFuncTemplateSize); - *(UINTN *)((UINTN)NewTestEntry->UT.TestFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; - - NewTestEntry->UT.SetupFunc = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mSetupFuncTemplateSize); - ASSERT(NewTestEntry->UT.SetupFunc != NULL); - CopyMem ((VOID *)(UINTN)NewTestEntry->UT.SetupFunc, (VOID *)(UINTN)SetupFuncTemplate, mSetupFuncTemplateSize); - *(UINTN *)((UINTN)NewTestEntry->UT.SetupFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; - - NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)(UINTN)AllocateExecutableMemory (mTeardownFuncTemplateSize); - ASSERT(NewTestEntry->UT.TeardownFunc != NULL); - CopyMem ((VOID *)(UINTN)NewTestEntry->UT.TeardownFunc, (VOID *)(UINTN)TeardownFuncTemplate, mTeardownFuncTemplateSize); - *(UINTN *)((UINTN)NewTestEntry->UT.TeardownFunc + sizeof(UINTN)/sizeof(UINT32)) = (UINTN)&NewTestEntry->UT; - NewTestEntry->UT.TestFunc = (CMUnitTestFunction)Func; NewTestEntry->UT.SetupFunc = (CMFixtureFunction)PreReq; NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)CleanUp; diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf index aabe64232fe..9b76efebaa9 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf @@ -16,7 +16,6 @@ [LibraryClasses] BaseLib MemoryAllocationLib - OsServiceLib CmockaLib [Packages] @@ -25,13 +24,3 @@ [Sources] UnitTestLib.c - -[Sources.Ia32] - IA32/cmockaFuncTemplateMsvc.nasm | MSFT - IA32/cmockaFuncTemplateGcc.nasm | GCC - -[Sources.X64] - X64/cmockaFuncTemplateMsvc.nasm | MSFT - X64/cmockaFuncTemplateGcc.nasm | GCC - -[Pcd] diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm deleted file mode 100644 index 3bd81c13fbf..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateGcc.nasm +++ /dev/null @@ -1,172 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2019, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;------------------------------------------------------------------------------ - -SECTION .text - -; This must be aligned to MY_UNIT_TEST_SUITE -%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (8 * 5) -%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (8 * 6) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (8 * 9) - -; This must be aligned to MY_UNIT_TEST -%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (8 * 6) -%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (8 * 7) -%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (8 * 8) -%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (8 * 9) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (8 * 11) - -;------------------------------------------------------------------------------ -; int GroupSetupTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupSetupTemplate) -ASM_PFX(GroupSetupTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) - mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] - test rax, rax - jz GroupSetupDone - push rbx - push rbp - call rax - pop rbp - pop rbx -GroupSetupDone: - - pop rbx - xor rax, rax - ret - -global ASM_PFX(mGroupSetupTemplateSize) -ASM_PFX(mGroupSetupTemplateSize) DQ $ - ASM_PFX(GroupSetupTemplate) - -;------------------------------------------------------------------------------ -; int GroupTeardownTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupTeardownTemplate) -ASM_PFX(GroupTeardownTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) - mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] - test rax, rax - jz GroupTeardownDone - push rbx - push rbp - call rax - pop rbp - pop rbx -GroupTeardownDone: - - pop rbx - xor rax, rax - ret - -global ASM_PFX(mGroupTeardownTemplateSize) -ASM_PFX(mGroupTeardownTemplateSize) DQ $ - ASM_PFX(GroupTeardownTemplate) - -;------------------------------------------------------------------------------ -; void TestFuncTemplate (void); -;------------------------------------------------------------------------------ -global ASM_PFX(TestFuncTemplate) -ASM_PFX(TestFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] - test rax, rax - jz DeadLoop - push rbx - push rbp - call rax - pop rbp - pop rbx - - pop rbx - ret - -DeadLoop: - jmp $ - ret -global ASM_PFX(mTestFuncTemplateSize) -ASM_PFX(mTestFuncTemplateSize) DQ $ - ASM_PFX(TestFuncTemplate) - -;------------------------------------------------------------------------------ -; int SetupFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(SetupFuncTemplate) -ASM_PFX(SetupFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] - test rax, rax - jz SetupDone - push rbx - push rbp - call rax - pop rbp - pop rbx -SetupDone: - - pop rbx - ret -global ASM_PFX(mSetupFuncTemplateSize) -ASM_PFX(mSetupFuncTemplateSize) DQ $ - ASM_PFX(SetupFuncTemplate) - -;------------------------------------------------------------------------------ -; int TeardownFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(TeardownFuncTemplate) -ASM_PFX(TeardownFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rdi, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rsi, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] - test rax, rax - jz TeardownDone - push rbx - push rbp - call rax - pop rbp - pop rbx -TeardownDone: - - pop rbx - xor rax, rax - ret -global ASM_PFX(mTeardownFuncTemplateSize) -ASM_PFX(mTeardownFuncTemplateSize) DQ $ - ASM_PFX(TeardownFuncTemplate) - diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm b/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm deleted file mode 100644 index 2d40a9d3f18..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/X64/cmockaFuncTemplateMsvc.nasm +++ /dev/null @@ -1,192 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2019, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;------------------------------------------------------------------------------ - -SECTION .text - -; This must be aligned to MY_UNIT_TEST_SUITE -%define OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE (8 * 5) -%define OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE (8 * 6) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE (8 * 9) - -; This must be aligned to MY_UNIT_TEST -%define OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST (8 * 6) -%define OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST (8 * 7) -%define OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST (8 * 8) -%define OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST (8 * 9) -%define OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST (8 * 11) - -;------------------------------------------------------------------------------ -; int GroupSetupTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupSetupTemplate) -ASM_PFX(GroupSetupTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_SUITE_SETUP(UNIT_TEST_FRAMEWORK_HANDLE) - mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_SETUP_IN_MY_UNIT_TEST_SUITE] - test rax, rax - jz GroupSetupDone - push rbx - push rbp - push rsi - push rdi - call rax - pop rdi - pop rsi - pop rbp - pop rbx -GroupSetupDone: - - pop rbx - xor rax, rax - ret - -global ASM_PFX(mGroupSetupTemplateSize) -ASM_PFX(mGroupSetupTemplateSize) DQ $ - ASM_PFX(GroupSetupTemplate) - -;------------------------------------------------------------------------------ -; int GroupTeardownTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(GroupTeardownTemplate) -ASM_PFX(GroupTeardownTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_SUITE_TEARDOWN(UNIT_TEST_FRAMEWORK_HANDLE) - mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST_SUITE] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_SUITE_TEARDOWN_IN_MY_UNIT_TEST_SUITE] - test rax, rax - jz GroupTeardownDone - push rbx - push rbp - push rsi - push rdi - call rax - pop rdi - pop rsi - pop rbp - pop rbx -GroupTeardownDone: - - pop rbx - xor rax, rax - ret - -global ASM_PFX(mGroupTeardownTemplateSize) -ASM_PFX(mGroupTeardownTemplateSize) DQ $ - ASM_PFX(GroupTeardownTemplate) - -;------------------------------------------------------------------------------ -; void TestFuncTemplate (void); -;------------------------------------------------------------------------------ -global ASM_PFX(TestFuncTemplate) -ASM_PFX(TestFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_FUNCTION(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_FUNCTION_IN_MY_UNIT_TEST] - test rax, rax - jz DeadLoop - push rbx - push rbp - push rsi - push rdi - call rax - pop rdi - pop rsi - pop rbp - pop rbx - - pop rbx - ret - -DeadLoop: - jmp $ - ret -global ASM_PFX(mTestFuncTemplateSize) -ASM_PFX(mTestFuncTemplateSize) DQ $ - ASM_PFX(TestFuncTemplate) - -;------------------------------------------------------------------------------ -; int SetupFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(SetupFuncTemplate) -ASM_PFX(SetupFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_PREREQ(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_PREREQ_IN_MY_UNIT_TEST] - test rax, rax - jz SetupDone - push rbx - push rbp - push rsi - push rdi - call rax - pop rdi - pop rsi - pop rbp - pop rbx -SetupDone: - - pop rbx - ret -global ASM_PFX(mSetupFuncTemplateSize) -ASM_PFX(mSetupFuncTemplateSize) DQ $ - ASM_PFX(SetupFuncTemplate) - -;------------------------------------------------------------------------------ -; int TeardownFuncTemplate (void **state); -;------------------------------------------------------------------------------ -global ASM_PFX(TeardownFuncTemplate) -ASM_PFX(TeardownFuncTemplate): - ; mov rax, - DB 0x48, 0xB8 - DQ 0x0 ; to be patched - push rbx - mov rbx, rax - - ; call UNIT_TEST_CLEANUP(UNIT_TEST_FRAMEWORK_HANDLE, UNIT_TEST_CONTEXT) - mov rcx, [rbx + OFFSET_OF_UNIT_TEST_FRAMEWORK_HANDLE_IN_MY_UNIT_TEST] - mov rdx, [rbx + OFFSET_OF_UNIT_TEST_CONTEXT_IN_MY_UNIT_TEST] - mov rax, [rbx + OFFSET_OF_UNIT_TEST_CLEANUP_IN_MY_UNIT_TEST] - test rax, rax - jz TeardownDone - push rbx - push rbp - push rsi - push rdi - call rax - pop rdi - pop rsi - pop rbp - pop rbx -TeardownDone: - - pop rbx - xor rax, rax - ret -global ASM_PFX(mTeardownFuncTemplateSize) -ASM_PFX(mTeardownFuncTemplateSize) DQ $ - ASM_PFX(TeardownFuncTemplate) - diff --git a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c deleted file mode 100644 index a10bed71542..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibGcc.c +++ /dev/null @@ -1,46 +0,0 @@ -/**@file - -Copyright (c) 2019, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -VOID * -AllocateExecutableMemory ( - IN UINTN Size - ) -{ - VOID *Buffer; - size_t FinalSize; - size_t PageSize; - - PageSize = getpagesize(); - - FinalSize = (Size + PageSize - 1) / PageSize * PageSize; - - Buffer = mmap(NULL, FinalSize, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_ANONYMOUS | MAP_PRIVATE, 0, 0); - if (Buffer == NULL) { - return NULL; - } - - return Buffer; -} - -VOID -FreeExecutableMemory ( - IN VOID *Buffer, - IN UINTN Size - ) -{ - size_t FinalSize; - size_t PageSize; - - PageSize = getpagesize(); - - FinalSize = (Size + PageSize - 1) / PageSize * PageSize; - - munmap (Buffer, FinalSize); -} diff --git a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf deleted file mode 100644 index 4ae9805703e..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf +++ /dev/null @@ -1,26 +0,0 @@ -## @file -# -# Copyright (c) 2017, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = OsServiceLibHost - FILE_GUID = 56DCD496-CD73-42D0-B145-B7C100CE5877 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = OsServiceLib - -[Sources] - OsServiceLibMsvc.c | MSFT - OsServiceLibGcc.c | GCC - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - -[BuildOptions] - diff --git a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c deleted file mode 100644 index 843d4885788..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibMsvc.c +++ /dev/null @@ -1,41 +0,0 @@ -/**@file - -Copyright (c) 2019, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -VOID * -AllocateExecutableMemory ( - IN UINTN Size - ) -{ - VOID *Buffer; - SIZE_T FinalSize; - UINT32 PageSize; - SYSTEM_INFO SystemInfo; - - GetSystemInfo(&SystemInfo); - PageSize = SystemInfo.dwPageSize; - - FinalSize = (Size + PageSize - 1) / PageSize * PageSize; - - Buffer = VirtualAlloc(NULL, FinalSize, MEM_COMMIT, PAGE_EXECUTE_READWRITE); - if (Buffer == NULL) { - return NULL; - } - - return Buffer; -} - -VOID -FreeExecutableMemory ( - IN VOID *Buffer, - IN UINTN Size - ) -{ - VirtualFree(Buffer, 0, MEM_RELEASE); -} diff --git a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h b/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h deleted file mode 100644 index 10a7aaddcc7..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/WinNTInclude.h +++ /dev/null @@ -1,74 +0,0 @@ -/**@file - -Copyright (c) 2006 - 2014, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -Module Name: - WinNtLib.h - -Abstract: - Public include file for the WinNt Library - -**/ - -#ifndef __WIN_NT_INCLUDE_H__ -#define __WIN_NT_INCLUDE_H__ - -// -// Win32 include files do not compile clean with /W4, so we use the warning -// pragma to suppress the warnings for Win32 only. This way our code can stil -// compile at /W4 (highest warning level) with /WX (warnings cause build -// errors). -// -#pragma warning(disable : 4115) -#pragma warning(disable : 4201) -#pragma warning(disable : 4028) -#pragma warning(disable : 4133) - -#define GUID _WINNT_DUP_GUID_____ -#define _LIST_ENTRY _WINNT_DUP_LIST_ENTRY_FORWARD -#define LIST_ENTRY _WINNT_DUP_LIST_ENTRY -#if defined (MDE_CPU_IA32) && (_MSC_VER < 1800) -#define InterlockedIncrement _WINNT_DUP_InterlockedIncrement -#define InterlockedDecrement _WINNT_DUP_InterlockedDecrement -#define InterlockedCompareExchange64 _WINNT_DUP_InterlockedCompareExchange64 -#endif -#undef UNALIGNED -#undef CONST -#undef VOID -#undef DEBUG_EVENT - -// WQBugBug: This typedef is to make "windows.h" buildable. -// It should be removed after the root cause why -// size_t is undefined when go into the line below is found. -#if defined (MDE_CPU_IA32) -typedef UINT32 size_t ; -#endif - -#include "windows.h" - -#undef GUID -#undef _LIST_ENTRY -#undef LIST_ENTRY -#undef InterlockedIncrement -#undef InterlockedDecrement -#undef InterlockedCompareExchange64 -#undef InterlockedCompareExchangePointer -#undef CreateEventEx - -#define VOID void - -// -// Prevent collisions with Windows API name macros that deal with Unicode/Not issues -// -#undef LoadImage -#undef CreateEvent - -// -// Set the warnings back on as the EFI code must be /W4. -// -#pragma warning(default : 4115) -#pragma warning(default : 4201) - - -#endif diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index c62b7e205c2..610b4451d12 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,7 +30,6 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/Library/HostCRT/OsServiceLibHost/OsServiceLibHost.inf", "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf", "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf" diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index ae801ed60e0..bce20c977ca 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -30,10 +30,6 @@ # UnitTestResultReportLib|FrameworkInclude/Library/UnitTestResultReportLib.h - ## @libraryclass Provides memory allocation routines specific to host-based tests. - # - OsServiceLib|FrameworkInclude/Library/OsServiceLib.h - ## @libraryclass Provides boot-option routines useful in shell-based tests. # UnitTestBootLib|FrameworkInclude/Library/UnitTestBootLib.h From 76b4faefd0c765d0c66ae5628de2299ce0cd4cf2 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 17:33:46 -0800 Subject: [PATCH 241/384] MdePkg/Test: Remove BaseLibHost and BaseMemoryLibHost Signed-off-by: Michael D Kinney --- .../Test/HostLibrary/BaseLibHost/ARShiftU64.c | 44 - .../HostLibrary/BaseLibHost/BaseLibHost.inf | 79 - .../BaseLibHost/BaseLibHostNoAsm.inf | 75 - .../Test/HostLibrary/BaseLibHost/BitField.c | 1004 ----- MdePkg/Test/HostLibrary/BaseLibHost/Cache.c | 40 - .../Test/HostLibrary/BaseLibHost/CheckSum.c | 628 --- MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c | 95 - .../BaseLibHost/CpuBreakpointGcc.c | 26 - .../BaseLibHost/CpuBreakpointMsvc.c | 35 - .../HostLibrary/BaseLibHost/CpuDeadLoop.c | 32 - .../BaseLibHost/DivS64x64Remainder.c | 54 - .../Test/HostLibrary/BaseLibHost/DivU64x32.c | 45 - .../BaseLibHost/DivU64x32Remainder.c | 50 - .../BaseLibHost/DivU64x64Remainder.c | 50 - .../HostLibrary/BaseLibHost/DummyRdRand.c | 65 - .../HostLibrary/BaseLibHost/DummyReadTsc.c | 19 - .../HostLibrary/BaseLibHost/GetPowerOfTwo32.c | 37 - .../HostLibrary/BaseLibHost/GetPowerOfTwo64.c | 37 - .../HostLibrary/BaseLibHost/HighBitSet32.c | 40 - .../HostLibrary/BaseLibHost/HighBitSet64.c | 47 - .../HostLibrary/BaseLibHost/Ia32/RdRand.nasm | 84 - .../HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm | 31 - MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c | 38 - MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c | 45 - .../Test/HostLibrary/BaseLibHost/LShiftU64.c | 44 - MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c | 10 - .../Test/HostLibrary/BaseLibHost/LinkedList.c | 536 --- .../Test/HostLibrary/BaseLibHost/LongJump.c | 46 - .../HostLibrary/BaseLibHost/LowBitSet32.c | 40 - .../HostLibrary/BaseLibHost/LowBitSet64.c | 43 - MdePkg/Test/HostLibrary/BaseLibHost/Math64.c | 364 -- .../Test/HostLibrary/BaseLibHost/ModU64x32.c | 45 - .../Test/HostLibrary/BaseLibHost/MultS64x64.c | 35 - .../Test/HostLibrary/BaseLibHost/MultU64x32.c | 46 - .../Test/HostLibrary/BaseLibHost/MultU64x64.c | 46 - MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c | 38 - MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c | 45 - .../Test/HostLibrary/BaseLibHost/RShiftU64.c | 44 - .../Test/HostLibrary/BaseLibHost/SafeString.c | 3693 ----------------- MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c | 54 - MdePkg/Test/HostLibrary/BaseLibHost/String.c | 1163 ------ .../HostLibrary/BaseLibHost/SwapBytes16.c | 31 - .../HostLibrary/BaseLibHost/SwapBytes32.c | 37 - .../HostLibrary/BaseLibHost/SwapBytes64.c | 37 - .../HostLibrary/BaseLibHost/SwitchStackNull.c | 52 - .../Test/HostLibrary/BaseLibHost/Unaligned.c | 216 - .../HostLibrary/BaseLibHost/X64/RdRand.nasm | 77 - .../HostLibrary/BaseLibHost/X64/ReadTsc.nasm | 34 - MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c | 180 - .../BaseLibHost/X86DisablePaging64Null.c | 53 - MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c | 170 - .../HostLibrary/BaseLibHost/X86GdtrNull.c | 50 - .../HostLibrary/BaseLibHost/X86IdtrNull.c | 50 - .../BaseLibHost/X86MemoryFenceGcc.c | 29 - .../BaseLibHost/X86MemoryFenceMsvc.c | 27 - .../BaseLibHost/X86PatchInstruction.c | 84 - .../Test/HostLibrary/BaseLibHost/X86RdRand.c | 121 - .../HostLibrary/BaseLibHost/X86SegmentNull.c | 163 - .../BaseMemoryLibHost/BaseMemoryLibHost.c | 160 - .../BaseMemoryLibHost/BaseMemoryLibHost.inf | 24 - 60 files changed, 10587 deletions(-) delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/BitField.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Cache.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Math64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/String.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c delete mode 100644 MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c delete mode 100644 MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c delete mode 100644 MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c deleted file mode 100644 index 82aa010ea76..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/ARShiftU64.c +++ /dev/null @@ -1,44 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathARShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ); - -/** - Shifts a 64-bit integer right between 0 and 63 bits. The high bits are filled - with the original integer's bit 63. The shifted value is returned. - - This function shifts the 64-bit value Operand to the right by Count bits. The - high Count bits are set to bit 63 of Operand. The shifted value is returned. - - If Count is greater than 63, then ASSERT(). - - @param Operand The 64-bit operand to shift right. - @param Count The number of bits to shift right. - - @return Operand >> Count - -**/ -UINT64 -EFIAPI -ARShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 64); - return InternalMathARShiftU64 (Operand, Count); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf b/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf deleted file mode 100644 index 405d1ddab06..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHost.inf +++ /dev/null @@ -1,79 +0,0 @@ -## @file -# -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseLibHost - FILE_GUID = FA4A8DE0-8D55-44AA-8368-07D24BDA6A7D - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = BaseLib | HOST_APPLICATION - -[Sources] - Math64.c - RShiftU64.c - LShiftU64.c - ARShiftU64.c - MultU64x64.c - MultS64x64.c - MultU64x32.c - DivS64x64Remainder.c - DivU64x64Remainder.c - DivU64x32Remainder.c - DivU64x32.c - ModU64x32.c - SwapBytes16.c - SwapBytes32.c - SwapBytes64.c - BitField.c - GetPowerOfTwo32.c - GetPowerOfTwo64.c - HighBitSet32.c - HighBitSet64.c - LowBitSet32.c - LowBitSet64.c - LRotU32.c - LRotU64.c - RRotU32.c - RRotU64.c - SafeString.c - String.c - CheckSum.c - CpuDeadLoop.c - LinkedList.c - Unaligned.c - SetJump.c - LongJump.c - X86MemoryFenceMsvc.c | MSFT - X86MemoryFenceGcc.c | GCC - CpuBreakpointMsvc.c | MSFT - CpuBreakpointGcc.c | GCC - Cpu.c - Cache.c - X86Cr.c - X86Dr.c - X86RdRand.c - X86PatchInstruction.c - X86GdtrNull.c - X86IdtrNull.c - X86SegmentNull.c - X86DisablePaging64Null.c - SwitchStackNull.c - -[Sources.Ia32] - Ia32/RdRand.nasm - Ia32/ReadTsc.nasm - -[Sources.X64] - X64/RdRand.nasm - X64/ReadTsc.nasm - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseMemoryLib diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf b/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf deleted file mode 100644 index 9de6c389c9b..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/BaseLibHostNoAsm.inf +++ /dev/null @@ -1,75 +0,0 @@ -## @file -# -# this is a special build to pass KLEE build, because KLEE cannot use ASM. -# -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseLibHostNoAsm - FILE_GUID = 6DF0F6CC-DF9E-4644-8C1F-5A239B598E28 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = BaseLib | HOST_APPLICATION - -[Sources] - Math64.c - RShiftU64.c - LShiftU64.c - ARShiftU64.c - MultU64x64.c - MultS64x64.c - MultU64x32.c - DivS64x64Remainder.c - DivU64x64Remainder.c - DivU64x32Remainder.c - DivU64x32.c - ModU64x32.c - SwapBytes16.c - SwapBytes32.c - SwapBytes64.c - BitField.c - GetPowerOfTwo32.c - GetPowerOfTwo64.c - HighBitSet32.c - HighBitSet64.c - LowBitSet32.c - LowBitSet64.c - LRotU32.c - LRotU64.c - RRotU32.c - RRotU64.c - SafeString.c - String.c - CheckSum.c - CpuDeadLoop.c - LinkedList.c - Unaligned.c - SetJump.c - LongJump.c - X86MemoryFenceMsvc.c | MSFT - X86MemoryFenceGcc.c | GCC - CpuBreakpointMsvc.c | MSFT - CpuBreakpointGcc.c | GCC - Cpu.c - Cache.c - X86Cr.c - X86Dr.c - X86RdRand.c - X86PatchInstruction.c - X86GdtrNull.c - X86IdtrNull.c - X86SegmentNull.c - X86DisablePaging64Null.c - SwitchStackNull.c - DummyRdRand.c - DummyReadTsc.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseMemoryLib diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/BitField.c b/MdePkg/Test/HostLibrary/BaseLibHost/BitField.c deleted file mode 100644 index 8d044e0e742..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/BitField.c +++ /dev/null @@ -1,1004 +0,0 @@ -/** @file - Bit field functions of BaseLib. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Worker function that returns a bit field from Operand. - - Returns the bitfield specified by the StartBit and the EndBit from Operand. - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - @param EndBit The ordinal of the most significant bit in the bit field. - - @return The bit field read. - -**/ -UINTN -EFIAPI -InternalBaseLibBitFieldReadUint ( - IN UINTN Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - // - // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] - // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. - // - return (Operand & ~((UINTN)-2 << EndBit)) >> StartBit; -} - -/** - Worker function that reads a bit field from Operand, performs a bitwise OR, - and returns the result. - - Performs a bitwise OR between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new value is returned. - - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - @param EndBit The ordinal of the most significant bit in the bit field. - @param OrData The value to OR with the read value from the value. - - @return The new value. - -**/ -UINTN -EFIAPI -InternalBaseLibBitFieldOrUint ( - IN UINTN Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINTN OrData - ) -{ - // - // Higher bits in OrData those are not used must be zero. - // - // EndBit - StartBit + 1 might be 32 while the result right shifting 32 on a 32bit integer is undefined, - // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. - // - ASSERT ((OrData >> (EndBit - StartBit)) == ((OrData >> (EndBit - StartBit)) & 1)); - - // - // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] - // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. - // - return Operand | ((OrData << StartBit) & ~((UINTN) -2 << EndBit)); -} - -/** - Worker function that reads a bit field from Operand, performs a bitwise AND, - and returns the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new value is returned. - - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - @param EndBit The ordinal of the most significant bit in the bit field. - @param AndData The value to And with the read value from the value. - - @return The new value. - -**/ -UINTN -EFIAPI -InternalBaseLibBitFieldAndUint ( - IN UINTN Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINTN AndData - ) -{ - // - // Higher bits in AndData those are not used must be zero. - // - // EndBit - StartBit + 1 might be 32 while the result right shifting 32 on a 32bit integer is undefined, - // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. - // - ASSERT ((AndData >> (EndBit - StartBit)) == ((AndData >> (EndBit - StartBit)) & 1)); - - // - // ~((UINTN)-2 << EndBit) is a mask in which bit[0] thru bit[EndBit] - // are 1's while bit[EndBit + 1] thru the most significant bit are 0's. - // - return Operand & ~((~AndData << StartBit) & ~((UINTN)-2 << EndBit)); -} - -/** - Returns a bit field from an 8-bit value. - - Returns the bitfield specified by the StartBit and the EndBit from Operand. - - If 8-bit operations are not supported, then ASSERT(). - If StartBit is greater than 7, then ASSERT(). - If EndBit is greater than 7, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..7. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..7. - - @return The bit field read. - -**/ -UINT8 -EFIAPI -BitFieldRead8 ( - IN UINT8 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - ASSERT (EndBit < 8); - ASSERT (StartBit <= EndBit); - return (UINT8)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); -} - -/** - Writes a bit field to an 8-bit value, and returns the result. - - Writes Value to the bit field specified by the StartBit and the EndBit in - Operand. All other bits in Operand are preserved. The new 8-bit value is - returned. - - If 8-bit operations are not supported, then ASSERT(). - If StartBit is greater than 7, then ASSERT(). - If EndBit is greater than 7, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..7. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..7. - @param Value The new value of the bit field. - - @return The new 8-bit value. - -**/ -UINT8 -EFIAPI -BitFieldWrite8 ( - IN UINT8 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT8 Value - ) -{ - ASSERT (EndBit < 8); - ASSERT (StartBit <= EndBit); - return BitFieldAndThenOr8 (Operand, StartBit, EndBit, 0, Value); -} - -/** - Reads a bit field from an 8-bit value, performs a bitwise OR, and returns the - result. - - Performs a bitwise OR between the bit field specified by StartBit - and EndBit in Operand and the value specified by OrData. All other bits in - Operand are preserved. The new 8-bit value is returned. - - If 8-bit operations are not supported, then ASSERT(). - If StartBit is greater than 7, then ASSERT(). - If EndBit is greater than 7, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..7. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..7. - @param OrData The value to OR with the read value from the value. - - @return The new 8-bit value. - -**/ -UINT8 -EFIAPI -BitFieldOr8 ( - IN UINT8 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT8 OrData - ) -{ - ASSERT (EndBit < 8); - ASSERT (StartBit <= EndBit); - return (UINT8)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); -} - -/** - Reads a bit field from an 8-bit value, performs a bitwise AND, and returns - the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new 8-bit value is returned. - - If 8-bit operations are not supported, then ASSERT(). - If StartBit is greater than 7, then ASSERT(). - If EndBit is greater than 7, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..7. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..7. - @param AndData The value to AND with the read value from the value. - - @return The new 8-bit value. - -**/ -UINT8 -EFIAPI -BitFieldAnd8 ( - IN UINT8 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT8 AndData - ) -{ - ASSERT (EndBit < 8); - ASSERT (StartBit <= EndBit); - return (UINT8)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); -} - -/** - Reads a bit field from an 8-bit value, performs a bitwise AND followed by a - bitwise OR, and returns the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData, followed by a bitwise - OR with value specified by OrData. All other bits in Operand are - preserved. The new 8-bit value is returned. - - If 8-bit operations are not supported, then ASSERT(). - If StartBit is greater than 7, then ASSERT(). - If EndBit is greater than 7, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..7. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..7. - @param AndData The value to AND with the read value from the value. - @param OrData The value to OR with the result of the AND operation. - - @return The new 8-bit value. - -**/ -UINT8 -EFIAPI -BitFieldAndThenOr8 ( - IN UINT8 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT8 AndData, - IN UINT8 OrData - ) -{ - ASSERT (EndBit < 8); - ASSERT (StartBit <= EndBit); - return BitFieldOr8 ( - BitFieldAnd8 (Operand, StartBit, EndBit, AndData), - StartBit, - EndBit, - OrData - ); -} - -/** - Returns a bit field from a 16-bit value. - - Returns the bitfield specified by the StartBit and the EndBit from Operand. - - If 16-bit operations are not supported, then ASSERT(). - If StartBit is greater than 15, then ASSERT(). - If EndBit is greater than 15, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..15. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..15. - - @return The bit field read. - -**/ -UINT16 -EFIAPI -BitFieldRead16 ( - IN UINT16 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - ASSERT (EndBit < 16); - ASSERT (StartBit <= EndBit); - return (UINT16)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); -} - -/** - Writes a bit field to a 16-bit value, and returns the result. - - Writes Value to the bit field specified by the StartBit and the EndBit in - Operand. All other bits in Operand are preserved. The new 16-bit value is - returned. - - If 16-bit operations are not supported, then ASSERT(). - If StartBit is greater than 15, then ASSERT(). - If EndBit is greater than 15, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..15. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..15. - @param Value The new value of the bit field. - - @return The new 16-bit value. - -**/ -UINT16 -EFIAPI -BitFieldWrite16 ( - IN UINT16 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT16 Value - ) -{ - ASSERT (EndBit < 16); - ASSERT (StartBit <= EndBit); - return BitFieldAndThenOr16 (Operand, StartBit, EndBit, 0, Value); -} - -/** - Reads a bit field from a 16-bit value, performs a bitwise OR, and returns the - result. - - Performs a bitwise OR between the bit field specified by StartBit - and EndBit in Operand and the value specified by OrData. All other bits in - Operand are preserved. The new 16-bit value is returned. - - If 16-bit operations are not supported, then ASSERT(). - If StartBit is greater than 15, then ASSERT(). - If EndBit is greater than 15, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..15. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..15. - @param OrData The value to OR with the read value from the value. - - @return The new 16-bit value. - -**/ -UINT16 -EFIAPI -BitFieldOr16 ( - IN UINT16 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT16 OrData - ) -{ - ASSERT (EndBit < 16); - ASSERT (StartBit <= EndBit); - return (UINT16)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); -} - -/** - Reads a bit field from a 16-bit value, performs a bitwise AND, and returns - the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new 16-bit value is returned. - - If 16-bit operations are not supported, then ASSERT(). - If StartBit is greater than 15, then ASSERT(). - If EndBit is greater than 15, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..15. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..15. - @param AndData The value to AND with the read value from the value. - - @return The new 16-bit value. - -**/ -UINT16 -EFIAPI -BitFieldAnd16 ( - IN UINT16 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT16 AndData - ) -{ - ASSERT (EndBit < 16); - ASSERT (StartBit <= EndBit); - return (UINT16)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); -} - -/** - Reads a bit field from a 16-bit value, performs a bitwise AND followed by a - bitwise OR, and returns the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData, followed by a bitwise - OR with value specified by OrData. All other bits in Operand are - preserved. The new 16-bit value is returned. - - If 16-bit operations are not supported, then ASSERT(). - If StartBit is greater than 15, then ASSERT(). - If EndBit is greater than 15, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..15. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..15. - @param AndData The value to AND with the read value from the value. - @param OrData The value to OR with the result of the AND operation. - - @return The new 16-bit value. - -**/ -UINT16 -EFIAPI -BitFieldAndThenOr16 ( - IN UINT16 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT16 AndData, - IN UINT16 OrData - ) -{ - ASSERT (EndBit < 16); - ASSERT (StartBit <= EndBit); - return BitFieldOr16 ( - BitFieldAnd16 (Operand, StartBit, EndBit, AndData), - StartBit, - EndBit, - OrData - ); -} - -/** - Returns a bit field from a 32-bit value. - - Returns the bitfield specified by the StartBit and the EndBit from Operand. - - If 32-bit operations are not supported, then ASSERT(). - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - - @return The bit field read. - -**/ -UINT32 -EFIAPI -BitFieldRead32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - return (UINT32)InternalBaseLibBitFieldReadUint (Operand, StartBit, EndBit); -} - -/** - Writes a bit field to a 32-bit value, and returns the result. - - Writes Value to the bit field specified by the StartBit and the EndBit in - Operand. All other bits in Operand are preserved. The new 32-bit value is - returned. - - If 32-bit operations are not supported, then ASSERT(). - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - @param Value The new value of the bit field. - - @return The new 32-bit value. - -**/ -UINT32 -EFIAPI -BitFieldWrite32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT32 Value - ) -{ - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - return BitFieldAndThenOr32 (Operand, StartBit, EndBit, 0, Value); -} - -/** - Reads a bit field from a 32-bit value, performs a bitwise OR, and returns the - result. - - Performs a bitwise OR between the bit field specified by StartBit - and EndBit in Operand and the value specified by OrData. All other bits in - Operand are preserved. The new 32-bit value is returned. - - If 32-bit operations are not supported, then ASSERT(). - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - @param OrData The value to OR with the read value from the value. - - @return The new 32-bit value. - -**/ -UINT32 -EFIAPI -BitFieldOr32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT32 OrData - ) -{ - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - return (UINT32)InternalBaseLibBitFieldOrUint (Operand, StartBit, EndBit, OrData); -} - -/** - Reads a bit field from a 32-bit value, performs a bitwise AND, and returns - the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new 32-bit value is returned. - - If 32-bit operations are not supported, then ASSERT(). - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - @param AndData The value to AND with the read value from the value. - - @return The new 32-bit value. - -**/ -UINT32 -EFIAPI -BitFieldAnd32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT32 AndData - ) -{ - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - return (UINT32)InternalBaseLibBitFieldAndUint (Operand, StartBit, EndBit, AndData); -} - -/** - Reads a bit field from a 32-bit value, performs a bitwise AND followed by a - bitwise OR, and returns the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData, followed by a bitwise - OR with value specified by OrData. All other bits in Operand are - preserved. The new 32-bit value is returned. - - If 32-bit operations are not supported, then ASSERT(). - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - @param AndData The value to AND with the read value from the value. - @param OrData The value to OR with the result of the AND operation. - - @return The new 32-bit value. - -**/ -UINT32 -EFIAPI -BitFieldAndThenOr32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT32 AndData, - IN UINT32 OrData - ) -{ - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - return BitFieldOr32 ( - BitFieldAnd32 (Operand, StartBit, EndBit, AndData), - StartBit, - EndBit, - OrData - ); -} - -/** - Returns a bit field from a 64-bit value. - - Returns the bitfield specified by the StartBit and the EndBit from Operand. - - If 64-bit operations are not supported, then ASSERT(). - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - - @return The bit field read. - -**/ -UINT64 -EFIAPI -BitFieldRead64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - return RShiftU64 (Operand & ~LShiftU64 ((UINT64)-2, EndBit), StartBit); -} - -/** - Writes a bit field to a 64-bit value, and returns the result. - - Writes Value to the bit field specified by the StartBit and the EndBit in - Operand. All other bits in Operand are preserved. The new 64-bit value is - returned. - - If 64-bit operations are not supported, then ASSERT(). - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If Value is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - @param Value The new value of the bit field. - - @return The new 64-bit value. - -**/ -UINT64 -EFIAPI -BitFieldWrite64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT64 Value - ) -{ - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - return BitFieldAndThenOr64 (Operand, StartBit, EndBit, 0, Value); -} - -/** - Reads a bit field from a 64-bit value, performs a bitwise OR, and returns the - result. - - Performs a bitwise OR between the bit field specified by StartBit - and EndBit in Operand and the value specified by OrData. All other bits in - Operand are preserved. The new 64-bit value is returned. - - If 64-bit operations are not supported, then ASSERT(). - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - @param OrData The value to OR with the read value from the value - - @return The new 64-bit value. - -**/ -UINT64 -EFIAPI -BitFieldOr64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT64 OrData - ) -{ - UINT64 Value1; - UINT64 Value2; - - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - // - // Higher bits in OrData those are not used must be zero. - // - // EndBit - StartBit + 1 might be 64 while the result right shifting 64 on RShiftU64() API is invalid, - // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. - // - ASSERT (RShiftU64 (OrData, EndBit - StartBit) == (RShiftU64 (OrData, EndBit - StartBit) & 1)); - - Value1 = LShiftU64 (OrData, StartBit); - Value2 = LShiftU64 ((UINT64) - 2, EndBit); - - return Operand | (Value1 & ~Value2); -} - -/** - Reads a bit field from a 64-bit value, performs a bitwise AND, and returns - the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData. All other bits in Operand are - preserved. The new 64-bit value is returned. - - If 64-bit operations are not supported, then ASSERT(). - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - @param AndData The value to AND with the read value from the value. - - @return The new 64-bit value. - -**/ -UINT64 -EFIAPI -BitFieldAnd64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT64 AndData - ) -{ - UINT64 Value1; - UINT64 Value2; - - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - // - // Higher bits in AndData those are not used must be zero. - // - // EndBit - StartBit + 1 might be 64 while the right shifting 64 on RShiftU64() API is invalid, - // So the logic is updated to right shift (EndBit - StartBit) bits and compare the last bit directly. - // - ASSERT (RShiftU64 (AndData, EndBit - StartBit) == (RShiftU64 (AndData, EndBit - StartBit) & 1)); - - Value1 = LShiftU64 (~AndData, StartBit); - Value2 = LShiftU64 ((UINT64)-2, EndBit); - - return Operand & ~(Value1 & ~Value2); -} - -/** - Reads a bit field from a 64-bit value, performs a bitwise AND followed by a - bitwise OR, and returns the result. - - Performs a bitwise AND between the bit field specified by StartBit and EndBit - in Operand and the value specified by AndData, followed by a bitwise - OR with value specified by OrData. All other bits in Operand are - preserved. The new 64-bit value is returned. - - If 64-bit operations are not supported, then ASSERT(). - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - If AndData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - If OrData is larger than the bitmask value range specified by StartBit and EndBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - @param AndData The value to AND with the read value from the value. - @param OrData The value to OR with the result of the AND operation. - - @return The new 64-bit value. - -**/ -UINT64 -EFIAPI -BitFieldAndThenOr64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit, - IN UINT64 AndData, - IN UINT64 OrData - ) -{ - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - return BitFieldOr64 ( - BitFieldAnd64 (Operand, StartBit, EndBit, AndData), - StartBit, - EndBit, - OrData - ); -} - -/** - Reads a bit field from a 32-bit value, counts and returns - the number of set bits. - - Counts the number of set bits in the bit field specified by - StartBit and EndBit in Operand. The count is returned. - - If StartBit is greater than 31, then ASSERT(). - If EndBit is greater than 31, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..31. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..31. - - @return The number of bits set between StartBit and EndBit. - -**/ -UINT8 -EFIAPI -BitFieldCountOnes32 ( - IN UINT32 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - UINT32 Count; - - ASSERT (EndBit < 32); - ASSERT (StartBit <= EndBit); - - Count = BitFieldRead32 (Operand, StartBit, EndBit); - Count -= ((Count >> 1) & 0x55555555); - Count = (Count & 0x33333333) + ((Count >> 2) & 0x33333333); - Count += Count >> 4; - Count &= 0x0F0F0F0F; - Count += Count >> 8; - Count += Count >> 16; - - return (UINT8) Count & 0x3F; -} - -/** - Reads a bit field from a 64-bit value, counts and returns - the number of set bits. - - Counts the number of set bits in the bit field specified by - StartBit and EndBit in Operand. The count is returned. - - If StartBit is greater than 63, then ASSERT(). - If EndBit is greater than 63, then ASSERT(). - If EndBit is less than StartBit, then ASSERT(). - - @param Operand Operand on which to perform the bitfield operation. - @param StartBit The ordinal of the least significant bit in the bit field. - Range 0..63. - @param EndBit The ordinal of the most significant bit in the bit field. - Range 0..63. - - @return The number of bits set between StartBit and EndBit. - -**/ -UINT8 -EFIAPI -BitFieldCountOnes64 ( - IN UINT64 Operand, - IN UINTN StartBit, - IN UINTN EndBit - ) -{ - UINT64 BitField; - UINT8 Count; - - ASSERT (EndBit < 64); - ASSERT (StartBit <= EndBit); - - BitField = BitFieldRead64 (Operand, StartBit, EndBit); - Count = BitFieldCountOnes32 ((UINT32) BitField, 0, 31); - Count += BitFieldCountOnes32 ((UINT32) RShiftU64(BitField, 32), 0, 31); - - return Count; -} - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Cache.c b/MdePkg/Test/HostLibrary/BaseLibHost/Cache.c deleted file mode 100644 index ff787e3f24f..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Cache.c +++ /dev/null @@ -1,40 +0,0 @@ -/** @file - Base Library CPU Functions for all architectures. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -/** - Set CD bit and clear NW bit of CR0 followed by a WBINVD. - - Disables the caches by setting the CD bit of CR0 to 1, clearing the NW bit of CR0 to 0, - and executing a WBINVD instruction. This function is only available on IA-32 and x64. - -**/ -VOID -EFIAPI -AsmDisableCache ( - VOID - ) -{ -} - - -/** - Perform a WBINVD and clear both the CD and NW bits of CR0. - - Enables the caches by executing a WBINVD instruction and then clear both the CD and NW - bits of CR0 to 0. This function is only available on IA-32 and x64. - -**/ -VOID -EFIAPI -AsmEnableCache ( - VOID - ) -{ -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c b/MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c deleted file mode 100644 index 0dd3cc95c2d..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/CheckSum.c +++ /dev/null @@ -1,628 +0,0 @@ -/** @file - Utility functions to generate checksum based on 2's complement - algorithm. - - Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the sum of all elements in a buffer in unit of UINT8. - During calculation, the carry bits are dropped. - - This function calculates the sum of all elements in a buffer - in unit of UINT8. The carry bits in result of addition are dropped. - The result is returned as UINT8. If Length is Zero, then Zero is - returned. - - If Buffer is NULL, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the sum operation. - @param Length The size, in bytes, of Buffer. - - @return Sum The sum of Buffer with carry bits dropped during additions. - -**/ -UINT8 -EFIAPI -CalculateSum8 ( - IN CONST UINT8 *Buffer, - IN UINTN Length - ) -{ - UINT8 Sum; - UINTN Count; - - ASSERT (Buffer != NULL); - ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); - - for (Sum = 0, Count = 0; Count < Length; Count++) { - Sum = (UINT8) (Sum + *(Buffer + Count)); - } - - return Sum; -} - - -/** - Returns the two's complement checksum of all elements in a buffer - of 8-bit values. - - This function first calculates the sum of the 8-bit values in the - buffer specified by Buffer and Length. The carry bits in the result - of addition are dropped. Then, the two's complement of the sum is - returned. If Length is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the checksum operation. - @param Length The size, in bytes, of Buffer. - - @return Checksum The 2's complement checksum of Buffer. - -**/ -UINT8 -EFIAPI -CalculateCheckSum8 ( - IN CONST UINT8 *Buffer, - IN UINTN Length - ) -{ - UINT8 CheckSum; - - CheckSum = CalculateSum8 (Buffer, Length); - - // - // Return the checksum based on 2's complement. - // - return (UINT8) (0x100 - CheckSum); -} - -/** - Returns the sum of all elements in a buffer of 16-bit values. During - calculation, the carry bits are dropped. - - This function calculates the sum of the 16-bit values in the buffer - specified by Buffer and Length. The carry bits in result of addition are dropped. - The 16-bit result is returned. If Length is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 16-bit boundary, then ASSERT(). - If Length is not aligned on a 16-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the sum operation. - @param Length The size, in bytes, of Buffer. - - @return Sum The sum of Buffer with carry bits dropped during additions. - -**/ -UINT16 -EFIAPI -CalculateSum16 ( - IN CONST UINT16 *Buffer, - IN UINTN Length - ) -{ - UINT16 Sum; - UINTN Count; - UINTN Total; - - ASSERT (Buffer != NULL); - ASSERT (((UINTN) Buffer & 0x1) == 0); - ASSERT ((Length & 0x1) == 0); - ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); - - Total = Length / sizeof (*Buffer); - for (Sum = 0, Count = 0; Count < Total; Count++) { - Sum = (UINT16) (Sum + *(Buffer + Count)); - } - - return Sum; -} - - -/** - Returns the two's complement checksum of all elements in a buffer of - 16-bit values. - - This function first calculates the sum of the 16-bit values in the buffer - specified by Buffer and Length. The carry bits in the result of addition - are dropped. Then, the two's complement of the sum is returned. If Length - is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 16-bit boundary, then ASSERT(). - If Length is not aligned on a 16-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the checksum operation. - @param Length The size, in bytes, of Buffer. - - @return Checksum The 2's complement checksum of Buffer. - -**/ -UINT16 -EFIAPI -CalculateCheckSum16 ( - IN CONST UINT16 *Buffer, - IN UINTN Length - ) -{ - UINT16 CheckSum; - - CheckSum = CalculateSum16 (Buffer, Length); - - // - // Return the checksum based on 2's complement. - // - return (UINT16) (0x10000 - CheckSum); -} - - -/** - Returns the sum of all elements in a buffer of 32-bit values. During - calculation, the carry bits are dropped. - - This function calculates the sum of the 32-bit values in the buffer - specified by Buffer and Length. The carry bits in result of addition are dropped. - The 32-bit result is returned. If Length is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 32-bit boundary, then ASSERT(). - If Length is not aligned on a 32-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the sum operation. - @param Length The size, in bytes, of Buffer. - - @return Sum The sum of Buffer with carry bits dropped during additions. - -**/ -UINT32 -EFIAPI -CalculateSum32 ( - IN CONST UINT32 *Buffer, - IN UINTN Length - ) -{ - UINT32 Sum; - UINTN Count; - UINTN Total; - - ASSERT (Buffer != NULL); - ASSERT (((UINTN) Buffer & 0x3) == 0); - ASSERT ((Length & 0x3) == 0); - ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); - - Total = Length / sizeof (*Buffer); - for (Sum = 0, Count = 0; Count < Total; Count++) { - Sum = Sum + *(Buffer + Count); - } - - return Sum; -} - - -/** - Returns the two's complement checksum of all elements in a buffer of - 32-bit values. - - This function first calculates the sum of the 32-bit values in the buffer - specified by Buffer and Length. The carry bits in the result of addition - are dropped. Then, the two's complement of the sum is returned. If Length - is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 32-bit boundary, then ASSERT(). - If Length is not aligned on a 32-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the checksum operation. - @param Length The size, in bytes, of Buffer. - - @return Checksum The 2's complement checksum of Buffer. - -**/ -UINT32 -EFIAPI -CalculateCheckSum32 ( - IN CONST UINT32 *Buffer, - IN UINTN Length - ) -{ - UINT32 CheckSum; - - CheckSum = CalculateSum32 (Buffer, Length); - - // - // Return the checksum based on 2's complement. - // - return (UINT32) ((UINT32)(-1) - CheckSum + 1); -} - - -/** - Returns the sum of all elements in a buffer of 64-bit values. During - calculation, the carry bits are dropped. - - This function calculates the sum of the 64-bit values in the buffer - specified by Buffer and Length. The carry bits in result of addition are dropped. - The 64-bit result is returned. If Length is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 64-bit boundary, then ASSERT(). - If Length is not aligned on a 64-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the sum operation. - @param Length The size, in bytes, of Buffer. - - @return Sum The sum of Buffer with carry bits dropped during additions. - -**/ -UINT64 -EFIAPI -CalculateSum64 ( - IN CONST UINT64 *Buffer, - IN UINTN Length - ) -{ - UINT64 Sum; - UINTN Count; - UINTN Total; - - ASSERT (Buffer != NULL); - ASSERT (((UINTN) Buffer & 0x7) == 0); - ASSERT ((Length & 0x7) == 0); - ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); - - Total = Length / sizeof (*Buffer); - for (Sum = 0, Count = 0; Count < Total; Count++) { - Sum = Sum + *(Buffer + Count); - } - - return Sum; -} - - -/** - Returns the two's complement checksum of all elements in a buffer of - 64-bit values. - - This function first calculates the sum of the 64-bit values in the buffer - specified by Buffer and Length. The carry bits in the result of addition - are dropped. Then, the two's complement of the sum is returned. If Length - is 0, then 0 is returned. - - If Buffer is NULL, then ASSERT(). - If Buffer is not aligned on a 64-bit boundary, then ASSERT(). - If Length is not aligned on a 64-bit boundary, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param Buffer The pointer to the buffer to carry out the checksum operation. - @param Length The size, in bytes, of Buffer. - - @return Checksum The 2's complement checksum of Buffer. - -**/ -UINT64 -EFIAPI -CalculateCheckSum64 ( - IN CONST UINT64 *Buffer, - IN UINTN Length - ) -{ - UINT64 CheckSum; - - CheckSum = CalculateSum64 (Buffer, Length); - - // - // Return the checksum based on 2's complement. - // - return (UINT64) ((UINT64)(-1) - CheckSum + 1); -} - -GLOBAL_REMOVE_IF_UNREFERENCED CONST UINT32 mCrcTable[256] = { - 0x00000000, - 0x77073096, - 0xEE0E612C, - 0x990951BA, - 0x076DC419, - 0x706AF48F, - 0xE963A535, - 0x9E6495A3, - 0x0EDB8832, - 0x79DCB8A4, - 0xE0D5E91E, - 0x97D2D988, - 0x09B64C2B, - 0x7EB17CBD, - 0xE7B82D07, - 0x90BF1D91, - 0x1DB71064, - 0x6AB020F2, - 0xF3B97148, - 0x84BE41DE, - 0x1ADAD47D, - 0x6DDDE4EB, - 0xF4D4B551, - 0x83D385C7, - 0x136C9856, - 0x646BA8C0, - 0xFD62F97A, - 0x8A65C9EC, - 0x14015C4F, - 0x63066CD9, - 0xFA0F3D63, - 0x8D080DF5, - 0x3B6E20C8, - 0x4C69105E, - 0xD56041E4, - 0xA2677172, - 0x3C03E4D1, - 0x4B04D447, - 0xD20D85FD, - 0xA50AB56B, - 0x35B5A8FA, - 0x42B2986C, - 0xDBBBC9D6, - 0xACBCF940, - 0x32D86CE3, - 0x45DF5C75, - 0xDCD60DCF, - 0xABD13D59, - 0x26D930AC, - 0x51DE003A, - 0xC8D75180, - 0xBFD06116, - 0x21B4F4B5, - 0x56B3C423, - 0xCFBA9599, - 0xB8BDA50F, - 0x2802B89E, - 0x5F058808, - 0xC60CD9B2, - 0xB10BE924, - 0x2F6F7C87, - 0x58684C11, - 0xC1611DAB, - 0xB6662D3D, - 0x76DC4190, - 0x01DB7106, - 0x98D220BC, - 0xEFD5102A, - 0x71B18589, - 0x06B6B51F, - 0x9FBFE4A5, - 0xE8B8D433, - 0x7807C9A2, - 0x0F00F934, - 0x9609A88E, - 0xE10E9818, - 0x7F6A0DBB, - 0x086D3D2D, - 0x91646C97, - 0xE6635C01, - 0x6B6B51F4, - 0x1C6C6162, - 0x856530D8, - 0xF262004E, - 0x6C0695ED, - 0x1B01A57B, - 0x8208F4C1, - 0xF50FC457, - 0x65B0D9C6, - 0x12B7E950, - 0x8BBEB8EA, - 0xFCB9887C, - 0x62DD1DDF, - 0x15DA2D49, - 0x8CD37CF3, - 0xFBD44C65, - 0x4DB26158, - 0x3AB551CE, - 0xA3BC0074, - 0xD4BB30E2, - 0x4ADFA541, - 0x3DD895D7, - 0xA4D1C46D, - 0xD3D6F4FB, - 0x4369E96A, - 0x346ED9FC, - 0xAD678846, - 0xDA60B8D0, - 0x44042D73, - 0x33031DE5, - 0xAA0A4C5F, - 0xDD0D7CC9, - 0x5005713C, - 0x270241AA, - 0xBE0B1010, - 0xC90C2086, - 0x5768B525, - 0x206F85B3, - 0xB966D409, - 0xCE61E49F, - 0x5EDEF90E, - 0x29D9C998, - 0xB0D09822, - 0xC7D7A8B4, - 0x59B33D17, - 0x2EB40D81, - 0xB7BD5C3B, - 0xC0BA6CAD, - 0xEDB88320, - 0x9ABFB3B6, - 0x03B6E20C, - 0x74B1D29A, - 0xEAD54739, - 0x9DD277AF, - 0x04DB2615, - 0x73DC1683, - 0xE3630B12, - 0x94643B84, - 0x0D6D6A3E, - 0x7A6A5AA8, - 0xE40ECF0B, - 0x9309FF9D, - 0x0A00AE27, - 0x7D079EB1, - 0xF00F9344, - 0x8708A3D2, - 0x1E01F268, - 0x6906C2FE, - 0xF762575D, - 0x806567CB, - 0x196C3671, - 0x6E6B06E7, - 0xFED41B76, - 0x89D32BE0, - 0x10DA7A5A, - 0x67DD4ACC, - 0xF9B9DF6F, - 0x8EBEEFF9, - 0x17B7BE43, - 0x60B08ED5, - 0xD6D6A3E8, - 0xA1D1937E, - 0x38D8C2C4, - 0x4FDFF252, - 0xD1BB67F1, - 0xA6BC5767, - 0x3FB506DD, - 0x48B2364B, - 0xD80D2BDA, - 0xAF0A1B4C, - 0x36034AF6, - 0x41047A60, - 0xDF60EFC3, - 0xA867DF55, - 0x316E8EEF, - 0x4669BE79, - 0xCB61B38C, - 0xBC66831A, - 0x256FD2A0, - 0x5268E236, - 0xCC0C7795, - 0xBB0B4703, - 0x220216B9, - 0x5505262F, - 0xC5BA3BBE, - 0xB2BD0B28, - 0x2BB45A92, - 0x5CB36A04, - 0xC2D7FFA7, - 0xB5D0CF31, - 0x2CD99E8B, - 0x5BDEAE1D, - 0x9B64C2B0, - 0xEC63F226, - 0x756AA39C, - 0x026D930A, - 0x9C0906A9, - 0xEB0E363F, - 0x72076785, - 0x05005713, - 0x95BF4A82, - 0xE2B87A14, - 0x7BB12BAE, - 0x0CB61B38, - 0x92D28E9B, - 0xE5D5BE0D, - 0x7CDCEFB7, - 0x0BDBDF21, - 0x86D3D2D4, - 0xF1D4E242, - 0x68DDB3F8, - 0x1FDA836E, - 0x81BE16CD, - 0xF6B9265B, - 0x6FB077E1, - 0x18B74777, - 0x88085AE6, - 0xFF0F6A70, - 0x66063BCA, - 0x11010B5C, - 0x8F659EFF, - 0xF862AE69, - 0x616BFFD3, - 0x166CCF45, - 0xA00AE278, - 0xD70DD2EE, - 0x4E048354, - 0x3903B3C2, - 0xA7672661, - 0xD06016F7, - 0x4969474D, - 0x3E6E77DB, - 0xAED16A4A, - 0xD9D65ADC, - 0x40DF0B66, - 0x37D83BF0, - 0xA9BCAE53, - 0xDEBB9EC5, - 0x47B2CF7F, - 0x30B5FFE9, - 0xBDBDF21C, - 0xCABAC28A, - 0x53B39330, - 0x24B4A3A6, - 0xBAD03605, - 0xCDD70693, - 0x54DE5729, - 0x23D967BF, - 0xB3667A2E, - 0xC4614AB8, - 0x5D681B02, - 0x2A6F2B94, - 0xB40BBE37, - 0xC30C8EA1, - 0x5A05DF1B, - 0x2D02EF8D -}; - -/** - Computes and returns a 32-bit CRC for a data buffer. - CRC32 value bases on ITU-T V.42. - - If Buffer is NULL, then ASSERT(). - If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). - - @param[in] Buffer A pointer to the buffer on which the 32-bit CRC is to be computed. - @param[in] Length The number of bytes in the buffer Data. - - @retval Crc32 The 32-bit CRC was computed for the data buffer. - -**/ -UINT32 -EFIAPI -CalculateCrc32( - IN VOID *Buffer, - IN UINTN Length - ) -{ - UINTN Index; - UINT32 Crc; - UINT8 *Ptr; - - ASSERT (Buffer != NULL); - ASSERT (Length <= (MAX_ADDRESS - ((UINTN) Buffer) + 1)); - - // - // Compute CRC - // - Crc = 0xffffffff; - for (Index = 0, Ptr = Buffer; Index < Length; Index++, Ptr++) { - Crc = (Crc >> 8) ^ mCrcTable[(UINT8) Crc ^ *Ptr]; - } - - return Crc ^ 0xffffffff; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c b/MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c deleted file mode 100644 index 727fd9084b7..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Cpu.c +++ /dev/null @@ -1,95 +0,0 @@ -/** @file - Base Library CPU Functions for all architectures. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -/** - Disables CPU interrupts and returns the interrupt state prior to the disable - operation. - - @retval TRUE CPU interrupts were enabled on entry to this call. - @retval FALSE CPU interrupts were disabled on entry to this call. - -**/ -BOOLEAN -EFIAPI -SaveAndDisableInterrupts ( - VOID - ) -{ - return FALSE; -} - -/** - Set the current CPU interrupt state. - - Sets the current CPU interrupt state to the state specified by - InterruptState. If InterruptState is TRUE, then interrupts are enabled. If - InterruptState is FALSE, then interrupts are disabled. InterruptState is - returned. - - @param InterruptState TRUE if interrupts should be enabled. FALSE if - interrupts should be disabled. - - @return InterruptState - -**/ -BOOLEAN -EFIAPI -SetInterruptState ( - IN BOOLEAN InterruptState - ) -{ - return InterruptState; -} - -/** - Uses as a barrier to stop speculative execution. - - Ensures that no later instruction will execute speculatively, until all prior - instructions have completed. - -**/ -VOID -EFIAPI -SpeculationBarrier ( - VOID - ) -{ -} - -/** - Requests CPU to pause for a short period of time. - - Requests CPU to pause for a short period of time. Typically used in MP - systems to prevent memory starvation while waiting for a spin lock. - -**/ -VOID -EFIAPI -CpuPause ( - VOID - ) -{ -} - -/** - Performs a serializing operation on all load-from-memory instructions that - were issued prior the AsmLfence function. - - Executes a LFENCE instruction. This function is only available on IA-32 and x64. - -**/ -VOID -EFIAPI -AsmLfence ( - VOID - ) -{ - return; -} \ No newline at end of file diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c deleted file mode 100644 index 20edc0c4dfd..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointGcc.c +++ /dev/null @@ -1,26 +0,0 @@ -/** @file - CpuBreakpoint function. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - - - -/** - Generates a breakpoint on the CPU. - - Generates a breakpoint on the CPU. The breakpoint must be implemented such - that code can resume normal execution after the breakpoint. - -**/ -VOID -EFIAPI -CpuBreakpoint ( - VOID - ) -{ - __asm__ __volatile__ ("int $3"); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c deleted file mode 100644 index a59da0ceef9..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/CpuBreakpointMsvc.c +++ /dev/null @@ -1,35 +0,0 @@ -/** @file - CpuBreakpoint function. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - - - -/** - Microsoft Visual Studio 7.1 Function Prototypes for I/O Intrinsics. -**/ - -void __debugbreak (VOID); - -#pragma intrinsic(__debugbreak) - -/** - Generates a breakpoint on the CPU. - - Generates a breakpoint on the CPU. The breakpoint must be implemented such - that code can resume normal execution after the breakpoint. - -**/ -VOID -EFIAPI -CpuBreakpoint ( - VOID - ) -{ - __debugbreak (); -} - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c b/MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c deleted file mode 100644 index 9e110cacbc9..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/CpuDeadLoop.c +++ /dev/null @@ -1,32 +0,0 @@ -/** @file - Base Library CPU Functions for all architectures. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - - -#include -#include - -/** - Executes an infinite loop. - - Forces the CPU to execute an infinite loop. A debugger may be used to skip - past the loop and the code that follows the loop must execute properly. This - implies that the infinite loop must not cause the code that follow it to be - optimized away. - -**/ -VOID -EFIAPI -CpuDeadLoop ( - VOID - ) -{ - volatile UINTN Index; - - for (Index = 0; Index == 0;); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c deleted file mode 100644 index 3048df52d31..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DivS64x64Remainder.c +++ /dev/null @@ -1,54 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -INT64 -EFIAPI -InternalMathDivRemS64x64 ( - IN INT64 Dividend, - IN INT64 Divisor, - OUT INT64 *Remainder OPTIONAL - ); - -/** - Divides a 64-bit signed integer by a 64-bit signed integer and generates a - 64-bit signed result and a optional 64-bit signed remainder. - - This function divides the 64-bit signed value Dividend by the 64-bit signed - value Divisor and generates a 64-bit signed quotient. If Remainder is not - NULL, then the 64-bit signed remainder is returned in Remainder. This - function returns the 64-bit signed quotient. - - It is the caller's responsibility to not call this function with a Divisor of 0. - If Divisor is 0, then the quotient and remainder should be assumed to be - the largest negative integer. - - If Divisor is 0, then ASSERT(). - - @param Dividend A 64-bit signed value. - @param Divisor A 64-bit signed value. - @param Remainder A pointer to a 64-bit signed value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor - -**/ -INT64 -EFIAPI -DivS64x64Remainder ( - IN INT64 Dividend, - IN INT64 Divisor, - OUT INT64 *Remainder OPTIONAL - ) -{ - ASSERT (Divisor != 0); - return InternalMathDivRemS64x64 (Dividend, Divisor, Remainder); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c deleted file mode 100644 index b63fb6d968a..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32.c +++ /dev/null @@ -1,45 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathDivU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ); - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates - a 64-bit unsigned result. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. This - function returns the 64-bit unsigned quotient. - - If Divisor is 0, then ASSERT(). - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - - @return Dividend / Divisor - -**/ -UINT64 -EFIAPI -DivU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ) -{ - ASSERT (Divisor != 0); - return InternalMathDivU64x32 (Dividend, Divisor); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c deleted file mode 100644 index 03ce598beb3..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x32Remainder.c +++ /dev/null @@ -1,50 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathDivRemU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor, - OUT UINT32 *Remainder OPTIONAL - ); - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates - a 64-bit unsigned result and an optional 32-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder - is not NULL, then the 32-bit unsigned remainder is returned in Remainder. - This function returns the 64-bit unsigned quotient. - - If Divisor is 0, then ASSERT(). - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - @param Remainder A pointer to a 32-bit unsigned value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor - -**/ -UINT64 -EFIAPI -DivU64x32Remainder ( - IN UINT64 Dividend, - IN UINT32 Divisor, - OUT UINT32 *Remainder OPTIONAL - ) -{ - ASSERT (Divisor != 0); - return InternalMathDivRemU64x32 (Dividend, Divisor, Remainder); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c b/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c deleted file mode 100644 index ee3fd264be2..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DivU64x64Remainder.c +++ /dev/null @@ -1,50 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathDivRemU64x64 ( - IN UINT64 Dividend, - IN UINT64 Divisor, - OUT UINT64 *Remainder OPTIONAL - ); - -/** - Divides a 64-bit unsigned integer by a 64-bit unsigned integer and generates - a 64-bit unsigned result and an optional 64-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 64-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder - is not NULL, then the 64-bit unsigned remainder is returned in Remainder. - This function returns the 64-bit unsigned quotient. - - If Divisor is 0, then ASSERT(). - - @param Dividend A 64-bit unsigned value. - @param Divisor A 64-bit unsigned value. - @param Remainder A pointer to a 64-bit unsigned value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor - -**/ -UINT64 -EFIAPI -DivU64x64Remainder ( - IN UINT64 Dividend, - IN UINT64 Divisor, - OUT UINT64 *Remainder OPTIONAL - ) -{ - ASSERT (Divisor != 0); - return InternalMathDivRemU64x64 (Dividend, Divisor, Remainder); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c b/MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c deleted file mode 100644 index 1e880d56e95..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DummyRdRand.c +++ /dev/null @@ -1,65 +0,0 @@ -/** @file - - Copyright (c) 2016, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Generates a 16-bit random number through RDRAND instruction. - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - - **/ -BOOLEAN -EFIAPI -InternalX86RdRand16 ( - OUT UINT16 *Rand - ) -{ - return TRUE; -} - -/** - Generates a 32-bit random number through RDRAND instruction. - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -InternalX86RdRand32 ( - OUT UINT32 *Rand - ) -{ - return TRUE; -} - -/** - Generates a 64-bit random number through RDRAND instruction. - - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -InternalX86RdRand64 ( - OUT UINT64 *Rand - ) -{ - return TRUE; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c b/MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c deleted file mode 100644 index 62650dd7a5d..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/DummyReadTsc.c +++ /dev/null @@ -1,19 +0,0 @@ -/** @file - - Copyright (c) 2016, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -AsmReadTsc ( - VOID - ) -{ - return 0; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c b/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c deleted file mode 100644 index 90e5d5fb8a9..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo32.c +++ /dev/null @@ -1,37 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the value of the highest bit set in a 32-bit value. Equivalent to - 1 << log2(x). - - This function computes the value of the highest bit set in the 32-bit value - specified by Operand. If Operand is zero, then zero is returned. - - @param Operand The 32-bit operand to evaluate. - - @return 1 << HighBitSet32(Operand) - @retval 0 Operand is zero. - -**/ -UINT32 -EFIAPI -GetPowerOfTwo32 ( - IN UINT32 Operand - ) -{ - if (0 == Operand) { - return 0; - } - - return 1ul << HighBitSet32 (Operand); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c b/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c deleted file mode 100644 index 680a82d0d57..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/GetPowerOfTwo64.c +++ /dev/null @@ -1,37 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the value of the highest bit set in a 64-bit value. Equivalent to - 1 << log2(x). - - This function computes the value of the highest bit set in the 64-bit value - specified by Operand. If Operand is zero, then zero is returned. - - @param Operand The 64-bit operand to evaluate. - - @return 1 << HighBitSet64(Operand) - @retval 0 Operand is zero. - -**/ -UINT64 -EFIAPI -GetPowerOfTwo64 ( - IN UINT64 Operand - ) -{ - if (Operand == 0) { - return 0; - } - - return LShiftU64 (1, (UINTN) HighBitSet64 (Operand)); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c b/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c deleted file mode 100644 index 610de67f062..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet32.c +++ /dev/null @@ -1,40 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the bit position of the highest bit set in a 32-bit value. Equivalent - to log2(x). - - This function computes the bit position of the highest bit set in the 32-bit - value specified by Operand. If Operand is zero, then -1 is returned. - Otherwise, a value between 0 and 31 is returned. - - @param Operand The 32-bit operand to evaluate. - - @retval 0..31 Position of the highest bit set in Operand if found. - @retval -1 Operand is zero. - -**/ -INTN -EFIAPI -HighBitSet32 ( - IN UINT32 Operand - ) -{ - INTN BitIndex; - - if (Operand == 0) { - return - 1; - } - for (BitIndex = 31; (INT32)Operand > 0; BitIndex--, Operand <<= 1); - return BitIndex; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c b/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c deleted file mode 100644 index 28be7cfb302..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/HighBitSet64.c +++ /dev/null @@ -1,47 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Returns the bit position of the highest bit set in a 64-bit value. Equivalent - to log2(x). - - This function computes the bit position of the highest bit set in the 64-bit - value specified by Operand. If Operand is zero, then -1 is returned. - Otherwise, a value between 0 and 63 is returned. - - @param Operand The 64-bit operand to evaluate. - - @retval 0..63 Position of the highest bit set in Operand if found. - @retval -1 Operand is zero. - -**/ -INTN -EFIAPI -HighBitSet64 ( - IN UINT64 Operand - ) -{ - if (Operand == (UINT32)Operand) { - // - // Operand is just a 32-bit integer - // - return HighBitSet32 ((UINT32)Operand); - } - - // - // Operand is really a 64-bit integer - // - if (sizeof (UINTN) == sizeof (UINT32)) { - return HighBitSet32 (((UINT32*)&Operand)[1]) + 32; - } else { - return HighBitSet32 ((UINT32)RShiftU64 (Operand, 32)) + 32; - } -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm deleted file mode 100644 index e12b8e96119..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/RdRand.nasm +++ /dev/null @@ -1,84 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; RdRand.nasm -; -; Abstract: -; -; Generates random number through CPU RdRand instruction under 32-bit platform. -; -; Notes: -; -;------------------------------------------------------------------------------ - -SECTION .text - -;------------------------------------------------------------------------------ -; Generates a 16 bit random number through RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand16 (UINT16 *Rand); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand16) -ASM_PFX(InternalX86RdRand16): - ; rdrand ax ; generate a 16 bit RN into ax - ; CF=1 if RN generated ok, otherwise CF=0 - db 0xf, 0xc7, 0xf0 ; rdrand r16: "0f c7 /6 ModRM:r/m(w)" - jc rn16_ok ; jmp if CF=1 - xor eax, eax ; reg=0 if CF=0 - ret ; return with failure status -rn16_ok: - mov edx, dword [esp + 4] - mov [edx], ax - mov eax, 1 - ret - -;------------------------------------------------------------------------------ -; Generates a 32 bit random number through RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand32 (UINT32 *Rand); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand32) -ASM_PFX(InternalX86RdRand32): - ; rdrand eax ; generate a 32 bit RN into eax - ; CF=1 if RN generated ok, otherwise CF=0 - db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" - jc rn32_ok ; jmp if CF=1 - xor eax, eax ; reg=0 if CF=0 - ret ; return with failure status -rn32_ok: - mov edx, dword [esp + 4] - mov [edx], eax - mov eax, 1 - ret - -;------------------------------------------------------------------------------ -; Generates a 64 bit random number through RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand64 (UINT64 *Rand); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand64) -ASM_PFX(InternalX86RdRand64): - ; rdrand eax ; generate a 32 bit RN into eax - ; CF=1 if RN generated ok, otherwise CF=0 - db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" - jnc rn64_ret ; jmp if CF=0 - mov edx, dword [esp + 4] - mov [edx], eax - - db 0xf, 0xc7, 0xf0 ; generate another 32 bit RN - jnc rn64_ret ; jmp if CF=0 - mov [edx + 4], eax - - mov eax, 1 - ret -rn64_ret: - xor eax, eax - ret ; return with failure status - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm deleted file mode 100644 index 1bc875bd363..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Ia32/ReadTsc.nasm +++ /dev/null @@ -1,31 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2006, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; ReadTsc.Asm -; -; Abstract: -; -; AsmReadTsc function -; -; Notes: -; -;------------------------------------------------------------------------------ - - SECTION .text - -;------------------------------------------------------------------------------ -; UINT64 -; EFIAPI -; AsmReadTsc ( -; VOID -; ); -;------------------------------------------------------------------------------ -global ASM_PFX(AsmReadTsc) -ASM_PFX(AsmReadTsc): - rdtsc - ret - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c b/MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c deleted file mode 100644 index 8c189817296..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LRotU32.c +++ /dev/null @@ -1,38 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Rotates a 32-bit integer left between 0 and 31 bits, filling the low bits - with the high bits that were rotated. - - This function rotates the 32-bit value Operand to the left by Count bits. The - low Count bits are fill with the high Count bits of Operand. The rotated - value is returned. - - If Count is greater than 31, then ASSERT(). - - @param Operand The 32-bit operand to rotate left. - @param Count The number of bits to rotate left. - - @return Operand << Count - -**/ -UINT32 -EFIAPI -LRotU32 ( - IN UINT32 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 32); - return (Operand << Count) | (Operand >> (32 - Count)); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c deleted file mode 100644 index c58cdeb6211..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LRotU64.c +++ /dev/null @@ -1,45 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathLRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ); - -/** - Rotates a 64-bit integer left between 0 and 63 bits, filling the low bits - with the high bits that were rotated. - - This function rotates the 64-bit value Operand to the left by Count bits. The - low Count bits are fill with the high Count bits of Operand. The rotated - value is returned. - - If Count is greater than 63, then ASSERT(). - - @param Operand The 64-bit operand to rotate left. - @param Count The number of bits to rotate left. - - @return Operand << Count - -**/ -UINT64 -EFIAPI -LRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 64); - return InternalMathLRotU64 (Operand, Count); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c deleted file mode 100644 index 220e5c13910..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LShiftU64.c +++ /dev/null @@ -1,44 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathLShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ); - -/** - Shifts a 64-bit integer left between 0 and 63 bits. The low bits are filled - with zeros. The shifted value is returned. - - This function shifts the 64-bit value Operand to the left by Count bits. The - low Count bits are set to zero. The shifted value is returned. - - If Count is greater than 63, then ASSERT(). - - @param Operand The 64-bit operand to shift left. - @param Count The number of bits to shift left. - - @return Operand << Count. - -**/ -UINT64 -EFIAPI -LShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 64); - return InternalMathLShiftU64 (Operand, Count); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c b/MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c deleted file mode 100644 index e894b4e22c4..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Lfence.c +++ /dev/null @@ -1,10 +0,0 @@ -/** @file - - Copyright (c) 2016, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c b/MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c deleted file mode 100644 index 550d5de5405..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LinkedList.c +++ /dev/null @@ -1,536 +0,0 @@ -/** @file - Linked List Library Functions. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -#define ASSERT_VERIFY_NODE_IN_VALID_LIST(FirstEntry, SecondEntry, InList) - -/** - Worker function that verifies the validity of this list. - - If List is NULL, then ASSERT(). - If List->ForwardLink is NULL, then ASSERT(). - If List->BackLink is NULL, then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and List contains more than - PcdMaximumLinkedListLength nodes, then ASSERT(). - - @param List A pointer to a node in a linked list. - - @retval TRUE if PcdVerifyNodeInList is FALSE - @retval TRUE if DoMembershipCheck is FALSE - @retval TRUE if PcdVerifyNodeInList is TRUE and DoMembershipCheck is TRUE - and Node is a member of List. - @retval FALSE if PcdVerifyNodeInList is TRUE and DoMembershipCheck is TRUE - and Node is in not a member of List. - -**/ -BOOLEAN -EFIAPI -InternalBaseLibIsListValid ( - IN CONST LIST_ENTRY *List - ) -{ - // - // Test the validity of List and Node - // - ASSERT (List != NULL); - ASSERT (List->ForwardLink != NULL); - ASSERT (List->BackLink != NULL); - - return TRUE; -} - -/** - Checks whether FirstEntry and SecondEntry are part of the same doubly-linked - list. - - If FirstEntry is NULL, then ASSERT(). - If FirstEntry->ForwardLink is NULL, then ASSERT(). - If FirstEntry->BackLink is NULL, then ASSERT(). - If SecondEntry is NULL, then ASSERT(); - If PcdMaximumLinkedListLength is not zero, and List contains more than - PcdMaximumLinkedListLength nodes, then ASSERT(). - - @param FirstEntry A pointer to a node in a linked list. - @param SecondEntry A pointer to the node to locate. - - @retval TRUE SecondEntry is in the same doubly-linked list as FirstEntry. - @retval FALSE SecondEntry isn't in the same doubly-linked list as FirstEntry, - or FirstEntry is invalid. - -**/ -BOOLEAN -EFIAPI -IsNodeInList ( - IN CONST LIST_ENTRY *FirstEntry, - IN CONST LIST_ENTRY *SecondEntry - ) -{ - CONST LIST_ENTRY *Ptr; - - // - // ASSERT List not too long - // - ASSERT (InternalBaseLibIsListValid (FirstEntry)); - - ASSERT (SecondEntry != NULL); - - Ptr = FirstEntry; - - // - // Check to see if SecondEntry is a member of FirstEntry. - // Exit early if the number of nodes in List >= PcdMaximumLinkedListLength - // - do { - Ptr = Ptr->ForwardLink; - if (Ptr == SecondEntry) { - return TRUE; - } - } while (Ptr != FirstEntry); - - return FALSE; -} - -/** - Initializes the head node of a doubly-linked list, and returns the pointer to - the head node of the doubly-linked list. - - Initializes the forward and backward links of a new linked list. After - initializing a linked list with this function, the other linked list - functions may be used to add and remove nodes from the linked list. It is up - to the caller of this function to allocate the memory for ListHead. - - If ListHead is NULL, then ASSERT(). - - @param ListHead A pointer to the head node of a new doubly-linked list. - - @return ListHead - -**/ -LIST_ENTRY * -EFIAPI -InitializeListHead ( - IN OUT LIST_ENTRY *ListHead - ) - -{ - ASSERT (ListHead != NULL); - - ListHead->ForwardLink = ListHead; - ListHead->BackLink = ListHead; - return ListHead; -} - -/** - Adds a node to the beginning of a doubly-linked list, and returns the pointer - to the head node of the doubly-linked list. - - Adds the node Entry at the beginning of the doubly-linked list denoted by - ListHead, and returns ListHead. - - If ListHead is NULL, then ASSERT(). - If Entry is NULL, then ASSERT(). - If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and prior to insertion the number - of nodes in ListHead, including the ListHead node, is greater than or - equal to PcdMaximumLinkedListLength, then ASSERT(). - - @param ListHead A pointer to the head node of a doubly-linked list. - @param Entry A pointer to a node that is to be inserted at the beginning - of a doubly-linked list. - - @return ListHead - -**/ -LIST_ENTRY * -EFIAPI -InsertHeadList ( - IN OUT LIST_ENTRY *ListHead, - IN OUT LIST_ENTRY *Entry - ) -{ - // - // ASSERT List not too long and Entry is not one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (ListHead, Entry, FALSE); - - Entry->ForwardLink = ListHead->ForwardLink; - Entry->BackLink = ListHead; - Entry->ForwardLink->BackLink = Entry; - ListHead->ForwardLink = Entry; - return ListHead; -} - -/** - Adds a node to the end of a doubly-linked list, and returns the pointer to - the head node of the doubly-linked list. - - Adds the node Entry to the end of the doubly-linked list denoted by ListHead, - and returns ListHead. - - If ListHead is NULL, then ASSERT(). - If Entry is NULL, then ASSERT(). - If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and prior to insertion the number - of nodes in ListHead, including the ListHead node, is greater than or - equal to PcdMaximumLinkedListLength, then ASSERT(). - - @param ListHead A pointer to the head node of a doubly-linked list. - @param Entry A pointer to a node that is to be added at the end of the - doubly-linked list. - - @return ListHead - -**/ -LIST_ENTRY * -EFIAPI -InsertTailList ( - IN OUT LIST_ENTRY *ListHead, - IN OUT LIST_ENTRY *Entry - ) -{ - // - // ASSERT List not too long and Entry is not one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (ListHead, Entry, FALSE); - - Entry->ForwardLink = ListHead; - Entry->BackLink = ListHead->BackLink; - Entry->BackLink->ForwardLink = Entry; - ListHead->BackLink = Entry; - return ListHead; -} - -/** - Retrieves the first node of a doubly-linked list. - - Returns the first node of a doubly-linked list. List must have been - initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). - If List is empty, then List is returned. - - If List is NULL, then ASSERT(). - If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes - in List, including the List node, is greater than or equal to - PcdMaximumLinkedListLength, then ASSERT(). - - @param List A pointer to the head node of a doubly-linked list. - - @return The first node of a doubly-linked list. - @retval List The list is empty. - -**/ -LIST_ENTRY * -EFIAPI -GetFirstNode ( - IN CONST LIST_ENTRY *List - ) -{ - // - // ASSERT List not too long - // - ASSERT (InternalBaseLibIsListValid (List)); - - return List->ForwardLink; -} - -/** - Retrieves the next node of a doubly-linked list. - - Returns the node of a doubly-linked list that follows Node. - List must have been initialized with INTIALIZE_LIST_HEAD_VARIABLE() - or InitializeListHead(). If List is empty, then List is returned. - - If List is NULL, then ASSERT(). - If Node is NULL, then ASSERT(). - If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and List contains more than - PcdMaximumLinkedListLength nodes, then ASSERT(). - If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). - - @param List A pointer to the head node of a doubly-linked list. - @param Node A pointer to a node in the doubly-linked list. - - @return A pointer to the next node if one exists. Otherwise List is returned. - -**/ -LIST_ENTRY * -EFIAPI -GetNextNode ( - IN CONST LIST_ENTRY *List, - IN CONST LIST_ENTRY *Node - ) -{ - // - // ASSERT List not too long and Node is one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); - - return Node->ForwardLink; -} - -/** - Retrieves the previous node of a doubly-linked list. - - Returns the node of a doubly-linked list that precedes Node. - List must have been initialized with INTIALIZE_LIST_HEAD_VARIABLE() - or InitializeListHead(). If List is empty, then List is returned. - - If List is NULL, then ASSERT(). - If Node is NULL, then ASSERT(). - If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and List contains more than - PcdMaximumLinkedListLength nodes, then ASSERT(). - If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). - - @param List A pointer to the head node of a doubly-linked list. - @param Node A pointer to a node in the doubly-linked list. - - @return A pointer to the previous node if one exists. Otherwise List is returned. - -**/ -LIST_ENTRY * -EFIAPI -GetPreviousNode ( - IN CONST LIST_ENTRY *List, - IN CONST LIST_ENTRY *Node - ) -{ - // - // ASSERT List not too long and Node is one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); - - return Node->BackLink; -} - -/** - Checks to see if a doubly-linked list is empty or not. - - Checks to see if the doubly-linked list is empty. If the linked list contains - zero nodes, this function returns TRUE. Otherwise, it returns FALSE. - - If ListHead is NULL, then ASSERT(). - If ListHead was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes - in List, including the List node, is greater than or equal to - PcdMaximumLinkedListLength, then ASSERT(). - - @param ListHead A pointer to the head node of a doubly-linked list. - - @retval TRUE The linked list is empty. - @retval FALSE The linked list is not empty. - -**/ -BOOLEAN -EFIAPI -IsListEmpty ( - IN CONST LIST_ENTRY *ListHead - ) -{ - // - // ASSERT List not too long - // - ASSERT (InternalBaseLibIsListValid (ListHead)); - - return (BOOLEAN)(ListHead->ForwardLink == ListHead); -} - -/** - Determines if a node in a doubly-linked list is the head node of a the same - doubly-linked list. This function is typically used to terminate a loop that - traverses all the nodes in a doubly-linked list starting with the head node. - - Returns TRUE if Node is equal to List. Returns FALSE if Node is one of the - nodes in the doubly-linked list specified by List. List must have been - initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). - - If List is NULL, then ASSERT(). - If Node is NULL, then ASSERT(). - If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(), - then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes - in List, including the List node, is greater than or equal to - PcdMaximumLinkedListLength, then ASSERT(). - If PcdVerifyNodeInList is TRUE and Node is not a node in List and Node is not - equal to List, then ASSERT(). - - @param List A pointer to the head node of a doubly-linked list. - @param Node A pointer to a node in the doubly-linked list. - - @retval TRUE Node is the head of the doubly-linked list pointed by List. - @retval FALSE Node is not the head of the doubly-linked list pointed by List. - -**/ -BOOLEAN -EFIAPI -IsNull ( - IN CONST LIST_ENTRY *List, - IN CONST LIST_ENTRY *Node - ) -{ - // - // ASSERT List not too long and Node is one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); - - return (BOOLEAN)(Node == List); -} - -/** - Determines if a node the last node in a doubly-linked list. - - Returns TRUE if Node is the last node in the doubly-linked list specified by - List. Otherwise, FALSE is returned. List must have been initialized with - INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). - - If List is NULL, then ASSERT(). - If Node is NULL, then ASSERT(). - If List was not initialized with INTIALIZE_LIST_HEAD_VARIABLE() or - InitializeListHead(), then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes - in List, including the List node, is greater than or equal to - PcdMaximumLinkedListLength, then ASSERT(). - If PcdVerifyNodeInList is TRUE and Node is not a node in List, then ASSERT(). - - @param List A pointer to the head node of a doubly-linked list. - @param Node A pointer to a node in the doubly-linked list. - - @retval TRUE Node is the last node in the linked list. - @retval FALSE Node is not the last node in the linked list. - -**/ -BOOLEAN -EFIAPI -IsNodeAtEnd ( - IN CONST LIST_ENTRY *List, - IN CONST LIST_ENTRY *Node - ) -{ - // - // ASSERT List not too long and Node is one of the nodes of List - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (List, Node, TRUE); - - return (BOOLEAN)(!IsNull (List, Node) && List->BackLink == Node); -} - -/** - Swaps the location of two nodes in a doubly-linked list, and returns the - first node after the swap. - - If FirstEntry is identical to SecondEntry, then SecondEntry is returned. - Otherwise, the location of the FirstEntry node is swapped with the location - of the SecondEntry node in a doubly-linked list. SecondEntry must be in the - same double linked list as FirstEntry and that double linked list must have - been initialized with INTIALIZE_LIST_HEAD_VARIABLE() or InitializeListHead(). - SecondEntry is returned after the nodes are swapped. - - If FirstEntry is NULL, then ASSERT(). - If SecondEntry is NULL, then ASSERT(). - If PcdVerifyNodeInList is TRUE and SecondEntry and FirstEntry are not in the - same linked list, then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes in the - linked list containing the FirstEntry and SecondEntry nodes, including - the FirstEntry and SecondEntry nodes, is greater than or equal to - PcdMaximumLinkedListLength, then ASSERT(). - - @param FirstEntry A pointer to a node in a linked list. - @param SecondEntry A pointer to another node in the same linked list. - - @return SecondEntry. - -**/ -LIST_ENTRY * -EFIAPI -SwapListEntries ( - IN OUT LIST_ENTRY *FirstEntry, - IN OUT LIST_ENTRY *SecondEntry - ) -{ - LIST_ENTRY *Ptr; - - if (FirstEntry == SecondEntry) { - return SecondEntry; - } - - // - // ASSERT Entry1 and Entry2 are in the same linked list - // - ASSERT_VERIFY_NODE_IN_VALID_LIST (FirstEntry, SecondEntry, TRUE); - - // - // Ptr is the node pointed to by FirstEntry->ForwardLink - // - Ptr = RemoveEntryList (FirstEntry); - - // - // If FirstEntry immediately follows SecondEntry, FirstEntry will be placed - // immediately in front of SecondEntry - // - if (Ptr->BackLink == SecondEntry) { - return InsertTailList (SecondEntry, FirstEntry); - } - - // - // Ptr == SecondEntry means SecondEntry immediately follows FirstEntry, - // then there are no further steps necessary - // - if (Ptr == InsertHeadList (SecondEntry, FirstEntry)) { - return Ptr; - } - - // - // Move SecondEntry to the front of Ptr - // - RemoveEntryList (SecondEntry); - InsertTailList (Ptr, SecondEntry); - return SecondEntry; -} - -/** - Removes a node from a doubly-linked list, and returns the node that follows - the removed node. - - Removes the node Entry from a doubly-linked list. It is up to the caller of - this function to release the memory used by this node if that is required. On - exit, the node following Entry in the doubly-linked list is returned. If - Entry is the only node in the linked list, then the head node of the linked - list is returned. - - If Entry is NULL, then ASSERT(). - If Entry is the head node of an empty list, then ASSERT(). - If PcdMaximumLinkedListLength is not zero, and the number of nodes in the - linked list containing Entry, including the Entry node, is greater than - or equal to PcdMaximumLinkedListLength, then ASSERT(). - - @param Entry A pointer to a node in a linked list. - - @return Entry. - -**/ -LIST_ENTRY * -EFIAPI -RemoveEntryList ( - IN CONST LIST_ENTRY *Entry - ) -{ - ASSERT (!IsListEmpty (Entry)); - - Entry->ForwardLink->BackLink = Entry->BackLink; - Entry->BackLink->ForwardLink = Entry->ForwardLink; - return Entry->ForwardLink; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c b/MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c deleted file mode 100644 index fec7056e92f..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LongJump.c +++ /dev/null @@ -1,46 +0,0 @@ -/** @file - Long Jump functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - -#include -#include -#include -#include -#include - -/** - Restores the CPU context that was saved with SetJump(). - - Restores the CPU context from the buffer specified by JumpBuffer. This - function never returns to the caller. Instead is resumes execution based on - the state of JumpBuffer. - - If JumpBuffer is NULL, then ASSERT(). - For Itanium processors, if JumpBuffer is not aligned on a 16-byte boundary, then ASSERT(). - If Value is 0, then ASSERT(). - - @param JumpBuffer A pointer to CPU context buffer. - @param Value The value to return when the SetJump() context is - restored and must be non-zero. - -**/ -VOID -EFIAPI -LongJump ( - IN BASE_LIBRARY_JUMP_BUFFER *JumpBuffer, - IN UINTN Value - ) -{ - jmp_buf local_buf; - jmp_buf *buf; - - buf = *(VOID **)JumpBuffer; - memcpy (&local_buf, buf, sizeof(jmp_buf)); - free (buf); - longjmp (local_buf, (int)Value); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c b/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c deleted file mode 100644 index bb7f49df29c..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet32.c +++ /dev/null @@ -1,40 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the bit position of the lowest bit set in a 32-bit value. - - This function computes the bit position of the lowest bit set in the 32-bit - value specified by Operand. If Operand is zero, then -1 is returned. - Otherwise, a value between 0 and 31 is returned. - - @param Operand The 32-bit operand to evaluate. - - @retval 0..31 The lowest bit set in Operand was found. - @retval -1 Operand is zero. - -**/ -INTN -EFIAPI -LowBitSet32 ( - IN UINT32 Operand - ) -{ - INTN BitIndex; - - if (Operand == 0) { - return -1; - } - - for (BitIndex = 0; 0 == (Operand & 1); BitIndex++, Operand >>= 1); - return BitIndex; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c b/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c deleted file mode 100644 index 860670f130f..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/LowBitSet64.c +++ /dev/null @@ -1,43 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the bit position of the lowest bit set in a 64-bit value. - - This function computes the bit position of the lowest bit set in the 64-bit - value specified by Operand. If Operand is zero, then -1 is returned. - Otherwise, a value between 0 and 63 is returned. - - @param Operand The 64-bit operand to evaluate. - - @retval 0..63 The lowest bit set in Operand was found. - @retval -1 Operand is zero. - - -**/ -INTN -EFIAPI -LowBitSet64 ( - IN UINT64 Operand - ) -{ - INTN BitIndex; - - if (Operand == 0) { - return -1; - } - - for (BitIndex = 0; - (Operand & 1) == 0; - BitIndex++, Operand = RShiftU64 (Operand, 1)); - return BitIndex; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Math64.c b/MdePkg/Test/HostLibrary/BaseLibHost/Math64.c deleted file mode 100644 index 7308dec22bf..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Math64.c +++ /dev/null @@ -1,364 +0,0 @@ -/** @file - Leaf math worker functions that require 64-bit arithmetic support from the - compiler. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Shifts a 64-bit integer left between 0 and 63 bits. The low bits - are filled with zeros. The shifted value is returned. - - This function shifts the 64-bit value Operand to the left by Count bits. The - low Count bits are set to zero. The shifted value is returned. - - @param Operand The 64-bit operand to shift left. - @param Count The number of bits to shift left. - - @return Operand << Count. - -**/ -UINT64 -EFIAPI -InternalMathLShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - return Operand << Count; -} - -/** - Shifts a 64-bit integer right between 0 and 63 bits. This high bits - are filled with zeros. The shifted value is returned. - - This function shifts the 64-bit value Operand to the right by Count bits. The - high Count bits are set to zero. The shifted value is returned. - - @param Operand The 64-bit operand to shift right. - @param Count The number of bits to shift right. - - @return Operand >> Count. - -**/ -UINT64 -EFIAPI -InternalMathRShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - return Operand >> Count; -} - -/** - Shifts a 64-bit integer right between 0 and 63 bits. The high bits - are filled with original integer's bit 63. The shifted value is returned. - - This function shifts the 64-bit value Operand to the right by Count bits. The - high Count bits are set to bit 63 of Operand. The shifted value is returned. - - @param Operand The 64-bit operand to shift right. - @param Count The number of bits to shift right. - - @return Operand arithmetically shifted right by Count. - -**/ -UINT64 -EFIAPI -InternalMathARShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - INTN TestValue; - - // - // Test if this compiler supports arithmetic shift - // - TestValue = (INTN)((INT64)(1ULL << 63) >> 63); - if (TestValue == -1) { - // - // Arithmetic shift is supported - // - return (UINT64)((INT64)Operand >> Count); - } - - // - // Arithmetic is not supported - // - return (Operand >> Count) | - ((INTN)Operand < 0 ? ~((UINTN)-1 >> Count) : 0); -} - - -/** - Rotates a 64-bit integer left between 0 and 63 bits, filling - the low bits with the high bits that were rotated. - - This function rotates the 64-bit value Operand to the left by Count bits. The - low Count bits are fill with the high Count bits of Operand. The rotated - value is returned. - - @param Operand The 64-bit operand to rotate left. - @param Count The number of bits to rotate left. - - @return Operand <<< Count. - -**/ -UINT64 -EFIAPI -InternalMathLRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - return (Operand << Count) | (Operand >> (64 - Count)); -} - -/** - Rotates a 64-bit integer right between 0 and 63 bits, filling - the high bits with the high low bits that were rotated. - - This function rotates the 64-bit value Operand to the right by Count bits. - The high Count bits are fill with the low Count bits of Operand. The rotated - value is returned. - - @param Operand The 64-bit operand to rotate right. - @param Count The number of bits to rotate right. - - @return Operand >>> Count. - -**/ -UINT64 -EFIAPI -InternalMathRRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - return (Operand >> Count) | (Operand << (64 - Count)); -} - -/** - Switches the endianess of a 64-bit integer. - - This function swaps the bytes in a 64-bit unsigned value to switch the value - from little endian to big endian or vice versa. The byte swapped value is - returned. - - @param Operand A 64-bit unsigned value. - - @return The byte swapped Operand. - -**/ -UINT64 -EFIAPI -InternalMathSwapBytes64 ( - IN UINT64 Operand - ) -{ - UINT64 LowerBytes; - UINT64 HigherBytes; - - LowerBytes = (UINT64) SwapBytes32 ((UINT32) Operand); - HigherBytes = (UINT64) SwapBytes32 ((UINT32) (Operand >> 32)); - - return (LowerBytes << 32 | HigherBytes); -} - -/** - Multiplies a 64-bit unsigned integer by a 32-bit unsigned integer - and generates a 64-bit unsigned result. - - This function multiplies the 64-bit unsigned value Multiplicand by the 32-bit - unsigned value Multiplier and generates a 64-bit unsigned result. This 64- - bit unsigned result is returned. - - @param Multiplicand A 64-bit unsigned value. - @param Multiplier A 32-bit unsigned value. - - @return Multiplicand * Multiplier - -**/ -UINT64 -EFIAPI -InternalMathMultU64x32 ( - IN UINT64 Multiplicand, - IN UINT32 Multiplier - ) -{ - return Multiplicand * Multiplier; -} - - -/** - Multiplies a 64-bit unsigned integer by a 64-bit unsigned integer - and generates a 64-bit unsigned result. - - This function multiplies the 64-bit unsigned value Multiplicand by the 64-bit - unsigned value Multiplier and generates a 64-bit unsigned result. This 64- - bit unsigned result is returned. - - @param Multiplicand A 64-bit unsigned value. - @param Multiplier A 64-bit unsigned value. - - @return Multiplicand * Multiplier. - -**/ -UINT64 -EFIAPI -InternalMathMultU64x64 ( - IN UINT64 Multiplicand, - IN UINT64 Multiplier - ) -{ - return Multiplicand * Multiplier; -} - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and - generates a 64-bit unsigned result. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. This - function returns the 64-bit unsigned quotient. - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - - @return Dividend / Divisor. - -**/ -UINT64 -EFIAPI -InternalMathDivU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ) -{ - return Dividend / Divisor; -} - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and - generates a 32-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 32-bit remainder. This function - returns the 32-bit unsigned remainder. - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - - @return Dividend % Divisor. - -**/ -UINT32 -EFIAPI -InternalMathModU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ) -{ - return (UINT32)(Dividend % Divisor); -} - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and - generates a 64-bit unsigned result and an optional 32-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder - is not NULL, then the 32-bit unsigned remainder is returned in Remainder. - This function returns the 64-bit unsigned quotient. - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - @param Remainder A pointer to a 32-bit unsigned value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor. - -**/ -UINT64 -EFIAPI -InternalMathDivRemU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor, - OUT UINT32 *Remainder OPTIONAL - ) -{ - if (Remainder != NULL) { - *Remainder = (UINT32)(Dividend % Divisor); - } - return Dividend / Divisor; -} - -/** - Divides a 64-bit unsigned integer by a 64-bit unsigned integer and - generates a 64-bit unsigned result and an optional 64-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 64-bit - unsigned value Divisor and generates a 64-bit unsigned quotient. If Remainder - is not NULL, then the 64-bit unsigned remainder is returned in Remainder. - This function returns the 64-bit unsigned quotient. - - @param Dividend A 64-bit unsigned value. - @param Divisor A 64-bit unsigned value. - @param Remainder A pointer to a 64-bit unsigned value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor - -**/ -UINT64 -EFIAPI -InternalMathDivRemU64x64 ( - IN UINT64 Dividend, - IN UINT64 Divisor, - OUT UINT64 *Remainder OPTIONAL - ) -{ - if (Remainder != NULL) { - *Remainder = Dividend % Divisor; - } - return Dividend / Divisor; -} - -/** - Divides a 64-bit signed integer by a 64-bit signed integer and - generates a 64-bit signed result and an optional 64-bit signed remainder. - - This function divides the 64-bit signed value Dividend by the 64-bit - signed value Divisor and generates a 64-bit signed quotient. If Remainder - is not NULL, then the 64-bit signed remainder is returned in Remainder. - This function returns the 64-bit signed quotient. - - @param Dividend A 64-bit signed value. - @param Divisor A 64-bit signed value. - @param Remainder A pointer to a 64-bit signed value. This parameter is - optional and may be NULL. - - @return Dividend / Divisor. - -**/ -INT64 -EFIAPI -InternalMathDivRemS64x64 ( - IN INT64 Dividend, - IN INT64 Divisor, - OUT INT64 *Remainder OPTIONAL - ) -{ - if (Remainder != NULL) { - *Remainder = Dividend % Divisor; - } - return Dividend / Divisor; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c deleted file mode 100644 index b64a1fc4f37..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/ModU64x32.c +++ /dev/null @@ -1,45 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT32 -EFIAPI -InternalMathModU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ); - -/** - Divides a 64-bit unsigned integer by a 32-bit unsigned integer and generates - a 32-bit unsigned remainder. - - This function divides the 64-bit unsigned value Dividend by the 32-bit - unsigned value Divisor and generates a 32-bit remainder. This function - returns the 32-bit unsigned remainder. - - If Divisor is 0, then ASSERT(). - - @param Dividend A 64-bit unsigned value. - @param Divisor A 32-bit unsigned value. - - @return Dividend % Divisor. - -**/ -UINT32 -EFIAPI -ModU64x32 ( - IN UINT64 Dividend, - IN UINT32 Divisor - ) -{ - ASSERT (Divisor != 0); - return InternalMathModU64x32 (Dividend, Divisor); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c deleted file mode 100644 index a64790fb150..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/MultS64x64.c +++ /dev/null @@ -1,35 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Multiplies a 64-bit signed integer by a 64-bit signed integer and generates a - 64-bit signed result. - - This function multiplies the 64-bit signed value Multiplicand by the 64-bit - signed value Multiplier and generates a 64-bit signed result. This 64-bit - signed result is returned. - - @param Multiplicand A 64-bit signed value. - @param Multiplier A 64-bit signed value. - - @return Multiplicand * Multiplier. - -**/ -INT64 -EFIAPI -MultS64x64 ( - IN INT64 Multiplicand, - IN INT64 Multiplier - ) -{ - return (INT64)MultU64x64 ((UINT64) Multiplicand, (UINT64) Multiplier); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c deleted file mode 100644 index ba56b3a0e70..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x32.c +++ /dev/null @@ -1,46 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathMultU64x32 ( - IN UINT64 Multiplicand, - IN UINT32 Multiplier - ); - -/** - Multiplies a 64-bit unsigned integer by a 32-bit unsigned integer and - generates a 64-bit unsigned result. - - This function multiplies the 64-bit unsigned value Multiplicand by the 32-bit - unsigned value Multiplier and generates a 64-bit unsigned result. This 64- - bit unsigned result is returned. - - @param Multiplicand A 64-bit unsigned value. - @param Multiplier A 32-bit unsigned value. - - @return Multiplicand * Multiplier. - -**/ -UINT64 -EFIAPI -MultU64x32 ( - IN UINT64 Multiplicand, - IN UINT32 Multiplier - ) -{ - UINT64 Result; - - Result = InternalMathMultU64x32 (Multiplicand, Multiplier); - - return Result; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c b/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c deleted file mode 100644 index 0d30efea869..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/MultU64x64.c +++ /dev/null @@ -1,46 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathMultU64x64 ( - IN UINT64 Multiplicand, - IN UINT64 Multiplier - ); - -/** - Multiplies a 64-bit unsigned integer by a 64-bit unsigned integer and - generates a 64-bit unsigned result. - - This function multiplies the 64-bit unsigned value Multiplicand by the 64-bit - unsigned value Multiplier and generates a 64-bit unsigned result. This 64- - bit unsigned result is returned. - - @param Multiplicand A 64-bit unsigned value. - @param Multiplier A 64-bit unsigned value. - - @return Multiplicand * Multiplier. - -**/ -UINT64 -EFIAPI -MultU64x64 ( - IN UINT64 Multiplicand, - IN UINT64 Multiplier - ) -{ - UINT64 Result; - - Result = InternalMathMultU64x64 (Multiplicand, Multiplier); - - return Result; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c b/MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c deleted file mode 100644 index 8dddf95c09a..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/RRotU32.c +++ /dev/null @@ -1,38 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Rotates a 32-bit integer right between 0 and 31 bits, filling the high bits - with the low bits that were rotated. - - This function rotates the 32-bit value Operand to the right by Count bits. - The high Count bits are fill with the low Count bits of Operand. The rotated - value is returned. - - If Count is greater than 31, then ASSERT(). - - @param Operand The 32-bit operand to rotate right. - @param Count The number of bits to rotate right. - - @return Operand >> Count. - -**/ -UINT32 -EFIAPI -RRotU32 ( - IN UINT32 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 32); - return (Operand >> Count) | (Operand << (32 - Count)); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c deleted file mode 100644 index 88fe7622153..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/RRotU64.c +++ /dev/null @@ -1,45 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathRRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ); - -/** - Rotates a 64-bit integer right between 0 and 63 bits, filling the high bits - with the high low bits that were rotated. - - This function rotates the 64-bit value Operand to the right by Count bits. - The high Count bits are fill with the low Count bits of Operand. The rotated - value is returned. - - If Count is greater than 63, then ASSERT(). - - @param Operand The 64-bit operand to rotate right. - @param Count The number of bits to rotate right. - - @return Operand >> Count. - -**/ -UINT64 -EFIAPI -RRotU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 64); - return InternalMathRRotU64 (Operand, Count); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c b/MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c deleted file mode 100644 index 0a081b31208..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/RShiftU64.c +++ /dev/null @@ -1,44 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -UINT64 -EFIAPI -InternalMathRShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ); - -/** - Shifts a 64-bit integer right between 0 and 63 bits. This high bits are - filled with zeros. The shifted value is returned. - - This function shifts the 64-bit value Operand to the right by Count bits. The - high Count bits are set to zero. The shifted value is returned. - - If Count is greater than 63, then ASSERT(). - - @param Operand The 64-bit operand to shift right. - @param Count The number of bits to shift right. - - @return Operand >> Count. - -**/ -UINT64 -EFIAPI -RShiftU64 ( - IN UINT64 Operand, - IN UINTN Count - ) -{ - ASSERT (Count < 64); - return InternalMathRShiftU64 (Operand, Count); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c b/MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c deleted file mode 100644 index 954cf2cf22b..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SafeString.c +++ /dev/null @@ -1,3693 +0,0 @@ -/** @file - Safe String functions. - - Copyright (c) 2014 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include - -#ifndef RSIZE_MAX -#define RSIZE_MAX (0x1000000) -#endif - -#ifndef ASCII_RSIZE_MAX -#define ASCII_RSIZE_MAX (0x1000000) -#endif - -#define SAFE_STRING_CONSTRAINT_CHECK(Expression, Status) \ - do { \ - ASSERT (Expression); \ - if (!(Expression)) { \ - return Status; \ - } \ - } while (FALSE) - -BOOLEAN -EFIAPI -InternalIsDecimalDigitCharacter ( - IN CHAR16 Char - ); -CHAR16 -EFIAPI -InternalCharToUpper ( - IN CHAR16 Char - ); -BOOLEAN -EFIAPI -InternalIsHexaDecimalDigitCharacter ( - IN CHAR16 Char - ); -UINTN -EFIAPI -InternalHexCharToUintn ( - IN CHAR16 Char - ); -BOOLEAN -EFIAPI -InternalAsciiIsDecimalDigitCharacter ( - IN CHAR8 Char - ); -CHAR8 -EFIAPI -InternalBaseLibAsciiToUpper ( - IN CHAR8 Chr - ); -BOOLEAN -EFIAPI -InternalAsciiIsHexaDecimalDigitCharacter ( - IN CHAR8 Char - ); -UINTN -EFIAPI -InternalAsciiHexCharToUintn ( - IN CHAR8 Char - ); - - -/** - Returns if 2 memory blocks are overlapped. - - @param Base1 Base address of 1st memory block. - @param Size1 Size of 1st memory block. - @param Base2 Base address of 2nd memory block. - @param Size2 Size of 2nd memory block. - - @retval TRUE 2 memory blocks are overlapped. - @retval FALSE 2 memory blocks are not overlapped. -**/ -BOOLEAN -InternalSafeStringIsOverlap ( - IN VOID *Base1, - IN UINTN Size1, - IN VOID *Base2, - IN UINTN Size2 - ) -{ - if ((((UINTN)Base1 >= (UINTN)Base2) && ((UINTN)Base1 < (UINTN)Base2 + Size2)) || - (((UINTN)Base2 >= (UINTN)Base1) && ((UINTN)Base2 < (UINTN)Base1 + Size1))) { - return TRUE; - } - return FALSE; -} - -/** - Returns if 2 Unicode strings are not overlapped. - - @param Str1 Start address of 1st Unicode string. - @param Size1 The number of char in 1st Unicode string, - including terminating null char. - @param Str2 Start address of 2nd Unicode string. - @param Size2 The number of char in 2nd Unicode string, - including terminating null char. - - @retval TRUE 2 Unicode strings are NOT overlapped. - @retval FALSE 2 Unicode strings are overlapped. -**/ -BOOLEAN -InternalSafeStringNoStrOverlap ( - IN CHAR16 *Str1, - IN UINTN Size1, - IN CHAR16 *Str2, - IN UINTN Size2 - ) -{ - return !InternalSafeStringIsOverlap (Str1, Size1 * sizeof(CHAR16), Str2, Size2 * sizeof(CHAR16)); -} - -/** - Returns if 2 Ascii strings are not overlapped. - - @param Str1 Start address of 1st Ascii string. - @param Size1 The number of char in 1st Ascii string, - including terminating null char. - @param Str2 Start address of 2nd Ascii string. - @param Size2 The number of char in 2nd Ascii string, - including terminating null char. - - @retval TRUE 2 Ascii strings are NOT overlapped. - @retval FALSE 2 Ascii strings are overlapped. -**/ -BOOLEAN -InternalSafeStringNoAsciiStrOverlap ( - IN CHAR8 *Str1, - IN UINTN Size1, - IN CHAR8 *Str2, - IN UINTN Size2 - ) -{ - return !InternalSafeStringIsOverlap (Str1, Size1, Str2, Size2); -} - -/** - Returns the length of a Null-terminated Unicode string. - - This function is similar as strlen_s defined in C11. - - If String is not aligned on a 16-bit boundary, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - @param MaxSize The maximum number of Destination Unicode - char, including terminating null char. - - @retval 0 If String is NULL. - @retval MaxSize If there is no null character in the first MaxSize characters of String. - @return The number of characters that percede the terminating null character. - -**/ -UINTN -EFIAPI -StrnLenS ( - IN CONST CHAR16 *String, - IN UINTN MaxSize - ) -{ - UINTN Length; - - ASSERT (((UINTN) String & BIT0) == 0); - - // - // If String is a null pointer or MaxSize is 0, then the StrnLenS function returns zero. - // - if ((String == NULL) || (MaxSize == 0)) { - return 0; - } - - // - // Otherwise, the StrnLenS function returns the number of characters that precede the - // terminating null character. If there is no null character in the first MaxSize characters of - // String then StrnLenS returns MaxSize. At most the first MaxSize characters of String shall - // be accessed by StrnLenS. - // - Length = 0; - while (String[Length] != 0) { - if (Length >= MaxSize - 1) { - return MaxSize; - } - Length++; - } - return Length; -} - -/** - Returns the size of a Null-terminated Unicode string in bytes, including the - Null terminator. - - This function returns the size of the Null-terminated Unicode string - specified by String in bytes, including the Null terminator. - - If String is not aligned on a 16-bit boundary, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - @param MaxSize The maximum number of Destination Unicode - char, including the Null terminator. - - @retval 0 If String is NULL. - @retval (sizeof (CHAR16) * (MaxSize + 1)) - If there is no Null terminator in the first MaxSize characters of - String. - @return The size of the Null-terminated Unicode string in bytes, including - the Null terminator. - -**/ -UINTN -EFIAPI -StrnSizeS ( - IN CONST CHAR16 *String, - IN UINTN MaxSize - ) -{ - // - // If String is a null pointer, then the StrnSizeS function returns zero. - // - if (String == NULL) { - return 0; - } - - // - // Otherwise, the StrnSizeS function returns the size of the Null-terminated - // Unicode string in bytes, including the Null terminator. If there is no - // Null terminator in the first MaxSize characters of String, then StrnSizeS - // returns (sizeof (CHAR16) * (MaxSize + 1)) to keep a consistent map with - // the StrnLenS function. - // - return (StrnLenS (String, MaxSize) + 1) * sizeof (*String); -} - -/** - Copies the string pointed to by Source (including the terminating null char) - to the array pointed to by Destination. - - This function is similar as strcpy_s defined in C11. - - If Destination is not aligned on a 16-bit boundary, then ASSERT(). - If Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode - char, including terminating null char. - @param Source A pointer to a Null-terminated Unicode string. - - @retval RETURN_SUCCESS String is copied. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -StrCpyS ( - OUT CHAR16 *Destination, - IN UINTN DestMax, - IN CONST CHAR16 *Source - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. DestMax shall be greater than StrnLenS(Source, DestMax). - // - SourceLen = StrnLenS (Source, DestMax); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 5. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The StrCpyS function copies the string pointed to by Source (including the terminating - // null character) into the array pointed to by Destination. - // - while (*Source != 0) { - *(Destination++) = *(Source++); - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Copies not more than Length successive char from the string pointed to by - Source to the array pointed to by Destination. If no null char is copied from - Source, then Destination[Length] is always set to null. - - This function is similar as strncpy_s defined in C11. - - If Length > 0 and Destination is not aligned on a 16-bit boundary, then ASSERT(). - If Length > 0 and Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode - char, including terminating null char. - @param Source A pointer to a Null-terminated Unicode string. - @param Length The maximum number of Unicode characters to copy. - - @retval RETURN_SUCCESS String is copied. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than - MIN(StrLen(Source), Length). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -StrnCpyS ( - OUT CHAR16 *Destination, - IN UINTN DestMax, - IN CONST CHAR16 *Source, - IN UINTN Length - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither DestMax nor Length shall be greater than RSIZE_MAX - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. If Length is not less than DestMax, then DestMax shall be greater than StrnLenS(Source, DestMax). - // - SourceLen = StrnLenS (Source, MIN (DestMax, Length)); - if (Length >= DestMax) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 5. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The StrnCpyS function copies not more than Length successive characters (characters that - // follow a null character are not copied) from the array pointed to by Source to the array - // pointed to by Destination. If no null character was copied from Source, then Destination[Length] is set to a null - // character. - // - while ((SourceLen > 0) && (*Source != 0)) { - *(Destination++) = *(Source++); - SourceLen--; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Appends a copy of the string pointed to by Source (including the terminating - null char) to the end of the string pointed to by Destination. - - This function is similar as strcat_s defined in C11. - - If Destination is not aligned on a 16-bit boundary, then ASSERT(). - If Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode - char, including terminating null char. - @param Source A pointer to a Null-terminated Unicode string. - - @retval RETURN_SUCCESS String is appended. - @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than - StrLen(Destination). - @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT - greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -StrCatS ( - IN OUT CHAR16 *Destination, - IN UINTN DestMax, - IN CONST CHAR16 *Source - ) -{ - UINTN DestLen; - UINTN CopyLen; - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // Let CopyLen denote the value DestMax - StrnLenS(Destination, DestMax) upon entry to StrCatS. - // - DestLen = StrnLenS (Destination, DestMax); - CopyLen = DestMax - DestLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. CopyLen shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); - - // - // 5. CopyLen shall be greater than StrnLenS(Source, CopyLen). - // - SourceLen = StrnLenS (Source, CopyLen); - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 6. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The StrCatS function appends a copy of the string pointed to by Source (including the - // terminating null character) to the end of the string pointed to by Destination. The initial character - // from Source overwrites the null character at the end of Destination. - // - Destination = Destination + DestLen; - while (*Source != 0) { - *(Destination++) = *(Source++); - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Appends not more than Length successive char from the string pointed to by - Source to the end of the string pointed to by Destination. If no null char is - copied from Source, then Destination[StrLen(Destination) + Length] is always - set to null. - - This function is similar as strncat_s defined in C11. - - If Destination is not aligned on a 16-bit boundary, then ASSERT(). - If Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode - char, including terminating null char. - @param Source A pointer to a Null-terminated Unicode string. - @param Length The maximum number of Unicode characters to copy. - - @retval RETURN_SUCCESS String is appended. - @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than - StrLen(Destination). - @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT - greater than MIN(StrLen(Source), Length). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -StrnCatS ( - IN OUT CHAR16 *Destination, - IN UINTN DestMax, - IN CONST CHAR16 *Source, - IN UINTN Length - ) -{ - UINTN DestLen; - UINTN CopyLen; - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // Let CopyLen denote the value DestMax - StrnLenS(Destination, DestMax) upon entry to StrnCatS. - // - DestLen = StrnLenS (Destination, DestMax); - CopyLen = DestMax - DestLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither DestMax nor Length shall be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. CopyLen shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); - - // - // 5. If Length is not less than CopyLen, then CopyLen shall be greater than StrnLenS(Source, CopyLen). - // - SourceLen = StrnLenS (Source, MIN (CopyLen, Length)); - if (Length >= CopyLen) { - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 6. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoStrOverlap (Destination, DestMax, (CHAR16 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The StrnCatS function appends not more than Length successive characters (characters - // that follow a null character are not copied) from the array pointed to by Source to the end of - // the string pointed to by Destination. The initial character from Source overwrites the null character at - // the end of Destination. If no null character was copied from Source, then Destination[DestMax-CopyLen+Length] is set to - // a null character. - // - Destination = Destination + DestLen; - while ((SourceLen > 0) && (*Source != 0)) { - *(Destination++) = *(Source++); - SourceLen--; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode decimal string to a value of type UINTN. - - This function outputs a value of type UINTN by interpreting the contents of - the Unicode string specified by String as a decimal number. The format of the - input Unicode string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before - [decimal digits]. The running zero in the beginning of [decimal digits] will - be ignored. Then, the function stops at the first character that is a not a - valid decimal character or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid decimal digits in the above format, then 0 is stored - at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINTN, then - MAX_UINTN is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - decimal digits right after the optional pad spaces, the value of String is - stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumUnicodeStringLength is not - zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINTN. - -**/ -RETURN_STATUS -EFIAPI -StrDecimalToUintnS ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT UINTN *Data - ) -{ - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == L' ') || (*String == L'\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == L'0') { - String++; - } - - *Data = 0; - - while (InternalIsDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINTN, then MAX_UINTN is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > ((MAX_UINTN - (*String - L'0')) / 10)) { - *Data = MAX_UINTN; - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = *Data * 10 + (*String - L'0'); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode decimal string to a value of type UINT64. - - This function outputs a value of type UINT64 by interpreting the contents of - the Unicode string specified by String as a decimal number. The format of the - input Unicode string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before - [decimal digits]. The running zero in the beginning of [decimal digits] will - be ignored. Then, the function stops at the first character that is a not a - valid decimal character or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid decimal digits in the above format, then 0 is stored - at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINT64, then - MAX_UINT64 is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - decimal digits right after the optional pad spaces, the value of String is - stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumUnicodeStringLength is not - zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINT64. - -**/ -RETURN_STATUS -EFIAPI -StrDecimalToUint64S ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT UINT64 *Data - ) -{ - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == L' ') || (*String == L'\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == L'0') { - String++; - } - - *Data = 0; - - while (InternalIsDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINT64, then MAX_UINT64 is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > DivU64x32 (MAX_UINT64 - (*String - L'0'), 10)) { - *Data = MAX_UINT64; - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = MultU64x32 (*Data, 10) + (*String - L'0'); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode hexadecimal string to a value of type - UINTN. - - This function outputs a value of type UINTN by interpreting the contents of - the Unicode string specified by String as a hexadecimal number. The format of - the input Unicode string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. - If "x" appears in the input string, it must be prefixed with at least one 0. - The function will ignore the pad space, which includes spaces or tab - characters, before [zeros], [x] or [hexadecimal digit]. The running zero - before [x] or [hexadecimal digit] will be ignored. Then, the decoding starts - after [x] or the first valid hexadecimal digit. Then, the function stops at - the first character that is a not a valid hexadecimal character or NULL, - whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid hexadecimal digits in the above format, then 0 is - stored at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINTN, then - MAX_UINTN is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - hexadecimal digits right after the optional pad spaces, the value of String - is stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumUnicodeStringLength is not - zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINTN. - -**/ -RETURN_STATUS -EFIAPI -StrHexToUintnS ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT UINTN *Data - ) -{ - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == L' ') || (*String == L'\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == L'0') { - String++; - } - - if (InternalCharToUpper (*String) == L'X') { - if (*(String - 1) != L'0') { - *Data = 0; - return RETURN_SUCCESS; - } - // - // Skip the 'X' - // - String++; - } - - *Data = 0; - - while (InternalIsHexaDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINTN, then MAX_UINTN is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > ((MAX_UINTN - InternalHexCharToUintn (*String)) >> 4)) { - *Data = MAX_UINTN; - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = (*Data << 4) + InternalHexCharToUintn (*String); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode hexadecimal string to a value of type - UINT64. - - This function outputs a value of type UINT64 by interpreting the contents of - the Unicode string specified by String as a hexadecimal number. The format of - the input Unicode string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. - If "x" appears in the input string, it must be prefixed with at least one 0. - The function will ignore the pad space, which includes spaces or tab - characters, before [zeros], [x] or [hexadecimal digit]. The running zero - before [x] or [hexadecimal digit] will be ignored. Then, the decoding starts - after [x] or the first valid hexadecimal digit. Then, the function stops at - the first character that is a not a valid hexadecimal character or NULL, - whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid hexadecimal digits in the above format, then 0 is - stored at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINT64, then - MAX_UINT64 is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - hexadecimal digits right after the optional pad spaces, the value of String - is stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumUnicodeStringLength is not - zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINT64. - -**/ -RETURN_STATUS -EFIAPI -StrHexToUint64S ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT UINT64 *Data - ) -{ - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((StrnLenS (String, RSIZE_MAX + 1) <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == L' ') || (*String == L'\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == L'0') { - String++; - } - - if (InternalCharToUpper (*String) == L'X') { - if (*(String - 1) != L'0') { - *Data = 0; - return RETURN_SUCCESS; - } - // - // Skip the 'X' - // - String++; - } - - *Data = 0; - - while (InternalIsHexaDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINT64, then MAX_UINT64 is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > RShiftU64 (MAX_UINT64 - InternalHexCharToUintn (*String), 4)) { - *Data = MAX_UINT64; - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = LShiftU64 (*Data, 4) + InternalHexCharToUintn (*String); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode string to IPv6 address and prefix length. - - This function outputs a value of type IPv6_ADDRESS and may output a value - of type UINT8 by interpreting the contents of the Unicode string specified - by String. The format of the input Unicode string String is as follows: - - X:X:X:X:X:X:X:X[/P] - - X contains one to four hexadecimal digit characters in the range [0-9], [a-f] and - [A-F]. X is converted to a value of type UINT16, whose low byte is stored in low - memory address and high byte is stored in high memory address. P contains decimal - digit characters in the range [0-9]. The running zero in the beginning of P will - be ignored. /P is optional. - - When /P is not in the String, the function stops at the first character that is - not a valid hexadecimal digit character after eight X's are converted. - - When /P is in the String, the function stops at the first character that is not - a valid decimal digit character after P is converted. - - "::" can be used to compress one or more groups of X when X contains only 0. - The "::" can only appear once in the String. - - If String is NULL, then ASSERT(). - - If Address is NULL, then ASSERT(). - - If String is not aligned in a 16-bit boundary, then ASSERT(). - - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If EndPointer is not NULL and Address is translated from String, a pointer - to the character that stopped the scan is stored at the location pointed to - by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Address Pointer to the converted IPv6 address. - @param PrefixLength Pointer to the converted IPv6 address prefix - length. MAX_UINT8 is returned when /P is - not in the String. - - @retval RETURN_SUCCESS Address is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If X contains more than four hexadecimal - digit characters. - If String contains "::" and number of X - is not less than 8. - If P starts with character that is not a - valid decimal digit character. - If the decimal number converted from P - exceeds 128. - -**/ -RETURN_STATUS -EFIAPI -StrToIpv6Address ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT IPv6_ADDRESS *Address, - OUT UINT8 *PrefixLength OPTIONAL - ) -{ - RETURN_STATUS Status; - UINTN AddressIndex; - UINTN Uintn; - IPv6_ADDRESS LocalAddress; - UINT8 LocalPrefixLength; - CONST CHAR16 *Pointer; - CHAR16 *End; - UINTN CompressStart; - BOOLEAN ExpectPrefix; - - LocalPrefixLength = MAX_UINT8; - CompressStart = ARRAY_SIZE (Address->Addr); - ExpectPrefix = FALSE; - - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. None of String or Guid shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); - - for (Pointer = String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { - if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) { - if (*Pointer != L':') { - // - // ":" or "/" should be followed by digit characters. - // - return RETURN_UNSUPPORTED; - } - - // - // Meet second ":" after previous ":" or "/" - // or meet first ":" in the beginning of String. - // - if (ExpectPrefix) { - // - // ":" shall not be after "/" - // - return RETURN_UNSUPPORTED; - } - - if (CompressStart != ARRAY_SIZE (Address->Addr) || AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // "::" can only appear once. - // "::" can only appear when address is not full length. - // - return RETURN_UNSUPPORTED; - } else { - // - // Remember the start of zero compressing. - // - CompressStart = AddressIndex; - Pointer++; - - if (CompressStart == 0) { - if (*Pointer != L':') { - // - // Single ":" shall not be in the beginning of String. - // - return RETURN_UNSUPPORTED; - } - Pointer++; - } - } - } - - if (!InternalIsHexaDecimalDigitCharacter (*Pointer)) { - if (*Pointer == L'/') { - // - // Might be optional "/P" after "::". - // - if (CompressStart != AddressIndex) { - return RETURN_UNSUPPORTED; - } - } else { - break; - } - } else { - if (!ExpectPrefix) { - // - // Get X. - // - Status = StrHexToUintnS (Pointer, &End, &Uintn); - if (RETURN_ERROR (Status) || End - Pointer > 4) { - // - // Number of hexadecimal digit characters is no more than 4. - // - return RETURN_UNSUPPORTED; - } - Pointer = End; - // - // Uintn won't exceed MAX_UINT16 if number of hexadecimal digit characters is no more than 4. - // - ASSERT (AddressIndex + 1 < ARRAY_SIZE (Address->Addr)); - LocalAddress.Addr[AddressIndex] = (UINT8) ((UINT16) Uintn >> 8); - LocalAddress.Addr[AddressIndex + 1] = (UINT8) Uintn; - AddressIndex += 2; - } else { - // - // Get P, then exit the loop. - // - Status = StrDecimalToUintnS (Pointer, &End, &Uintn); - if (RETURN_ERROR (Status) || End == Pointer || Uintn > 128) { - // - // Prefix length should not exceed 128. - // - return RETURN_UNSUPPORTED; - } - LocalPrefixLength = (UINT8) Uintn; - Pointer = End; - break; - } - } - - // - // Skip ':' or "/" - // - if (*Pointer == L'/') { - ExpectPrefix = TRUE; - } else if (*Pointer == L':') { - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // Meet additional ":" after all 8 16-bit address - // - break; - } - } else { - // - // Meet other character that is not "/" or ":" after all 8 16-bit address - // - break; - } - Pointer++; - } - - if ((AddressIndex == ARRAY_SIZE (Address->Addr) && CompressStart != ARRAY_SIZE (Address->Addr)) || - (AddressIndex != ARRAY_SIZE (Address->Addr) && CompressStart == ARRAY_SIZE (Address->Addr)) - ) { - // - // Full length of address shall not have compressing zeros. - // Non-full length of address shall have compressing zeros. - // - return RETURN_UNSUPPORTED; - } - CopyMem (&Address->Addr[0], &LocalAddress.Addr[0], CompressStart); - ZeroMem (&Address->Addr[CompressStart], ARRAY_SIZE (Address->Addr) - AddressIndex); - if (AddressIndex > CompressStart) { - CopyMem ( - &Address->Addr[CompressStart + ARRAY_SIZE (Address->Addr) - AddressIndex], - &LocalAddress.Addr[CompressStart], - AddressIndex - CompressStart - ); - } - - if (PrefixLength != NULL) { - *PrefixLength = LocalPrefixLength; - } - if (EndPointer != NULL) { - *EndPointer = (CHAR16 *) Pointer; - } - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode string to IPv4 address and prefix length. - - This function outputs a value of type IPv4_ADDRESS and may output a value - of type UINT8 by interpreting the contents of the Unicode string specified - by String. The format of the input Unicode string String is as follows: - - D.D.D.D[/P] - - D and P are decimal digit characters in the range [0-9]. The running zero in - the beginning of D and P will be ignored. /P is optional. - - When /P is not in the String, the function stops at the first character that is - not a valid decimal digit character after four D's are converted. - - When /P is in the String, the function stops at the first character that is not - a valid decimal digit character after P is converted. - - If String is NULL, then ASSERT(). - - If Address is NULL, then ASSERT(). - - If String is not aligned in a 16-bit boundary, then ASSERT(). - - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - If EndPointer is not NULL and Address is translated from String, a pointer - to the character that stopped the scan is stored at the location pointed to - by EndPointer. - - @param String Pointer to a Null-terminated Unicode string. - @param EndPointer Pointer to character that stops scan. - @param Address Pointer to the converted IPv4 address. - @param PrefixLength Pointer to the converted IPv4 address prefix - length. MAX_UINT8 is returned when /P is - not in the String. - - @retval RETURN_SUCCESS Address is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If String is not in the correct format. - If any decimal number converted from D - exceeds 255. - If the decimal number converted from P - exceeds 32. - -**/ -RETURN_STATUS -EFIAPI -StrToIpv4Address ( - IN CONST CHAR16 *String, - OUT CHAR16 **EndPointer, OPTIONAL - OUT IPv4_ADDRESS *Address, - OUT UINT8 *PrefixLength OPTIONAL - ) -{ - RETURN_STATUS Status; - UINTN AddressIndex; - UINTN Uintn; - IPv4_ADDRESS LocalAddress; - UINT8 LocalPrefixLength; - CHAR16 *Pointer; - - LocalPrefixLength = MAX_UINT8; - - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. None of String or Guid shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); - - for (Pointer = (CHAR16 *) String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { - if (!InternalIsDecimalDigitCharacter (*Pointer)) { - // - // D or P contains invalid characters. - // - break; - } - - // - // Get D or P. - // - Status = StrDecimalToUintnS ((CONST CHAR16 *) Pointer, &Pointer, &Uintn); - if (RETURN_ERROR (Status)) { - return RETURN_UNSUPPORTED; - } - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // It's P. - // - if (Uintn > 32) { - return RETURN_UNSUPPORTED; - } - LocalPrefixLength = (UINT8) Uintn; - } else { - // - // It's D. - // - if (Uintn > MAX_UINT8) { - return RETURN_UNSUPPORTED; - } - LocalAddress.Addr[AddressIndex] = (UINT8) Uintn; - AddressIndex++; - } - - // - // Check the '.' or '/', depending on the AddressIndex. - // - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - if (*Pointer == L'/') { - // - // '/P' is in the String. - // Skip "/" and get P in next loop. - // - Pointer++; - } else { - // - // '/P' is not in the String. - // - break; - } - } else if (AddressIndex < ARRAY_SIZE (Address->Addr)) { - if (*Pointer == L'.') { - // - // D should be followed by '.' - // - Pointer++; - } else { - return RETURN_UNSUPPORTED; - } - } - } - - if (AddressIndex < ARRAY_SIZE (Address->Addr)) { - return RETURN_UNSUPPORTED; - } - - CopyMem (Address, &LocalAddress, sizeof (*Address)); - if (PrefixLength != NULL) { - *PrefixLength = LocalPrefixLength; - } - if (EndPointer != NULL) { - *EndPointer = Pointer; - } - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode GUID string to a value of type - EFI_GUID. - - This function outputs a GUID value by interpreting the contents of - the Unicode string specified by String. The format of the input - Unicode string String consists of 36 characters, as follows: - - aabbccdd-eeff-gghh-iijj-kkllmmnnoopp - - The pairs aa - pp are two characters in the range [0-9], [a-f] and - [A-F], with each pair representing a single byte hexadecimal value. - - The mapping between String and the EFI_GUID structure is as follows: - aa Data1[24:31] - bb Data1[16:23] - cc Data1[8:15] - dd Data1[0:7] - ee Data2[8:15] - ff Data2[0:7] - gg Data3[8:15] - hh Data3[0:7] - ii Data4[0:7] - jj Data4[8:15] - kk Data4[16:23] - ll Data4[24:31] - mm Data4[32:39] - nn Data4[40:47] - oo Data4[48:55] - pp Data4[56:63] - - If String is NULL, then ASSERT(). - If Guid is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - - @param String Pointer to a Null-terminated Unicode string. - @param Guid Pointer to the converted GUID. - - @retval RETURN_SUCCESS Guid is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If String is not as the above format. - -**/ -RETURN_STATUS -EFIAPI -StrToGuid ( - IN CONST CHAR16 *String, - OUT GUID *Guid - ) -{ - RETURN_STATUS Status; - GUID LocalGuid; - - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. None of String or Guid shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Guid != NULL), RETURN_INVALID_PARAMETER); - - // - // Get aabbccdd in big-endian. - // - Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data1), (UINT8 *) &LocalGuid.Data1, sizeof (LocalGuid.Data1)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data1)] != L'-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data1 = SwapBytes32 (LocalGuid.Data1); - String += 2 * sizeof (LocalGuid.Data1) + 1; - - // - // Get eeff in big-endian. - // - Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data2), (UINT8 *) &LocalGuid.Data2, sizeof (LocalGuid.Data2)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data2)] != L'-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data2 = SwapBytes16 (LocalGuid.Data2); - String += 2 * sizeof (LocalGuid.Data2) + 1; - - // - // Get gghh in big-endian. - // - Status = StrHexToBytes (String, 2 * sizeof (LocalGuid.Data3), (UINT8 *) &LocalGuid.Data3, sizeof (LocalGuid.Data3)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data3)] != L'-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data3 = SwapBytes16 (LocalGuid.Data3); - String += 2 * sizeof (LocalGuid.Data3) + 1; - - // - // Get iijj. - // - Status = StrHexToBytes (String, 2 * 2, &LocalGuid.Data4[0], 2); - if (RETURN_ERROR (Status) || String[2 * 2] != L'-') { - return RETURN_UNSUPPORTED; - } - String += 2 * 2 + 1; - - // - // Get kkllmmnnoopp. - // - Status = StrHexToBytes (String, 2 * 6, &LocalGuid.Data4[2], 6); - if (RETURN_ERROR (Status)) { - return RETURN_UNSUPPORTED; - } - - CopyGuid (Guid, &LocalGuid); - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode hexadecimal string to a byte array. - - This function outputs a byte array by interpreting the contents of - the Unicode string specified by String in hexadecimal format. The format of - the input Unicode string String is: - - [XX]* - - X is a hexadecimal digit character in the range [0-9], [a-f] and [A-F]. - The function decodes every two hexadecimal digit characters as one byte. The - decoding stops after Length of characters and outputs Buffer containing - (Length / 2) bytes. - - If String is not aligned in a 16-bit boundary, then ASSERT(). - - If String is NULL, then ASSERT(). - - If Buffer is NULL, then ASSERT(). - - If Length is not multiple of 2, then ASSERT(). - - If PcdMaximumUnicodeStringLength is not zero and Length is greater than - PcdMaximumUnicodeStringLength, then ASSERT(). - - If MaxBufferSize is less than (Length / 2), then ASSERT(). - - @param String Pointer to a Null-terminated Unicode string. - @param Length The number of Unicode characters to decode. - @param Buffer Pointer to the converted bytes array. - @param MaxBufferSize The maximum size of Buffer. - - @retval RETURN_SUCCESS Buffer is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If Length is not multiple of 2. - If PcdMaximumUnicodeStringLength is not zero, - and Length is greater than - PcdMaximumUnicodeStringLength. - @retval RETURN_UNSUPPORTED If Length of characters from String contain - a character that is not valid hexadecimal - digit characters, or a Null-terminator. - @retval RETURN_BUFFER_TOO_SMALL If MaxBufferSize is less than (Length / 2). -**/ -RETURN_STATUS -EFIAPI -StrHexToBytes ( - IN CONST CHAR16 *String, - IN UINTN Length, - OUT UINT8 *Buffer, - IN UINTN MaxBufferSize - ) -{ - UINTN Index; - - ASSERT (((UINTN) String & BIT0) == 0); - - // - // 1. None of String or Buffer shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Buffer != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Length shall not be greater than RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. Length shall not be odd. - // - SAFE_STRING_CONSTRAINT_CHECK (((Length & BIT0) == 0), RETURN_INVALID_PARAMETER); - - // - // 4. MaxBufferSize shall equal to or greater than Length / 2. - // - SAFE_STRING_CONSTRAINT_CHECK ((MaxBufferSize >= Length / 2), RETURN_BUFFER_TOO_SMALL); - - // - // 5. String shall not contains invalid hexadecimal digits. - // - for (Index = 0; Index < Length; Index++) { - if (!InternalIsHexaDecimalDigitCharacter (String[Index])) { - break; - } - } - if (Index != Length) { - return RETURN_UNSUPPORTED; - } - - // - // Convert the hex string to bytes. - // - for(Index = 0; Index < Length; Index++) { - - // - // For even characters, write the upper nibble for each buffer byte, - // and for even characters, the lower nibble. - // - if ((Index & BIT0) == 0) { - Buffer[Index / 2] = (UINT8) InternalHexCharToUintn (String[Index]) << 4; - } else { - Buffer[Index / 2] |= (UINT8) InternalHexCharToUintn (String[Index]); - } - } - return RETURN_SUCCESS; -} - -/** - Returns the length of a Null-terminated Ascii string. - - This function is similar as strlen_s defined in C11. - - @param String A pointer to a Null-terminated Ascii string. - @param MaxSize The maximum number of Destination Ascii - char, including terminating null char. - - @retval 0 If String is NULL. - @retval MaxSize If there is no null character in the first MaxSize characters of String. - @return The number of characters that percede the terminating null character. - -**/ -UINTN -EFIAPI -AsciiStrnLenS ( - IN CONST CHAR8 *String, - IN UINTN MaxSize - ) -{ - UINTN Length; - - // - // If String is a null pointer or MaxSize is 0, then the AsciiStrnLenS function returns zero. - // - if ((String == NULL) || (MaxSize == 0)) { - return 0; - } - - // - // Otherwise, the AsciiStrnLenS function returns the number of characters that precede the - // terminating null character. If there is no null character in the first MaxSize characters of - // String then AsciiStrnLenS returns MaxSize. At most the first MaxSize characters of String shall - // be accessed by AsciiStrnLenS. - // - Length = 0; - while (String[Length] != 0) { - if (Length >= MaxSize - 1) { - return MaxSize; - } - Length++; - } - return Length; -} - -/** - Returns the size of a Null-terminated Ascii string in bytes, including the - Null terminator. - - This function returns the size of the Null-terminated Ascii string specified - by String in bytes, including the Null terminator. - - @param String A pointer to a Null-terminated Ascii string. - @param MaxSize The maximum number of Destination Ascii - char, including the Null terminator. - - @retval 0 If String is NULL. - @retval (sizeof (CHAR8) * (MaxSize + 1)) - If there is no Null terminator in the first MaxSize characters of - String. - @return The size of the Null-terminated Ascii string in bytes, including the - Null terminator. - -**/ -UINTN -EFIAPI -AsciiStrnSizeS ( - IN CONST CHAR8 *String, - IN UINTN MaxSize - ) -{ - // - // If String is a null pointer, then the AsciiStrnSizeS function returns - // zero. - // - if (String == NULL) { - return 0; - } - - // - // Otherwise, the AsciiStrnSizeS function returns the size of the - // Null-terminated Ascii string in bytes, including the Null terminator. If - // there is no Null terminator in the first MaxSize characters of String, - // then AsciiStrnSizeS returns (sizeof (CHAR8) * (MaxSize + 1)) to keep a - // consistent map with the AsciiStrnLenS function. - // - return (AsciiStrnLenS (String, MaxSize) + 1) * sizeof (*String); -} - -/** - Copies the string pointed to by Source (including the terminating null char) - to the array pointed to by Destination. - - This function is similar as strcpy_s defined in C11. - - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Ascii string. - @param DestMax The maximum number of Destination Ascii - char, including terminating null char. - @param Source A pointer to a Null-terminated Ascii string. - - @retval RETURN_SUCCESS String is copied. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -AsciiStrCpyS ( - OUT CHAR8 *Destination, - IN UINTN DestMax, - IN CONST CHAR8 *Source - ) -{ - UINTN SourceLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. DestMax shall be greater than AsciiStrnLenS(Source, DestMax). - // - SourceLen = AsciiStrnLenS (Source, DestMax); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 5. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The AsciiStrCpyS function copies the string pointed to by Source (including the terminating - // null character) into the array pointed to by Destination. - // - while (*Source != 0) { - *(Destination++) = *(Source++); - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Copies not more than Length successive char from the string pointed to by - Source to the array pointed to by Destination. If no null char is copied from - Source, then Destination[Length] is always set to null. - - This function is similar as strncpy_s defined in C11. - - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Ascii string. - @param DestMax The maximum number of Destination Ascii - char, including terminating null char. - @param Source A pointer to a Null-terminated Ascii string. - @param Length The maximum number of Ascii characters to copy. - - @retval RETURN_SUCCESS String is copied. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than - MIN(StrLen(Source), Length). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -AsciiStrnCpyS ( - OUT CHAR8 *Destination, - IN UINTN DestMax, - IN CONST CHAR8 *Source, - IN UINTN Length - ) -{ - UINTN SourceLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. If Length is not less than DestMax, then DestMax shall be greater than AsciiStrnLenS(Source, DestMax). - // - SourceLen = AsciiStrnLenS (Source, MIN (DestMax, Length)); - if (Length >= DestMax) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 5. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The AsciiStrnCpyS function copies not more than Length successive characters (characters that - // follow a null character are not copied) from the array pointed to by Source to the array - // pointed to by Destination. If no null character was copied from Source, then Destination[Length] is set to a null - // character. - // - while ((SourceLen > 0) && (*Source != 0)) { - *(Destination++) = *(Source++); - SourceLen--; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Appends a copy of the string pointed to by Source (including the terminating - null char) to the end of the string pointed to by Destination. - - This function is similar as strcat_s defined in C11. - - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Ascii string. - @param DestMax The maximum number of Destination Ascii - char, including terminating null char. - @param Source A pointer to a Null-terminated Ascii string. - - @retval RETURN_SUCCESS String is appended. - @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than - StrLen(Destination). - @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT - greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -AsciiStrCatS ( - IN OUT CHAR8 *Destination, - IN UINTN DestMax, - IN CONST CHAR8 *Source - ) -{ - UINTN DestLen; - UINTN CopyLen; - UINTN SourceLen; - - // - // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrCatS. - // - DestLen = AsciiStrnLenS (Destination, DestMax); - CopyLen = DestMax - DestLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. CopyLen shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); - - // - // 5. CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). - // - SourceLen = AsciiStrnLenS (Source, CopyLen); - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 6. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The AsciiStrCatS function appends a copy of the string pointed to by Source (including the - // terminating null character) to the end of the string pointed to by Destination. The initial character - // from Source overwrites the null character at the end of Destination. - // - Destination = Destination + DestLen; - while (*Source != 0) { - *(Destination++) = *(Source++); - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Appends not more than Length successive char from the string pointed to by - Source to the end of the string pointed to by Destination. If no null char is - copied from Source, then Destination[StrLen(Destination) + Length] is always - set to null. - - This function is similar as strncat_s defined in C11. - - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Destination A pointer to a Null-terminated Ascii string. - @param DestMax The maximum number of Destination Ascii - char, including terminating null char. - @param Source A pointer to a Null-terminated Ascii string. - @param Length The maximum number of Ascii characters to copy. - - @retval RETURN_SUCCESS String is appended. - @retval RETURN_BAD_BUFFER_SIZE If DestMax is NOT greater than - StrLen(Destination). - @retval RETURN_BUFFER_TOO_SMALL If (DestMax - StrLen(Destination)) is NOT - greater than MIN(StrLen(Source), Length). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. -**/ -RETURN_STATUS -EFIAPI -AsciiStrnCatS ( - IN OUT CHAR8 *Destination, - IN UINTN DestMax, - IN CONST CHAR8 *Source, - IN UINTN Length - ) -{ - UINTN DestLen; - UINTN CopyLen; - UINTN SourceLen; - - // - // Let CopyLen denote the value DestMax - AsciiStrnLenS(Destination, DestMax) upon entry to AsciiStrnCatS. - // - DestLen = AsciiStrnLenS (Destination, DestMax); - CopyLen = DestMax - DestLen; - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither DestMax nor Length shall be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. CopyLen shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen != 0), RETURN_BAD_BUFFER_SIZE); - - // - // 5. If Length is not less than CopyLen, then CopyLen shall be greater than AsciiStrnLenS(Source, CopyLen). - // - SourceLen = AsciiStrnLenS (Source, MIN (CopyLen, Length)); - if (Length >= CopyLen) { - SAFE_STRING_CONSTRAINT_CHECK ((CopyLen > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 6. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (InternalSafeStringNoAsciiStrOverlap (Destination, DestMax, (CHAR8 *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // The AsciiStrnCatS function appends not more than Length successive characters (characters - // that follow a null character are not copied) from the array pointed to by Source to the end of - // the string pointed to by Destination. The initial character from Source overwrites the null character at - // the end of Destination. If no null character was copied from Source, then Destination[DestMax-CopyLen+Length] is set to - // a null character. - // - Destination = Destination + DestLen; - while ((SourceLen > 0) && (*Source != 0)) { - *(Destination++) = *(Source++); - SourceLen--; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Ascii decimal string to a value of type UINTN. - - This function outputs a value of type UINTN by interpreting the contents of - the Ascii string specified by String as a decimal number. The format of the - input Ascii string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before - [decimal digits]. The running zero in the beginning of [decimal digits] will - be ignored. Then, the function stops at the first character that is a not a - valid decimal character or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength Ascii characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid decimal digits in the above format, then 0 is stored - at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINTN, then - MAX_UINTN is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - decimal digits right after the optional pad spaces, the value of String is - stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Ascii string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumAsciiStringLength is not zero, - and String contains more than - PcdMaximumAsciiStringLength Ascii - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINTN. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrDecimalToUintnS ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT UINTN *Data - ) -{ - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == ' ') || (*String == '\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == '0') { - String++; - } - - *Data = 0; - - while (InternalAsciiIsDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINTN, then MAX_UINTN is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > ((MAX_UINTN - (*String - '0')) / 10)) { - *Data = MAX_UINTN; - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = *Data * 10 + (*String - '0'); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Ascii decimal string to a value of type UINT64. - - This function outputs a value of type UINT64 by interpreting the contents of - the Ascii string specified by String as a decimal number. The format of the - input Ascii string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before - [decimal digits]. The running zero in the beginning of [decimal digits] will - be ignored. Then, the function stops at the first character that is a not a - valid decimal character or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength Ascii characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid decimal digits in the above format, then 0 is stored - at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINT64, then - MAX_UINT64 is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - decimal digits right after the optional pad spaces, the value of String is - stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Ascii string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumAsciiStringLength is not zero, - and String contains more than - PcdMaximumAsciiStringLength Ascii - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINT64. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrDecimalToUint64S ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT UINT64 *Data - ) -{ - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == ' ') || (*String == '\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == '0') { - String++; - } - - *Data = 0; - - while (InternalAsciiIsDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINT64, then MAX_UINT64 is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > DivU64x32 (MAX_UINT64 - (*String - '0'), 10)) { - *Data = MAX_UINT64; - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = MultU64x32 (*Data, 10) + (*String - '0'); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Ascii hexadecimal string to a value of type UINTN. - - This function outputs a value of type UINTN by interpreting the contents of - the Ascii string specified by String as a hexadecimal number. The format of - the input Ascii string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If - "x" appears in the input string, it must be prefixed with at least one 0. The - function will ignore the pad space, which includes spaces or tab characters, - before [zeros], [x] or [hexadecimal digits]. The running zero before [x] or - [hexadecimal digits] will be ignored. Then, the decoding starts after [x] or - the first valid hexadecimal digit. Then, the function stops at the first - character that is a not a valid hexadecimal character or Null-terminator, - whichever on comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength Ascii characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid hexadecimal digits in the above format, then 0 is - stored at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINTN, then - MAX_UINTN is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - hexadecimal digits right after the optional pad spaces, the value of String - is stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Ascii string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumAsciiStringLength is not zero, - and String contains more than - PcdMaximumAsciiStringLength Ascii - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINTN. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrHexToUintnS ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT UINTN *Data - ) -{ - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == ' ') || (*String == '\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == '0') { - String++; - } - - if (InternalBaseLibAsciiToUpper (*String) == 'X') { - if (*(String - 1) != '0') { - *Data = 0; - return RETURN_SUCCESS; - } - // - // Skip the 'X' - // - String++; - } - - *Data = 0; - - while (InternalAsciiIsHexaDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINTN, then MAX_UINTN is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > ((MAX_UINTN - InternalAsciiHexCharToUintn (*String)) >> 4)) { - *Data = MAX_UINTN; - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = (*Data << 4) + InternalAsciiHexCharToUintn (*String); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Ascii hexadecimal string to a value of type UINT64. - - This function outputs a value of type UINT64 by interpreting the contents of - the Ascii string specified by String as a hexadecimal number. The format of - the input Ascii string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If - "x" appears in the input string, it must be prefixed with at least one 0. The - function will ignore the pad space, which includes spaces or tab characters, - before [zeros], [x] or [hexadecimal digits]. The running zero before [x] or - [hexadecimal digits] will be ignored. Then, the decoding starts after [x] or - the first valid hexadecimal digit. Then, the function stops at the first - character that is a not a valid hexadecimal character or Null-terminator, - whichever on comes first. - - If String is NULL, then ASSERT(). - If Data is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength Ascii characters, not including the - Null-terminator, then ASSERT(). - - If String has no valid hexadecimal digits in the above format, then 0 is - stored at the location pointed to by Data. - If the number represented by String exceeds the range defined by UINT64, then - MAX_UINT64 is stored at the location pointed to by Data. - - If EndPointer is not NULL, a pointer to the character that stopped the scan - is stored at the location pointed to by EndPointer. If String has no valid - hexadecimal digits right after the optional pad spaces, the value of String - is stored at the location pointed to by EndPointer. - - @param String Pointer to a Null-terminated Ascii string. - @param EndPointer Pointer to character that stops scan. - @param Data Pointer to the converted value. - - @retval RETURN_SUCCESS Value is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If PcdMaximumAsciiStringLength is not zero, - and String contains more than - PcdMaximumAsciiStringLength Ascii - characters, not including the - Null-terminator. - @retval RETURN_UNSUPPORTED If the number represented by String exceeds - the range defined by UINT64. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrHexToUint64S ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT UINT64 *Data - ) -{ - // - // 1. Neither String nor Data shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Data != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. The length of String shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((AsciiStrnLenS (String, ASCII_RSIZE_MAX + 1) <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - - // - // Ignore the pad spaces (space or tab) - // - while ((*String == ' ') || (*String == '\t')) { - String++; - } - - // - // Ignore leading Zeros after the spaces - // - while (*String == '0') { - String++; - } - - if (InternalBaseLibAsciiToUpper (*String) == 'X') { - if (*(String - 1) != '0') { - *Data = 0; - return RETURN_SUCCESS; - } - // - // Skip the 'X' - // - String++; - } - - *Data = 0; - - while (InternalAsciiIsHexaDecimalDigitCharacter (*String)) { - // - // If the number represented by String overflows according to the range - // defined by UINT64, then MAX_UINT64 is stored in *Data and - // RETURN_UNSUPPORTED is returned. - // - if (*Data > RShiftU64 (MAX_UINT64 - InternalAsciiHexCharToUintn (*String), 4)) { - *Data = MAX_UINT64; - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_UNSUPPORTED; - } - - *Data = LShiftU64 (*Data, 4) + InternalAsciiHexCharToUintn (*String); - String++; - } - - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) String; - } - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated Unicode string to a Null-terminated - ASCII string. - - This function is similar to AsciiStrCpyS. - - This function converts the content of the Unicode string Source - to the ASCII string Destination by copying the lower 8 bits of - each Unicode character. The function terminates the ASCII string - Destination by appending a Null-terminator character at the end. - - The caller is responsible to make sure Destination points to a buffer with size - equal or greater than ((StrLen (Source) + 1) * sizeof (CHAR8)) in bytes. - - If any Unicode characters in Source contain non-zero value in - the upper 8 bits, then ASSERT(). - - If Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Source The pointer to a Null-terminated Unicode string. - @param Destination The pointer to a Null-terminated ASCII string. - @param DestMax The maximum number of Destination Ascii - char, including terminating null char. - - @retval RETURN_SUCCESS String is converted. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. - -**/ -RETURN_STATUS -EFIAPI -UnicodeStrToAsciiStrS ( - IN CONST CHAR16 *Source, - OUT CHAR8 *Destination, - IN UINTN DestMax - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than ASCII_RSIZE_MAX or RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. DestMax shall be greater than StrnLenS (Source, DestMax). - // - SourceLen = StrnLenS (Source, DestMax); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 5. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax, (VOID *)Source, (SourceLen + 1) * sizeof(CHAR16)), RETURN_ACCESS_DENIED); - - // - // convert string - // - while (*Source != '\0') { - // - // If any Unicode characters in Source contain - // non-zero value in the upper 8 bits, then ASSERT(). - // - ASSERT (*Source < 0x100); - *(Destination++) = (CHAR8) *(Source++); - } - *Destination = '\0'; - - return RETURN_SUCCESS; -} - -/** - Convert not more than Length successive characters from a Null-terminated - Unicode string to a Null-terminated Ascii string. If no null char is copied - from Source, then Destination[Length] is always set to null. - - This function converts not more than Length successive characters from the - Unicode string Source to the Ascii string Destination by copying the lower 8 - bits of each Unicode character. The function terminates the Ascii string - Destination by appending a Null-terminator character at the end. - - The caller is responsible to make sure Destination points to a buffer with - size not smaller than ((MIN(StrLen(Source), Length) + 1) * sizeof (CHAR8)) - in bytes. - - If any Unicode characters in Source contain non-zero value in the upper 8 - bits, then ASSERT(). - If Source is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then Destination and DestinationLength are - unmodified. - - @param Source The pointer to a Null-terminated Unicode string. - @param Length The maximum number of Unicode characters to - convert. - @param Destination The pointer to a Null-terminated Ascii string. - @param DestMax The maximum number of Destination Ascii char, - including terminating null char. - @param DestinationLength The number of Unicode characters converted. - - @retval RETURN_SUCCESS String is converted. - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If DestinationLength is NULL. - If PcdMaximumAsciiStringLength is not zero, - and Length or DestMax is greater than - PcdMaximumAsciiStringLength. - If PcdMaximumUnicodeStringLength is not - zero, and Length or DestMax is greater than - PcdMaximumUnicodeStringLength. - If DestMax is 0. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than - MIN(StrLen(Source), Length). - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. - -**/ -RETURN_STATUS -EFIAPI -UnicodeStrnToAsciiStrS ( - IN CONST CHAR16 *Source, - IN UINTN Length, - OUT CHAR8 *Destination, - IN UINTN DestMax, - OUT UINTN *DestinationLength - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Source & BIT0) == 0); - - // - // 1. None of Destination, Source or DestinationLength shall be a null - // pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestinationLength != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither Length nor DestMax shall be greater than ASCII_RSIZE_MAX or - // RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. If Length is not less than DestMax, then DestMax shall be greater than - // StrnLenS(Source, DestMax). - // - SourceLen = StrnLenS (Source, DestMax); - if (Length >= DestMax) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 5. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax, (VOID *)Source, (SourceLen + 1) * sizeof(CHAR16)), RETURN_ACCESS_DENIED); - - *DestinationLength = 0; - - // - // Convert string - // - while ((*Source != 0) && (SourceLen > 0)) { - // - // If any Unicode characters in Source contain non-zero value in the upper - // 8 bits, then ASSERT(). - // - ASSERT (*Source < 0x100); - *(Destination++) = (CHAR8) *(Source++); - SourceLen--; - (*DestinationLength)++; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Convert one Null-terminated ASCII string to a Null-terminated - Unicode string. - - This function is similar to StrCpyS. - - This function converts the contents of the ASCII string Source to the Unicode - string Destination. The function terminates the Unicode string Destination by - appending a Null-terminator character at the end. - - The caller is responsible to make sure Destination points to a buffer with size - equal or greater than ((AsciiStrLen (Source) + 1) * sizeof (CHAR16)) in bytes. - - If Destination is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then the Destination is unmodified. - - @param Source The pointer to a Null-terminated ASCII string. - @param Destination The pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode - char, including terminating null char. - - @retval RETURN_SUCCESS String is converted. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than StrLen(Source). - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If PcdMaximumUnicodeStringLength is not zero, - and DestMax is greater than - PcdMaximumUnicodeStringLength. - If PcdMaximumAsciiStringLength is not zero, - and DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrToUnicodeStrS ( - IN CONST CHAR8 *Source, - OUT CHAR16 *Destination, - IN UINTN DestMax - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - - // - // 1. Neither Destination nor Source shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. DestMax shall not be greater than RSIZE_MAX or ASCII_RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. DestMax shall be greater than AsciiStrnLenS(Source, DestMax). - // - SourceLen = AsciiStrnLenS (Source, DestMax); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - - // - // 5. Copying shall not take place between objects that overlap. - // - SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax * sizeof(CHAR16), (VOID *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - // - // Convert string - // - while (*Source != '\0') { - *(Destination++) = (CHAR16)*(Source++); - } - *Destination = '\0'; - - return RETURN_SUCCESS; -} - -/** - Convert not more than Length successive characters from a Null-terminated - Ascii string to a Null-terminated Unicode string. If no null char is copied - from Source, then Destination[Length] is always set to null. - - This function converts not more than Length successive characters from the - Ascii string Source to the Unicode string Destination. The function - terminates the Unicode string Destination by appending a Null-terminator - character at the end. - - The caller is responsible to make sure Destination points to a buffer with - size not smaller than - ((MIN(AsciiStrLen(Source), Length) + 1) * sizeof (CHAR8)) in bytes. - - If Destination is not aligned on a 16-bit boundary, then ASSERT(). - If an error would be returned, then the function will also ASSERT(). - - If an error is returned, then Destination and DestinationLength are - unmodified. - - @param Source The pointer to a Null-terminated Ascii string. - @param Length The maximum number of Ascii characters to convert. - @param Destination The pointer to a Null-terminated Unicode string. - @param DestMax The maximum number of Destination Unicode char, - including terminating null char. - @param DestinationLength The number of Ascii characters converted. - - @retval RETURN_SUCCESS String is converted. - @retval RETURN_INVALID_PARAMETER If Destination is NULL. - If Source is NULL. - If DestinationLength is NULL. - If PcdMaximumUnicodeStringLength is not - zero, and Length or DestMax is greater than - PcdMaximumUnicodeStringLength. - If PcdMaximumAsciiStringLength is not zero, - and Length or DestMax is greater than - PcdMaximumAsciiStringLength. - If DestMax is 0. - @retval RETURN_BUFFER_TOO_SMALL If DestMax is NOT greater than - MIN(AsciiStrLen(Source), Length). - @retval RETURN_ACCESS_DENIED If Source and Destination overlap. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrnToUnicodeStrS ( - IN CONST CHAR8 *Source, - IN UINTN Length, - OUT CHAR16 *Destination, - IN UINTN DestMax, - OUT UINTN *DestinationLength - ) -{ - UINTN SourceLen; - - ASSERT (((UINTN) Destination & BIT0) == 0); - - // - // 1. None of Destination, Source or DestinationLength shall be a null - // pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((Destination != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Source != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestinationLength != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Neither Length nor DestMax shall be greater than ASCII_RSIZE_MAX or - // RSIZE_MAX. - // - if (RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((DestMax <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. DestMax shall not equal zero. - // - SAFE_STRING_CONSTRAINT_CHECK ((DestMax != 0), RETURN_INVALID_PARAMETER); - - // - // 4. If Length is not less than DestMax, then DestMax shall be greater than - // AsciiStrnLenS(Source, DestMax). - // - SourceLen = AsciiStrnLenS (Source, DestMax); - if (Length >= DestMax) { - SAFE_STRING_CONSTRAINT_CHECK ((DestMax > SourceLen), RETURN_BUFFER_TOO_SMALL); - } - - // - // 5. Copying shall not take place between objects that overlap. - // - if (SourceLen > Length) { - SourceLen = Length; - } - SAFE_STRING_CONSTRAINT_CHECK (!InternalSafeStringIsOverlap (Destination, DestMax * sizeof(CHAR16), (VOID *)Source, SourceLen + 1), RETURN_ACCESS_DENIED); - - *DestinationLength = 0; - - // - // Convert string - // - while ((*Source != 0) && (SourceLen > 0)) { - *(Destination++) = (CHAR16)*(Source++); - SourceLen--; - (*DestinationLength)++; - } - *Destination = 0; - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated ASCII string to IPv6 address and prefix length. - - This function outputs a value of type IPv6_ADDRESS and may output a value - of type UINT8 by interpreting the contents of the ASCII string specified - by String. The format of the input ASCII string String is as follows: - - X:X:X:X:X:X:X:X[/P] - - X contains one to four hexadecimal digit characters in the range [0-9], [a-f] and - [A-F]. X is converted to a value of type UINT16, whose low byte is stored in low - memory address and high byte is stored in high memory address. P contains decimal - digit characters in the range [0-9]. The running zero in the beginning of P will - be ignored. /P is optional. - - When /P is not in the String, the function stops at the first character that is - not a valid hexadecimal digit character after eight X's are converted. - - When /P is in the String, the function stops at the first character that is not - a valid decimal digit character after P is converted. - - "::" can be used to compress one or more groups of X when X contains only 0. - The "::" can only appear once in the String. - - If String is NULL, then ASSERT(). - - If Address is NULL, then ASSERT(). - - If EndPointer is not NULL and Address is translated from String, a pointer - to the character that stopped the scan is stored at the location pointed to - by EndPointer. - - @param String Pointer to a Null-terminated ASCII string. - @param EndPointer Pointer to character that stops scan. - @param Address Pointer to the converted IPv6 address. - @param PrefixLength Pointer to the converted IPv6 address prefix - length. MAX_UINT8 is returned when /P is - not in the String. - - @retval RETURN_SUCCESS Address is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If X contains more than four hexadecimal - digit characters. - If String contains "::" and number of X - is not less than 8. - If P starts with character that is not a - valid decimal digit character. - If the decimal number converted from P - exceeds 128. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrToIpv6Address ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT IPv6_ADDRESS *Address, - OUT UINT8 *PrefixLength OPTIONAL - ) -{ - RETURN_STATUS Status; - UINTN AddressIndex; - UINTN Uintn; - IPv6_ADDRESS LocalAddress; - UINT8 LocalPrefixLength; - CONST CHAR8 *Pointer; - CHAR8 *End; - UINTN CompressStart; - BOOLEAN ExpectPrefix; - - LocalPrefixLength = MAX_UINT8; - CompressStart = ARRAY_SIZE (Address->Addr); - ExpectPrefix = FALSE; - - // - // None of String or Address shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); - - for (Pointer = String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { - if (!InternalAsciiIsHexaDecimalDigitCharacter (*Pointer)) { - if (*Pointer != ':') { - // - // ":" or "/" should be followed by digit characters. - // - return RETURN_UNSUPPORTED; - } - - // - // Meet second ":" after previous ":" or "/" - // or meet first ":" in the beginning of String. - // - if (ExpectPrefix) { - // - // ":" shall not be after "/" - // - return RETURN_UNSUPPORTED; - } - - if (CompressStart != ARRAY_SIZE (Address->Addr) || AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // "::" can only appear once. - // "::" can only appear when address is not full length. - // - return RETURN_UNSUPPORTED; - } else { - // - // Remember the start of zero compressing. - // - CompressStart = AddressIndex; - Pointer++; - - if (CompressStart == 0) { - if (*Pointer != ':') { - // - // Single ":" shall not be in the beginning of String. - // - return RETURN_UNSUPPORTED; - } - Pointer++; - } - } - } - - if (!InternalAsciiIsHexaDecimalDigitCharacter (*Pointer)) { - if (*Pointer == '/') { - // - // Might be optional "/P" after "::". - // - if (CompressStart != AddressIndex) { - return RETURN_UNSUPPORTED; - } - } else { - break; - } - } else { - if (!ExpectPrefix) { - // - // Get X. - // - Status = AsciiStrHexToUintnS (Pointer, &End, &Uintn); - if (RETURN_ERROR (Status) || End - Pointer > 4) { - // - // Number of hexadecimal digit characters is no more than 4. - // - return RETURN_UNSUPPORTED; - } - Pointer = End; - // - // Uintn won't exceed MAX_UINT16 if number of hexadecimal digit characters is no more than 4. - // - ASSERT (AddressIndex + 1 < ARRAY_SIZE (Address->Addr)); - LocalAddress.Addr[AddressIndex] = (UINT8) ((UINT16) Uintn >> 8); - LocalAddress.Addr[AddressIndex + 1] = (UINT8) Uintn; - AddressIndex += 2; - } else { - // - // Get P, then exit the loop. - // - Status = AsciiStrDecimalToUintnS (Pointer, &End, &Uintn); - if (RETURN_ERROR (Status) || End == Pointer || Uintn > 128) { - // - // Prefix length should not exceed 128. - // - return RETURN_UNSUPPORTED; - } - LocalPrefixLength = (UINT8) Uintn; - Pointer = End; - break; - } - } - - // - // Skip ':' or "/" - // - if (*Pointer == '/') { - ExpectPrefix = TRUE; - } else if (*Pointer == ':') { - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // Meet additional ":" after all 8 16-bit address - // - break; - } - } else { - // - // Meet other character that is not "/" or ":" after all 8 16-bit address - // - break; - } - Pointer++; - } - - if ((AddressIndex == ARRAY_SIZE (Address->Addr) && CompressStart != ARRAY_SIZE (Address->Addr)) || - (AddressIndex != ARRAY_SIZE (Address->Addr) && CompressStart == ARRAY_SIZE (Address->Addr)) - ) { - // - // Full length of address shall not have compressing zeros. - // Non-full length of address shall have compressing zeros. - // - return RETURN_UNSUPPORTED; - } - CopyMem (&Address->Addr[0], &LocalAddress.Addr[0], CompressStart); - ZeroMem (&Address->Addr[CompressStart], ARRAY_SIZE (Address->Addr) - AddressIndex); - if (AddressIndex > CompressStart) { - CopyMem ( - &Address->Addr[CompressStart + ARRAY_SIZE (Address->Addr) - AddressIndex], - &LocalAddress.Addr[CompressStart], - AddressIndex - CompressStart - ); - - } - - if (PrefixLength != NULL) { - *PrefixLength = LocalPrefixLength; - } - if (EndPointer != NULL) { - *EndPointer = (CHAR8 *) Pointer; - } - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated ASCII string to IPv4 address and prefix length. - - This function outputs a value of type IPv4_ADDRESS and may output a value - of type UINT8 by interpreting the contents of the ASCII string specified - by String. The format of the input ASCII string String is as follows: - - D.D.D.D[/P] - - D and P are decimal digit characters in the range [0-9]. The running zero in - the beginning of D and P will be ignored. /P is optional. - - When /P is not in the String, the function stops at the first character that is - not a valid decimal digit character after four D's are converted. - - When /P is in the String, the function stops at the first character that is not - a valid decimal digit character after P is converted. - - If String is NULL, then ASSERT(). - - If Address is NULL, then ASSERT(). - - If EndPointer is not NULL and Address is translated from String, a pointer - to the character that stopped the scan is stored at the location pointed to - by EndPointer. - - @param String Pointer to a Null-terminated ASCII string. - @param EndPointer Pointer to character that stops scan. - @param Address Pointer to the converted IPv4 address. - @param PrefixLength Pointer to the converted IPv4 address prefix - length. MAX_UINT8 is returned when /P is - not in the String. - - @retval RETURN_SUCCESS Address is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If String is not in the correct format. - If any decimal number converted from D - exceeds 255. - If the decimal number converted from P - exceeds 32. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrToIpv4Address ( - IN CONST CHAR8 *String, - OUT CHAR8 **EndPointer, OPTIONAL - OUT IPv4_ADDRESS *Address, - OUT UINT8 *PrefixLength OPTIONAL - ) -{ - RETURN_STATUS Status; - UINTN AddressIndex; - UINTN Uintn; - IPv4_ADDRESS LocalAddress; - UINT8 LocalPrefixLength; - CHAR8 *Pointer; - - LocalPrefixLength = MAX_UINT8; - - // - // None of String or Address shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Address != NULL), RETURN_INVALID_PARAMETER); - - for (Pointer = (CHAR8 *) String, AddressIndex = 0; AddressIndex < ARRAY_SIZE (Address->Addr) + 1;) { - if (!InternalAsciiIsDecimalDigitCharacter (*Pointer)) { - // - // D or P contains invalid characters. - // - break; - } - - // - // Get D or P. - // - Status = AsciiStrDecimalToUintnS ((CONST CHAR8 *) Pointer, &Pointer, &Uintn); - if (RETURN_ERROR (Status)) { - return RETURN_UNSUPPORTED; - } - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - // - // It's P. - // - if (Uintn > 32) { - return RETURN_UNSUPPORTED; - } - LocalPrefixLength = (UINT8) Uintn; - } else { - // - // It's D. - // - if (Uintn > MAX_UINT8) { - return RETURN_UNSUPPORTED; - } - LocalAddress.Addr[AddressIndex] = (UINT8) Uintn; - AddressIndex++; - } - - // - // Check the '.' or '/', depending on the AddressIndex. - // - if (AddressIndex == ARRAY_SIZE (Address->Addr)) { - if (*Pointer == '/') { - // - // '/P' is in the String. - // Skip "/" and get P in next loop. - // - Pointer++; - } else { - // - // '/P' is not in the String. - // - break; - } - } else if (AddressIndex < ARRAY_SIZE (Address->Addr)) { - if (*Pointer == '.') { - // - // D should be followed by '.' - // - Pointer++; - } else { - return RETURN_UNSUPPORTED; - } - } - } - - if (AddressIndex < ARRAY_SIZE (Address->Addr)) { - return RETURN_UNSUPPORTED; - } - - CopyMem (Address, &LocalAddress, sizeof (*Address)); - if (PrefixLength != NULL) { - *PrefixLength = LocalPrefixLength; - } - if (EndPointer != NULL) { - *EndPointer = Pointer; - } - - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated ASCII GUID string to a value of type - EFI_GUID. - - This function outputs a GUID value by interpreting the contents of - the ASCII string specified by String. The format of the input - ASCII string String consists of 36 characters, as follows: - - aabbccdd-eeff-gghh-iijj-kkllmmnnoopp - - The pairs aa - pp are two characters in the range [0-9], [a-f] and - [A-F], with each pair representing a single byte hexadecimal value. - - The mapping between String and the EFI_GUID structure is as follows: - aa Data1[24:31] - bb Data1[16:23] - cc Data1[8:15] - dd Data1[0:7] - ee Data2[8:15] - ff Data2[0:7] - gg Data3[8:15] - hh Data3[0:7] - ii Data4[0:7] - jj Data4[8:15] - kk Data4[16:23] - ll Data4[24:31] - mm Data4[32:39] - nn Data4[40:47] - oo Data4[48:55] - pp Data4[56:63] - - If String is NULL, then ASSERT(). - If Guid is NULL, then ASSERT(). - - @param String Pointer to a Null-terminated ASCII string. - @param Guid Pointer to the converted GUID. - - @retval RETURN_SUCCESS Guid is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - @retval RETURN_UNSUPPORTED If String is not as the above format. - -**/ -RETURN_STATUS -EFIAPI -AsciiStrToGuid ( - IN CONST CHAR8 *String, - OUT GUID *Guid - ) -{ - RETURN_STATUS Status; - GUID LocalGuid; - - // - // None of String or Guid shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Guid != NULL), RETURN_INVALID_PARAMETER); - - // - // Get aabbccdd in big-endian. - // - Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data1), (UINT8 *) &LocalGuid.Data1, sizeof (LocalGuid.Data1)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data1)] != '-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data1 = SwapBytes32 (LocalGuid.Data1); - String += 2 * sizeof (LocalGuid.Data1) + 1; - - // - // Get eeff in big-endian. - // - Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data2), (UINT8 *) &LocalGuid.Data2, sizeof (LocalGuid.Data2)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data2)] != '-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data2 = SwapBytes16 (LocalGuid.Data2); - String += 2 * sizeof (LocalGuid.Data2) + 1; - - // - // Get gghh in big-endian. - // - Status = AsciiStrHexToBytes (String, 2 * sizeof (LocalGuid.Data3), (UINT8 *) &LocalGuid.Data3, sizeof (LocalGuid.Data3)); - if (RETURN_ERROR (Status) || String[2 * sizeof (LocalGuid.Data3)] != '-') { - return RETURN_UNSUPPORTED; - } - // - // Convert big-endian to little-endian. - // - LocalGuid.Data3 = SwapBytes16 (LocalGuid.Data3); - String += 2 * sizeof (LocalGuid.Data3) + 1; - - // - // Get iijj. - // - Status = AsciiStrHexToBytes (String, 2 * 2, &LocalGuid.Data4[0], 2); - if (RETURN_ERROR (Status) || String[2 * 2] != '-') { - return RETURN_UNSUPPORTED; - } - String += 2 * 2 + 1; - - // - // Get kkllmmnnoopp. - // - Status = AsciiStrHexToBytes (String, 2 * 6, &LocalGuid.Data4[2], 6); - if (RETURN_ERROR (Status)) { - return RETURN_UNSUPPORTED; - } - - CopyGuid (Guid, &LocalGuid); - return RETURN_SUCCESS; -} - -/** - Convert a Null-terminated ASCII hexadecimal string to a byte array. - - This function outputs a byte array by interpreting the contents of - the ASCII string specified by String in hexadecimal format. The format of - the input ASCII string String is: - - [XX]* - - X is a hexadecimal digit character in the range [0-9], [a-f] and [A-F]. - The function decodes every two hexadecimal digit characters as one byte. The - decoding stops after Length of characters and outputs Buffer containing - (Length / 2) bytes. - - If String is NULL, then ASSERT(). - - If Buffer is NULL, then ASSERT(). - - If Length is not multiple of 2, then ASSERT(). - - If PcdMaximumAsciiStringLength is not zero and Length is greater than - PcdMaximumAsciiStringLength, then ASSERT(). - - If MaxBufferSize is less than (Length / 2), then ASSERT(). - - @param String Pointer to a Null-terminated ASCII string. - @param Length The number of ASCII characters to decode. - @param Buffer Pointer to the converted bytes array. - @param MaxBufferSize The maximum size of Buffer. - - @retval RETURN_SUCCESS Buffer is translated from String. - @retval RETURN_INVALID_PARAMETER If String is NULL. - If Data is NULL. - If Length is not multiple of 2. - If PcdMaximumAsciiStringLength is not zero, - and Length is greater than - PcdMaximumAsciiStringLength. - @retval RETURN_UNSUPPORTED If Length of characters from String contain - a character that is not valid hexadecimal - digit characters, or a Null-terminator. - @retval RETURN_BUFFER_TOO_SMALL If MaxBufferSize is less than (Length / 2). -**/ -RETURN_STATUS -EFIAPI -AsciiStrHexToBytes ( - IN CONST CHAR8 *String, - IN UINTN Length, - OUT UINT8 *Buffer, - IN UINTN MaxBufferSize - ) -{ - UINTN Index; - - // - // 1. None of String or Buffer shall be a null pointer. - // - SAFE_STRING_CONSTRAINT_CHECK ((String != NULL), RETURN_INVALID_PARAMETER); - SAFE_STRING_CONSTRAINT_CHECK ((Buffer != NULL), RETURN_INVALID_PARAMETER); - - // - // 2. Length shall not be greater than ASCII_RSIZE_MAX. - // - if (ASCII_RSIZE_MAX != 0) { - SAFE_STRING_CONSTRAINT_CHECK ((Length <= ASCII_RSIZE_MAX), RETURN_INVALID_PARAMETER); - } - - // - // 3. Length shall not be odd. - // - SAFE_STRING_CONSTRAINT_CHECK (((Length & BIT0) == 0), RETURN_INVALID_PARAMETER); - - // - // 4. MaxBufferSize shall equal to or greater than Length / 2. - // - SAFE_STRING_CONSTRAINT_CHECK ((MaxBufferSize >= Length / 2), RETURN_BUFFER_TOO_SMALL); - - // - // 5. String shall not contains invalid hexadecimal digits. - // - for (Index = 0; Index < Length; Index++) { - if (!InternalAsciiIsHexaDecimalDigitCharacter (String[Index])) { - break; - } - } - if (Index != Length) { - return RETURN_UNSUPPORTED; - } - - // - // Convert the hex string to bytes. - // - for(Index = 0; Index < Length; Index++) { - - // - // For even characters, write the upper nibble for each buffer byte, - // and for even characters, the lower nibble. - // - if ((Index & BIT0) == 0) { - Buffer[Index / 2] = (UINT8) InternalAsciiHexCharToUintn (String[Index]) << 4; - } else { - Buffer[Index / 2] |= (UINT8) InternalAsciiHexCharToUintn (String[Index]); - } - } - return RETURN_SUCCESS; -} - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c b/MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c deleted file mode 100644 index 6d61e93adc5..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SetJump.c +++ /dev/null @@ -1,54 +0,0 @@ -/** @file - Internal ASSERT () functions for SetJump. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - -#include -#include -#include -#include -#include - -/** - Saves the current CPU context that can be restored with a call to LongJump() - and returns 0. - - Saves the current CPU context in the buffer specified by JumpBuffer and - returns 0. The initial call to SetJump() must always return 0. Subsequent - calls to LongJump() cause a non-zero value to be returned by SetJump(). - - If JumpBuffer is NULL, then ASSERT(). - For Itanium processors, if JumpBuffer is not aligned on a 16-byte boundary, then ASSERT(). - - NOTE: The structure BASE_LIBRARY_JUMP_BUFFER is CPU architecture specific. - The same structure must never be used for more than one CPU architecture context. - For example, a BASE_LIBRARY_JUMP_BUFFER allocated by an IA-32 module must never be used from an x64 module. - SetJump()/LongJump() is not currently supported for the EBC processor type. - - @param JumpBuffer A pointer to CPU context buffer. - - @retval 0 Indicates a return from SetJump(). - -**/ -UINTN -EFIAPI -SetJump ( - OUT BASE_LIBRARY_JUMP_BUFFER *JumpBuffer - ) -{ - jmp_buf local_buf; - jmp_buf *buf; - UINTN Value; - - buf = malloc (sizeof(jmp_buf)); - *(VOID **)JumpBuffer = buf; - Value = setjmp (local_buf); - if (Value == 0) { - memcpy (buf, &local_buf, sizeof(jmp_buf)); - } - return Value; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/String.c b/MdePkg/Test/HostLibrary/BaseLibHost/String.c deleted file mode 100644 index 4f5fa470b33..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/String.c +++ /dev/null @@ -1,1163 +0,0 @@ -/** @file - Unicode and ASCII string primitives. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Returns the length of a Null-terminated Unicode string. - - This function returns the number of Unicode characters in the Null-terminated - Unicode string specified by String. - - If String is NULL, then ASSERT(). - If String is not aligned on a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @return The length of String. - -**/ -UINTN -EFIAPI -StrLen ( - IN CONST CHAR16 *String - ) -{ - UINTN Length; - - ASSERT (String != NULL); - ASSERT (((UINTN) String & BIT0) == 0); - - for (Length = 0; *String != L'\0'; String++, Length++) { - // - // If PcdMaximumUnicodeStringLength is not zero, - // length should not more than PcdMaximumUnicodeStringLength - // - } - return Length; -} - -/** - Returns the size of a Null-terminated Unicode string in bytes, including the - Null terminator. - - This function returns the size, in bytes, of the Null-terminated Unicode string - specified by String. - - If String is NULL, then ASSERT(). - If String is not aligned on a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @return The size of String. - -**/ -UINTN -EFIAPI -StrSize ( - IN CONST CHAR16 *String - ) -{ - return (StrLen (String) + 1) * sizeof (*String); -} - -/** - Compares two Null-terminated Unicode strings, and returns the difference - between the first mismatched Unicode characters. - - This function compares the Null-terminated Unicode string FirstString to the - Null-terminated Unicode string SecondString. If FirstString is identical to - SecondString, then 0 is returned. Otherwise, the value returned is the first - mismatched Unicode character in SecondString subtracted from the first - mismatched Unicode character in FirstString. - - If FirstString is NULL, then ASSERT(). - If FirstString is not aligned on a 16-bit boundary, then ASSERT(). - If SecondString is NULL, then ASSERT(). - If SecondString is not aligned on a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and FirstString contains more - than PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and SecondString contains more - than PcdMaximumUnicodeStringLength Unicode characters, not including the - Null-terminator, then ASSERT(). - - @param FirstString A pointer to a Null-terminated Unicode string. - @param SecondString A pointer to a Null-terminated Unicode string. - - @retval 0 FirstString is identical to SecondString. - @return others FirstString is not identical to SecondString. - -**/ -INTN -EFIAPI -StrCmp ( - IN CONST CHAR16 *FirstString, - IN CONST CHAR16 *SecondString - ) -{ - // - // ASSERT both strings are less long than PcdMaximumUnicodeStringLength - // - ASSERT (StrSize (FirstString) != 0); - ASSERT (StrSize (SecondString) != 0); - - while ((*FirstString != L'\0') && (*FirstString == *SecondString)) { - FirstString++; - SecondString++; - } - return *FirstString - *SecondString; -} - -/** - Compares up to a specified length the contents of two Null-terminated Unicode strings, - and returns the difference between the first mismatched Unicode characters. - - This function compares the Null-terminated Unicode string FirstString to the - Null-terminated Unicode string SecondString. At most, Length Unicode - characters will be compared. If Length is 0, then 0 is returned. If - FirstString is identical to SecondString, then 0 is returned. Otherwise, the - value returned is the first mismatched Unicode character in SecondString - subtracted from the first mismatched Unicode character in FirstString. - - If Length > 0 and FirstString is NULL, then ASSERT(). - If Length > 0 and FirstString is not aligned on a 16-bit boundary, then ASSERT(). - If Length > 0 and SecondString is NULL, then ASSERT(). - If Length > 0 and SecondString is not aligned on a 16-bit boundary, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and Length is greater than - PcdMaximumUnicodeStringLength, then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and FirstString contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, - then ASSERT(). - If PcdMaximumUnicodeStringLength is not zero, and SecondString contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, - then ASSERT(). - - @param FirstString A pointer to a Null-terminated Unicode string. - @param SecondString A pointer to a Null-terminated Unicode string. - @param Length The maximum number of Unicode characters to compare. - - @retval 0 FirstString is identical to SecondString. - @return others FirstString is not identical to SecondString. - -**/ -INTN -EFIAPI -StrnCmp ( - IN CONST CHAR16 *FirstString, - IN CONST CHAR16 *SecondString, - IN UINTN Length - ) -{ - if (Length == 0) { - return 0; - } - - // - // ASSERT both strings are less long than PcdMaximumUnicodeStringLength. - // Length tests are performed inside StrLen(). - // - ASSERT (StrSize (FirstString) != 0); - ASSERT (StrSize (SecondString) != 0); - - while ((*FirstString != L'\0') && - (*SecondString != L'\0') && - (*FirstString == *SecondString) && - (Length > 1)) { - FirstString++; - SecondString++; - Length--; - } - - return *FirstString - *SecondString; -} - -/** - Returns the first occurrence of a Null-terminated Unicode sub-string - in a Null-terminated Unicode string. - - This function scans the contents of the Null-terminated Unicode string - specified by String and returns the first occurrence of SearchString. - If SearchString is not found in String, then NULL is returned. If - the length of SearchString is zero, then String is - returned. - - If String is NULL, then ASSERT(). - If String is not aligned on a 16-bit boundary, then ASSERT(). - If SearchString is NULL, then ASSERT(). - If SearchString is not aligned on a 16-bit boundary, then ASSERT(). - - If PcdMaximumUnicodeStringLength is not zero, and SearchString - or String contains more than PcdMaximumUnicodeStringLength Unicode - characters, not including the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - @param SearchString A pointer to a Null-terminated Unicode string to search for. - - @retval NULL If the SearchString does not appear in String. - @return others If there is a match. - -**/ -CHAR16 * -EFIAPI -StrStr ( - IN CONST CHAR16 *String, - IN CONST CHAR16 *SearchString - ) -{ - CONST CHAR16 *FirstMatch; - CONST CHAR16 *SearchStringTmp; - - // - // ASSERT both strings are less long than PcdMaximumUnicodeStringLength. - // Length tests are performed inside StrLen(). - // - ASSERT (StrSize (String) != 0); - ASSERT (StrSize (SearchString) != 0); - - if (*SearchString == L'\0') { - return (CHAR16 *) String; - } - - while (*String != L'\0') { - SearchStringTmp = SearchString; - FirstMatch = String; - - while ((*String == *SearchStringTmp) - && (*String != L'\0')) { - String++; - SearchStringTmp++; - } - - if (*SearchStringTmp == L'\0') { - return (CHAR16 *) FirstMatch; - } - - if (*String == L'\0') { - return NULL; - } - - String = FirstMatch + 1; - } - - return NULL; -} - -/** - Check if a Unicode character is a decimal character. - - This internal function checks if a Unicode character is a - decimal character. The valid decimal character is from - L'0' to L'9'. - - @param Char The character to check against. - - @retval TRUE If the Char is a decmial character. - @retval FALSE If the Char is not a decmial character. - -**/ -BOOLEAN -EFIAPI -InternalIsDecimalDigitCharacter ( - IN CHAR16 Char - ) -{ - return (BOOLEAN) (Char >= L'0' && Char <= L'9'); -} - -/** - Convert a Unicode character to upper case only if - it maps to a valid small-case ASCII character. - - This internal function only deal with Unicode character - which maps to a valid small-case ASCII character, i.e. - L'a' to L'z'. For other Unicode character, the input character - is returned directly. - - @param Char The character to convert. - - @retval LowerCharacter If the Char is with range L'a' to L'z'. - @retval Unchanged Otherwise. - -**/ -CHAR16 -EFIAPI -InternalCharToUpper ( - IN CHAR16 Char - ) -{ - if (Char >= L'a' && Char <= L'z') { - return (CHAR16) (Char - (L'a' - L'A')); - } - - return Char; -} - -/** - Convert a Unicode character to numerical value. - - This internal function only deal with Unicode character - which maps to a valid hexadecimal ASII character, i.e. - L'0' to L'9', L'a' to L'f' or L'A' to L'F'. For other - Unicode character, the value returned does not make sense. - - @param Char The character to convert. - - @return The numerical value converted. - -**/ -UINTN -EFIAPI -InternalHexCharToUintn ( - IN CHAR16 Char - ) -{ - if (InternalIsDecimalDigitCharacter (Char)) { - return Char - L'0'; - } - - return (10 + InternalCharToUpper (Char) - L'A'); -} - -/** - Check if a Unicode character is a hexadecimal character. - - This internal function checks if a Unicode character is a - decimal character. The valid hexadecimal character is - L'0' to L'9', L'a' to L'f', or L'A' to L'F'. - - - @param Char The character to check against. - - @retval TRUE If the Char is a hexadecmial character. - @retval FALSE If the Char is not a hexadecmial character. - -**/ -BOOLEAN -EFIAPI -InternalIsHexaDecimalDigitCharacter ( - IN CHAR16 Char - ) -{ - - return (BOOLEAN) (InternalIsDecimalDigitCharacter (Char) || - (Char >= L'A' && Char <= L'F') || - (Char >= L'a' && Char <= L'f')); -} - -/** - Convert a Null-terminated Unicode decimal string to a value of - type UINTN. - - This function returns a value of type UINTN by interpreting the contents - of the Unicode string specified by String as a decimal number. The format - of the input Unicode string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The - function will ignore the pad space, which includes spaces or - tab characters, before [decimal digits]. The running zero in the - beginning of [decimal digits] will be ignored. Then, the function - stops at the first character that is a not a valid decimal character - or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If String has only pad spaces, then 0 is returned. - If String has no pad spaces or valid decimal digits, - then 0 is returned. - If the number represented by String overflows according - to the range defined by UINTN, then MAX_UINTN is returned. - - If PcdMaximumUnicodeStringLength is not zero, and String contains - more than PcdMaximumUnicodeStringLength Unicode characters, not including - the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @retval Value translated from String. - -**/ -UINTN -EFIAPI -StrDecimalToUintn ( - IN CONST CHAR16 *String - ) -{ - UINTN Result; - - StrDecimalToUintnS (String, (CHAR16 **) NULL, &Result); - return Result; -} - - -/** - Convert a Null-terminated Unicode decimal string to a value of - type UINT64. - - This function returns a value of type UINT64 by interpreting the contents - of the Unicode string specified by String as a decimal number. The format - of the input Unicode string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The - function will ignore the pad space, which includes spaces or - tab characters, before [decimal digits]. The running zero in the - beginning of [decimal digits] will be ignored. Then, the function - stops at the first character that is a not a valid decimal character - or a Null-terminator, whichever one comes first. - - If String is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If String has only pad spaces, then 0 is returned. - If String has no pad spaces or valid decimal digits, - then 0 is returned. - If the number represented by String overflows according - to the range defined by UINT64, then MAX_UINT64 is returned. - - If PcdMaximumUnicodeStringLength is not zero, and String contains - more than PcdMaximumUnicodeStringLength Unicode characters, not including - the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @retval Value translated from String. - -**/ -UINT64 -EFIAPI -StrDecimalToUint64 ( - IN CONST CHAR16 *String - ) -{ - UINT64 Result; - - StrDecimalToUint64S (String, (CHAR16 **) NULL, &Result); - return Result; -} - -/** - Convert a Null-terminated Unicode hexadecimal string to a value of type UINTN. - - This function returns a value of type UINTN by interpreting the contents - of the Unicode string specified by String as a hexadecimal number. - The format of the input Unicode string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. - If "x" appears in the input string, it must be prefixed with at least one 0. - The function will ignore the pad space, which includes spaces or tab characters, - before [zeros], [x] or [hexadecimal digit]. The running zero before [x] or - [hexadecimal digit] will be ignored. Then, the decoding starts after [x] or the - first valid hexadecimal digit. Then, the function stops at the first character that is - a not a valid hexadecimal character or NULL, whichever one comes first. - - If String is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If String has only pad spaces, then zero is returned. - If String has no leading pad spaces, leading zeros or valid hexadecimal digits, - then zero is returned. - If the number represented by String overflows according to the range defined by - UINTN, then MAX_UINTN is returned. - - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @retval Value translated from String. - -**/ -UINTN -EFIAPI -StrHexToUintn ( - IN CONST CHAR16 *String - ) -{ - UINTN Result; - - StrHexToUintnS (String, (CHAR16 **) NULL, &Result); - return Result; -} - - -/** - Convert a Null-terminated Unicode hexadecimal string to a value of type UINT64. - - This function returns a value of type UINT64 by interpreting the contents - of the Unicode string specified by String as a hexadecimal number. - The format of the input Unicode string String is - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. - If "x" appears in the input string, it must be prefixed with at least one 0. - The function will ignore the pad space, which includes spaces or tab characters, - before [zeros], [x] or [hexadecimal digit]. The running zero before [x] or - [hexadecimal digit] will be ignored. Then, the decoding starts after [x] or the - first valid hexadecimal digit. Then, the function stops at the first character that is - a not a valid hexadecimal character or NULL, whichever one comes first. - - If String is NULL, then ASSERT(). - If String is not aligned in a 16-bit boundary, then ASSERT(). - If String has only pad spaces, then zero is returned. - If String has no leading pad spaces, leading zeros or valid hexadecimal digits, - then zero is returned. - If the number represented by String overflows according to the range defined by - UINT64, then MAX_UINT64 is returned. - - If PcdMaximumUnicodeStringLength is not zero, and String contains more than - PcdMaximumUnicodeStringLength Unicode characters, not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated Unicode string. - - @retval Value translated from String. - -**/ -UINT64 -EFIAPI -StrHexToUint64 ( - IN CONST CHAR16 *String - ) -{ - UINT64 Result; - - StrHexToUint64S (String, (CHAR16 **) NULL, &Result); - return Result; -} - -/** - Check if a ASCII character is a decimal character. - - This internal function checks if a Unicode character is a - decimal character. The valid decimal character is from - '0' to '9'. - - @param Char The character to check against. - - @retval TRUE If the Char is a decmial character. - @retval FALSE If the Char is not a decmial character. - -**/ -BOOLEAN -EFIAPI -InternalAsciiIsDecimalDigitCharacter ( - IN CHAR8 Char - ) -{ - return (BOOLEAN) (Char >= '0' && Char <= '9'); -} - -/** - Check if a ASCII character is a hexadecimal character. - - This internal function checks if a ASCII character is a - decimal character. The valid hexadecimal character is - L'0' to L'9', L'a' to L'f', or L'A' to L'F'. - - - @param Char The character to check against. - - @retval TRUE If the Char is a hexadecmial character. - @retval FALSE If the Char is not a hexadecmial character. - -**/ -BOOLEAN -EFIAPI -InternalAsciiIsHexaDecimalDigitCharacter ( - IN CHAR8 Char - ) -{ - - return (BOOLEAN) (InternalAsciiIsDecimalDigitCharacter (Char) || - (Char >= 'A' && Char <= 'F') || - (Char >= 'a' && Char <= 'f')); -} - -/** - Returns the length of a Null-terminated ASCII string. - - This function returns the number of ASCII characters in the Null-terminated - ASCII string specified by String. - - If Length > 0 and Destination is NULL, then ASSERT(). - If Length > 0 and Source is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and String contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @return The length of String. - -**/ -UINTN -EFIAPI -AsciiStrLen ( - IN CONST CHAR8 *String - ) -{ - UINTN Length; - - ASSERT (String != NULL); - - for (Length = 0; *String != '\0'; String++, Length++) { - // - // If PcdMaximumUnicodeStringLength is not zero, - // length should not more than PcdMaximumUnicodeStringLength - // - } - return Length; -} - -/** - Returns the size of a Null-terminated ASCII string in bytes, including the - Null terminator. - - This function returns the size, in bytes, of the Null-terminated ASCII string - specified by String. - - If String is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and String contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @return The size of String. - -**/ -UINTN -EFIAPI -AsciiStrSize ( - IN CONST CHAR8 *String - ) -{ - return (AsciiStrLen (String) + 1) * sizeof (*String); -} - -/** - Compares two Null-terminated ASCII strings, and returns the difference - between the first mismatched ASCII characters. - - This function compares the Null-terminated ASCII string FirstString to the - Null-terminated ASCII string SecondString. If FirstString is identical to - SecondString, then 0 is returned. Otherwise, the value returned is the first - mismatched ASCII character in SecondString subtracted from the first - mismatched ASCII character in FirstString. - - If FirstString is NULL, then ASSERT(). - If SecondString is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and FirstString contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and SecondString contains more - than PcdMaximumAsciiStringLength ASCII characters, not including the - Null-terminator, then ASSERT(). - - @param FirstString A pointer to a Null-terminated ASCII string. - @param SecondString A pointer to a Null-terminated ASCII string. - - @retval ==0 FirstString is identical to SecondString. - @retval !=0 FirstString is not identical to SecondString. - -**/ -INTN -EFIAPI -AsciiStrCmp ( - IN CONST CHAR8 *FirstString, - IN CONST CHAR8 *SecondString - ) -{ - // - // ASSERT both strings are less long than PcdMaximumAsciiStringLength - // - ASSERT (AsciiStrSize (FirstString)); - ASSERT (AsciiStrSize (SecondString)); - - while ((*FirstString != '\0') && (*FirstString == *SecondString)) { - FirstString++; - SecondString++; - } - - return *FirstString - *SecondString; -} - -/** - Converts a lowercase Ascii character to upper one. - - If Chr is lowercase Ascii character, then converts it to upper one. - - If Value >= 0xA0, then ASSERT(). - If (Value & 0x0F) >= 0x0A, then ASSERT(). - - @param Chr one Ascii character - - @return The uppercase value of Ascii character - -**/ -CHAR8 -EFIAPI -InternalBaseLibAsciiToUpper ( - IN CHAR8 Chr - ) -{ - return (UINT8) ((Chr >= 'a' && Chr <= 'z') ? Chr - ('a' - 'A') : Chr); -} - -/** - Convert a ASCII character to numerical value. - - This internal function only deal with Unicode character - which maps to a valid hexadecimal ASII character, i.e. - '0' to '9', 'a' to 'f' or 'A' to 'F'. For other - ASCII character, the value returned does not make sense. - - @param Char The character to convert. - - @return The numerical value converted. - -**/ -UINTN -EFIAPI -InternalAsciiHexCharToUintn ( - IN CHAR8 Char - ) -{ - if (InternalIsDecimalDigitCharacter (Char)) { - return Char - '0'; - } - - return (10 + InternalBaseLibAsciiToUpper (Char) - 'A'); -} - - -/** - Performs a case insensitive comparison of two Null-terminated ASCII strings, - and returns the difference between the first mismatched ASCII characters. - - This function performs a case insensitive comparison of the Null-terminated - ASCII string FirstString to the Null-terminated ASCII string SecondString. If - FirstString is identical to SecondString, then 0 is returned. Otherwise, the - value returned is the first mismatched lower case ASCII character in - SecondString subtracted from the first mismatched lower case ASCII character - in FirstString. - - If FirstString is NULL, then ASSERT(). - If SecondString is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and FirstString contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - If PcdMaximumAsciiStringLength is not zero and SecondString contains more - than PcdMaximumAsciiStringLength ASCII characters, not including the - Null-terminator, then ASSERT(). - - @param FirstString A pointer to a Null-terminated ASCII string. - @param SecondString A pointer to a Null-terminated ASCII string. - - @retval ==0 FirstString is identical to SecondString using case insensitive - comparisons. - @retval !=0 FirstString is not identical to SecondString using case - insensitive comparisons. - -**/ -INTN -EFIAPI -AsciiStriCmp ( - IN CONST CHAR8 *FirstString, - IN CONST CHAR8 *SecondString - ) -{ - CHAR8 UpperFirstString; - CHAR8 UpperSecondString; - - // - // ASSERT both strings are less long than PcdMaximumAsciiStringLength - // - ASSERT (AsciiStrSize (FirstString)); - ASSERT (AsciiStrSize (SecondString)); - - UpperFirstString = InternalBaseLibAsciiToUpper (*FirstString); - UpperSecondString = InternalBaseLibAsciiToUpper (*SecondString); - while ((*FirstString != '\0') && (*SecondString != '\0') && (UpperFirstString == UpperSecondString)) { - FirstString++; - SecondString++; - UpperFirstString = InternalBaseLibAsciiToUpper (*FirstString); - UpperSecondString = InternalBaseLibAsciiToUpper (*SecondString); - } - - return UpperFirstString - UpperSecondString; -} - -/** - Compares two Null-terminated ASCII strings with maximum lengths, and returns - the difference between the first mismatched ASCII characters. - - This function compares the Null-terminated ASCII string FirstString to the - Null-terminated ASCII string SecondString. At most, Length ASCII characters - will be compared. If Length is 0, then 0 is returned. If FirstString is - identical to SecondString, then 0 is returned. Otherwise, the value returned - is the first mismatched ASCII character in SecondString subtracted from the - first mismatched ASCII character in FirstString. - - If Length > 0 and FirstString is NULL, then ASSERT(). - If Length > 0 and SecondString is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and Length is greater than - PcdMaximumAsciiStringLength, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and FirstString contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and SecondString contains more than - PcdMaximumAsciiStringLength ASCII characters, not including the Null-terminator, - then ASSERT(). - - @param FirstString A pointer to a Null-terminated ASCII string. - @param SecondString A pointer to a Null-terminated ASCII string. - @param Length The maximum number of ASCII characters for compare. - - @retval ==0 FirstString is identical to SecondString. - @retval !=0 FirstString is not identical to SecondString. - -**/ -INTN -EFIAPI -AsciiStrnCmp ( - IN CONST CHAR8 *FirstString, - IN CONST CHAR8 *SecondString, - IN UINTN Length - ) -{ - if (Length == 0) { - return 0; - } - - // - // ASSERT both strings are less long than PcdMaximumAsciiStringLength - // - ASSERT (AsciiStrSize (FirstString)); - ASSERT (AsciiStrSize (SecondString)); - - while ((*FirstString != '\0') && - (*SecondString != '\0') && - (*FirstString == *SecondString) && - (Length > 1)) { - FirstString++; - SecondString++; - Length--; - } - return *FirstString - *SecondString; -} - -/** - Returns the first occurrence of a Null-terminated ASCII sub-string - in a Null-terminated ASCII string. - - This function scans the contents of the ASCII string specified by String - and returns the first occurrence of SearchString. If SearchString is not - found in String, then NULL is returned. If the length of SearchString is zero, - then String is returned. - - If String is NULL, then ASSERT(). - If SearchString is NULL, then ASSERT(). - - If PcdMaximumAsciiStringLength is not zero, and SearchString or - String contains more than PcdMaximumAsciiStringLength Unicode characters - not including the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - @param SearchString A pointer to a Null-terminated ASCII string to search for. - - @retval NULL If the SearchString does not appear in String. - @retval others If there is a match return the first occurrence of SearchingString. - If the length of SearchString is zero,return String. - -**/ -CHAR8 * -EFIAPI -AsciiStrStr ( - IN CONST CHAR8 *String, - IN CONST CHAR8 *SearchString - ) -{ - CONST CHAR8 *FirstMatch; - CONST CHAR8 *SearchStringTmp; - - // - // ASSERT both strings are less long than PcdMaximumAsciiStringLength - // - ASSERT (AsciiStrSize (String) != 0); - ASSERT (AsciiStrSize (SearchString) != 0); - - if (*SearchString == '\0') { - return (CHAR8 *) String; - } - - while (*String != '\0') { - SearchStringTmp = SearchString; - FirstMatch = String; - - while ((*String == *SearchStringTmp) - && (*String != '\0')) { - String++; - SearchStringTmp++; - } - - if (*SearchStringTmp == '\0') { - return (CHAR8 *) FirstMatch; - } - - if (*String == '\0') { - return NULL; - } - - String = FirstMatch + 1; - } - - return NULL; -} - -/** - Convert a Null-terminated ASCII decimal string to a value of type - UINTN. - - This function returns a value of type UINTN by interpreting the contents - of the ASCII string String as a decimal number. The format of the input - ASCII string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before the digits. - The running zero in the beginning of [decimal digits] will be ignored. Then, the - function stops at the first character that is a not a valid decimal character or - Null-terminator, whichever on comes first. - - If String has only pad spaces, then 0 is returned. - If String has no pad spaces or valid decimal digits, then 0 is returned. - If the number represented by String overflows according to the range defined by - UINTN, then MAX_UINTN is returned. - If String is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength ASCII characters not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @retval Value translated from String. - -**/ -UINTN -EFIAPI -AsciiStrDecimalToUintn ( - IN CONST CHAR8 *String - ) -{ - UINTN Result; - - AsciiStrDecimalToUintnS (String, (CHAR8 **) NULL, &Result); - return Result; -} - - -/** - Convert a Null-terminated ASCII decimal string to a value of type - UINT64. - - This function returns a value of type UINT64 by interpreting the contents - of the ASCII string String as a decimal number. The format of the input - ASCII string String is: - - [spaces] [decimal digits]. - - The valid decimal digit character is in the range [0-9]. The function will - ignore the pad space, which includes spaces or tab characters, before the digits. - The running zero in the beginning of [decimal digits] will be ignored. Then, the - function stops at the first character that is a not a valid decimal character or - Null-terminator, whichever on comes first. - - If String has only pad spaces, then 0 is returned. - If String has no pad spaces or valid decimal digits, then 0 is returned. - If the number represented by String overflows according to the range defined by - UINT64, then MAX_UINT64 is returned. - If String is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, and String contains more than - PcdMaximumAsciiStringLength ASCII characters not including the Null-terminator, - then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @retval Value translated from String. - -**/ -UINT64 -EFIAPI -AsciiStrDecimalToUint64 ( - IN CONST CHAR8 *String - ) -{ - UINT64 Result; - - AsciiStrDecimalToUint64S (String, (CHAR8 **) NULL, &Result); - return Result; -} - -/** - Convert a Null-terminated ASCII hexadecimal string to a value of type UINTN. - - This function returns a value of type UINTN by interpreting the contents of - the ASCII string String as a hexadecimal number. The format of the input ASCII - string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If "x" - appears in the input string, it must be prefixed with at least one 0. The function - will ignore the pad space, which includes spaces or tab characters, before [zeros], - [x] or [hexadecimal digits]. The running zero before [x] or [hexadecimal digits] - will be ignored. Then, the decoding starts after [x] or the first valid hexadecimal - digit. Then, the function stops at the first character that is a not a valid - hexadecimal character or Null-terminator, whichever on comes first. - - If String has only pad spaces, then 0 is returned. - If String has no leading pad spaces, leading zeros or valid hexadecimal digits, then - 0 is returned. - - If the number represented by String overflows according to the range defined by UINTN, - then MAX_UINTN is returned. - If String is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, - and String contains more than PcdMaximumAsciiStringLength ASCII characters not including - the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @retval Value translated from String. - -**/ -UINTN -EFIAPI -AsciiStrHexToUintn ( - IN CONST CHAR8 *String - ) -{ - UINTN Result; - - AsciiStrHexToUintnS (String, (CHAR8 **) NULL, &Result); - return Result; -} - - -/** - Convert a Null-terminated ASCII hexadecimal string to a value of type UINT64. - - This function returns a value of type UINT64 by interpreting the contents of - the ASCII string String as a hexadecimal number. The format of the input ASCII - string String is: - - [spaces][zeros][x][hexadecimal digits]. - - The valid hexadecimal digit character is in the range [0-9], [a-f] and [A-F]. - The prefix "0x" is optional. Both "x" and "X" is allowed in "0x" prefix. If "x" - appears in the input string, it must be prefixed with at least one 0. The function - will ignore the pad space, which includes spaces or tab characters, before [zeros], - [x] or [hexadecimal digits]. The running zero before [x] or [hexadecimal digits] - will be ignored. Then, the decoding starts after [x] or the first valid hexadecimal - digit. Then, the function stops at the first character that is a not a valid - hexadecimal character or Null-terminator, whichever on comes first. - - If String has only pad spaces, then 0 is returned. - If String has no leading pad spaces, leading zeros or valid hexadecimal digits, then - 0 is returned. - - If the number represented by String overflows according to the range defined by UINT64, - then MAX_UINT64 is returned. - If String is NULL, then ASSERT(). - If PcdMaximumAsciiStringLength is not zero, - and String contains more than PcdMaximumAsciiStringLength ASCII characters not including - the Null-terminator, then ASSERT(). - - @param String A pointer to a Null-terminated ASCII string. - - @retval Value translated from String. - -**/ -UINT64 -EFIAPI -AsciiStrHexToUint64 ( - IN CONST CHAR8 *String - ) -{ - UINT64 Result; - - AsciiStrHexToUint64S (String, (CHAR8 **) NULL, &Result); - return Result; -} - -/** - Converts an 8-bit value to an 8-bit BCD value. - - Converts the 8-bit value specified by Value to BCD. The BCD value is - returned. - - If Value >= 100, then ASSERT(). - - @param Value The 8-bit value to convert to BCD. Range 0..99. - - @return The BCD value. - -**/ -UINT8 -EFIAPI -DecimalToBcd8 ( - IN UINT8 Value - ) -{ - ASSERT (Value < 100); - return (UINT8) (((Value / 10) << 4) | (Value % 10)); -} - -/** - Converts an 8-bit BCD value to an 8-bit value. - - Converts the 8-bit BCD value specified by Value to an 8-bit value. The 8-bit - value is returned. - - If Value >= 0xA0, then ASSERT(). - If (Value & 0x0F) >= 0x0A, then ASSERT(). - - @param Value The 8-bit BCD value to convert to an 8-bit value. - - @return The 8-bit value is returned. - -**/ -UINT8 -EFIAPI -BcdToDecimal8 ( - IN UINT8 Value - ) -{ - ASSERT (Value < 0xa0); - ASSERT ((Value & 0xf) < 0xa); - return (UINT8) ((Value >> 4) * 10 + (Value & 0xf)); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c deleted file mode 100644 index c04444750f3..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes16.c +++ /dev/null @@ -1,31 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Switches the endianess of a 16-bit integer. - - This function swaps the bytes in a 16-bit unsigned value to switch the value - from little endian to big endian or vice versa. The byte swapped value is - returned. - - @param Value A 16-bit unsigned value. - - @return The byte swapped Value. - -**/ -UINT16 -EFIAPI -SwapBytes16 ( - IN UINT16 Value - ) -{ - return (UINT16) ((Value<< 8) | (Value>> 8)); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c deleted file mode 100644 index 5e2d0edffd0..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes32.c +++ /dev/null @@ -1,37 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Switches the endianess of a 32-bit integer. - - This function swaps the bytes in a 32-bit unsigned value to switch the value - from little endian to big endian or vice versa. The byte swapped value is - returned. - - @param Value A 32-bit unsigned value. - - @return The byte swapped Value. - -**/ -UINT32 -EFIAPI -SwapBytes32 ( - IN UINT32 Value - ) -{ - UINT32 LowerBytes; - UINT32 HigherBytes; - - LowerBytes = (UINT32) SwapBytes16 ((UINT16) Value); - HigherBytes = (UINT32) SwapBytes16 ((UINT16) (Value >> 16)); - - return (LowerBytes << 16 | HigherBytes); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c deleted file mode 100644 index f56580168ea..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SwapBytes64.c +++ /dev/null @@ -1,37 +0,0 @@ -/** @file - Math worker functions. - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -UINT64 -EFIAPI -InternalMathSwapBytes64 ( - IN UINT64 Operand - ); - -/** - Switches the endianess of a 64-bit integer. - - This function swaps the bytes in a 64-bit unsigned value to switch the value - from little endian to big endian or vice versa. The byte swapped value is - returned. - - @param Value A 64-bit unsigned value. - - @return The byte swapped Value. - -**/ -UINT64 -EFIAPI -SwapBytes64 ( - IN UINT64 Value - ) -{ - return InternalMathSwapBytes64 (Value); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c deleted file mode 100644 index b011c147125..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/SwitchStackNull.c +++ /dev/null @@ -1,52 +0,0 @@ -/** @file - Switch Stack functions. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Transfers control to a function starting with a new stack. - - Transfers control to the function specified by EntryPoint using the - new stack specified by NewStack and passing in the parameters specified - by Context1 and Context2. Context1 and Context2 are optional and may - be NULL. The function EntryPoint must never return. This function - supports a variable number of arguments following the NewStack parameter. - These additional arguments are ignored on IA-32, x64, and EBC. - IPF CPUs expect one additional parameter of type VOID * that specifies - the new backing store pointer. - - If EntryPoint is NULL, then ASSERT(). - If NewStack is NULL, then ASSERT(). - - @param EntryPoint A pointer to function to call with the new stack. - @param Context1 A pointer to the context to pass into the EntryPoint - function. - @param Context2 A pointer to the context to pass into the EntryPoint - function. - @param NewStack A pointer to the new stack to use for the EntryPoint - function. - @param ... This variable argument list is ignored for IA32, x64, and EBC. - For IPF, this variable argument list is expected to contain - a single parameter of type VOID * that specifies the new backing - store pointer. - - -**/ -VOID -EFIAPI -SwitchStack ( - IN SWITCH_STACK_ENTRY_POINT EntryPoint, - IN VOID *Context1, OPTIONAL - IN VOID *Context2, OPTIONAL - IN VOID *NewStack, - ... - ) -{ - ASSERT (FALSE); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c b/MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c deleted file mode 100644 index fda732b6626..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/Unaligned.c +++ /dev/null @@ -1,216 +0,0 @@ -/** @file - Unaligned access functions of BaseLib. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Reads a 16-bit value from memory that may be unaligned. - - This function returns the 16-bit value pointed to by Buffer. The function - guarantees that the read operation does not produce an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 16-bit value that may be unaligned. - - @return The 16-bit value read from Buffer. - -**/ -UINT16 -EFIAPI -ReadUnaligned16 ( - IN CONST UINT16 *Buffer - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer; -} - -/** - Writes a 16-bit value to memory that may be unaligned. - - This function writes the 16-bit value specified by Value to Buffer. Value is - returned. The function guarantees that the write operation does not produce - an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 16-bit value that may be unaligned. - @param Value 16-bit value to write to Buffer. - - @return The 16-bit value to write to Buffer. - -**/ -UINT16 -EFIAPI -WriteUnaligned16 ( - OUT UINT16 *Buffer, - IN UINT16 Value - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer = Value; -} - -/** - Reads a 24-bit value from memory that may be unaligned. - - This function returns the 24-bit value pointed to by Buffer. The function - guarantees that the read operation does not produce an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 24-bit value that may be unaligned. - - @return The 24-bit value read from Buffer. - -**/ -UINT32 -EFIAPI -ReadUnaligned24 ( - IN CONST UINT32 *Buffer - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer & 0xffffff; -} - -/** - Writes a 24-bit value to memory that may be unaligned. - - This function writes the 24-bit value specified by Value to Buffer. Value is - returned. The function guarantees that the write operation does not produce - an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 24-bit value that may be unaligned. - @param Value 24-bit value to write to Buffer. - - @return The 24-bit value to write to Buffer. - -**/ -UINT32 -EFIAPI -WriteUnaligned24 ( - OUT UINT32 *Buffer, - IN UINT32 Value - ) -{ - ASSERT (Buffer != NULL); - - *Buffer = BitFieldWrite32 (*Buffer, 0, 23, Value); - return Value; -} - -/** - Reads a 32-bit value from memory that may be unaligned. - - This function returns the 32-bit value pointed to by Buffer. The function - guarantees that the read operation does not produce an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 32-bit value that may be unaligned. - - @return The 32-bit value read from Buffer. - -**/ -UINT32 -EFIAPI -ReadUnaligned32 ( - IN CONST UINT32 *Buffer - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer; -} - -/** - Writes a 32-bit value to memory that may be unaligned. - - This function writes the 32-bit value specified by Value to Buffer. Value is - returned. The function guarantees that the write operation does not produce - an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 32-bit value that may be unaligned. - @param Value The 32-bit value to write to Buffer. - - @return The 32-bit value to write to Buffer. - -**/ -UINT32 -EFIAPI -WriteUnaligned32 ( - OUT UINT32 *Buffer, - IN UINT32 Value - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer = Value; -} - -/** - Reads a 64-bit value from memory that may be unaligned. - - This function returns the 64-bit value pointed to by Buffer. The function - guarantees that the read operation does not produce an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 64-bit value that may be unaligned. - - @return The 64-bit value read from Buffer. - -**/ -UINT64 -EFIAPI -ReadUnaligned64 ( - IN CONST UINT64 *Buffer - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer; -} - -/** - Writes a 64-bit value to memory that may be unaligned. - - This function writes the 64-bit value specified by Value to Buffer. Value is - returned. The function guarantees that the write operation does not produce - an alignment fault. - - If the Buffer is NULL, then ASSERT(). - - @param Buffer A pointer to a 64-bit value that may be unaligned. - @param Value The 64-bit value to write to Buffer. - - @return The 64-bit value to write to Buffer. - -**/ -UINT64 -EFIAPI -WriteUnaligned64 ( - OUT UINT64 *Buffer, - IN UINT64 Value - ) -{ - ASSERT (Buffer != NULL); - - return *Buffer = Value; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm deleted file mode 100644 index 7e7fe99670f..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X64/RdRand.nasm +++ /dev/null @@ -1,77 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2015 - 2016, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; RdRand.nasm -; -; Abstract: -; -; Generates random number through CPU RdRand instruction under 64-bit platform. -; -; Notes: -; -;------------------------------------------------------------------------------ - - DEFAULT REL - SECTION .text - -;------------------------------------------------------------------------------ -; Generates a 16 bit random number through RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand16 (UINT16 *Rand); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand16) -ASM_PFX(InternalX86RdRand16): - ; rdrand ax ; generate a 16 bit RN into eax, - ; CF=1 if RN generated ok, otherwise CF=0 - db 0xf, 0xc7, 0xf0 ; rdrand r16: "0f c7 /6 ModRM:r/m(w)" - jc rn16_ok ; jmp if CF=1 - xor rax, rax ; reg=0 if CF=0 - ret ; return with failure status -rn16_ok: - mov [rcx], ax - mov rax, 1 - ret - -;------------------------------------------------------------------------------ -; Generates a 32 bit random number through RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand32 (UINT32 *Rand); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand32) -ASM_PFX(InternalX86RdRand32): - ; rdrand eax ; generate a 32 bit RN into eax, - ; CF=1 if RN generated ok, otherwise CF=0 - db 0xf, 0xc7, 0xf0 ; rdrand r32: "0f c7 /6 ModRM:r/m(w)" - jc rn32_ok ; jmp if CF=1 - xor rax, rax ; reg=0 if CF=0 - ret ; return with failure status -rn32_ok: - mov [rcx], eax - mov rax, 1 - ret - -;------------------------------------------------------------------------------ -; Generates a 64 bit random number through one RDRAND instruction. -; Return TRUE if Rand generated successfully, or FALSE if not. -; -; BOOLEAN EFIAPI InternalX86RdRand64 (UINT64 *Random); -;------------------------------------------------------------------------------ -global ASM_PFX(InternalX86RdRand64) -ASM_PFX(InternalX86RdRand64): - ; rdrand rax ; generate a 64 bit RN into rax, - ; CF=1 if RN generated ok, otherwise CF=0 - db 0x48, 0xf, 0xc7, 0xf0 ; rdrand r64: "REX.W + 0f c7 /6 ModRM:r/m(w)" - jc rn64_ok ; jmp if CF=1 - xor rax, rax ; reg=0 if CF=0 - ret ; return with failure status -rn64_ok: - mov [rcx], rax - mov rax, 1 - ret - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm b/MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm deleted file mode 100644 index 45672d680e6..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X64/ReadTsc.nasm +++ /dev/null @@ -1,34 +0,0 @@ -;------------------------------------------------------------------------------ -; -; Copyright (c) 2006, Intel Corporation. All rights reserved.
-; SPDX-License-Identifier: BSD-2-Clause-Patent -; -; Module Name: -; -; ReadTsc.Asm -; -; Abstract: -; -; AsmReadTsc function -; -; Notes: -; -;------------------------------------------------------------------------------ - - DEFAULT REL - SECTION .text - -;------------------------------------------------------------------------------ -; UINT64 -; EFIAPI -; AsmReadTsc ( -; VOID -; ); -;------------------------------------------------------------------------------ -global ASM_PFX(AsmReadTsc) -ASM_PFX(AsmReadTsc): - rdtsc - shl rdx, 0x20 - or rax, rdx - ret - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c deleted file mode 100644 index ab16ca6e286..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86Cr.c +++ /dev/null @@ -1,180 +0,0 @@ -/** @file - Base Library CPU Functions for all architectures. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -UINTN gCr0; -UINTN gCr2; -UINTN gCr3; -UINTN gCr4; - -/** - Reads the current value of the Control Register 0 (CR0). - - Reads and returns the current value of CR0. This function is only available - on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on - x64. - - @return The value of the Control Register 0 (CR0). - -**/ -UINTN -EFIAPI -AsmReadCr0 ( - VOID - ) -{ - return gCr0; -} - - -/** - Reads the current value of the Control Register 2 (CR2). - - Reads and returns the current value of CR2. This function is only available - on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on - x64. - - @return The value of the Control Register 2 (CR2). - -**/ -UINTN -EFIAPI -AsmReadCr2 ( - VOID - ) -{ - return gCr2; -} - - -/** - Reads the current value of the Control Register 3 (CR3). - - Reads and returns the current value of CR3. This function is only available - on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on - x64. - - @return The value of the Control Register 3 (CR3). - -**/ -UINTN -EFIAPI -AsmReadCr3 ( - VOID - ) -{ - return gCr3; -} - - -/** - Reads the current value of the Control Register 4 (CR4). - - Reads and returns the current value of CR4. This function is only available - on IA-32 and x64. This returns a 32-bit value on IA-32 and a 64-bit value on - x64. - - @return The value of the Control Register 4 (CR4). - -**/ -UINTN -EFIAPI -AsmReadCr4 ( - VOID - ) -{ - return gCr4; -} - - -/** - Writes a value to Control Register 0 (CR0). - - Writes and returns a new value to CR0. This function is only available on - IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. - - @param Cr0 The value to write to CR0. - - @return The value written to CR0. - -**/ -UINTN -EFIAPI -AsmWriteCr0 ( - UINTN Cr0 - ) -{ - gCr0 = Cr0; - return Cr0; -} - -/** - Writes a value to Control Register 2 (CR2). - - Writes and returns a new value to CR2. This function is only available on - IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. - - @param Cr2 The value to write to CR2. - - @return The value written to CR2. - -**/ -UINTN -EFIAPI -AsmWriteCr2 ( - UINTN Cr2 - ) -{ - gCr2 = Cr2; - return Cr2; -} - - -/** - Writes a value to Control Register 3 (CR3). - - Writes and returns a new value to CR3. This function is only available on - IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. - - @param Cr3 The value to write to CR3. - - @return The value written to CR3. - -**/ -UINTN -EFIAPI -AsmWriteCr3 ( - UINTN Cr3 - ) -{ - gCr3 = Cr3; - return Cr3; -} - - -/** - Writes a value to Control Register 4 (CR4). - - Writes and returns a new value to CR4. This function is only available on - IA-32 and x64. This writes a 32-bit value on IA-32 and a 64-bit value on x64. - - @param Cr4 The value to write to CR4. - - @return The value written to CR4. - -**/ -UINTN -EFIAPI -AsmWriteCr4 ( - UINTN Cr4 - ) -{ - gCr4 = Cr4; - return Cr4; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c deleted file mode 100644 index 255264fd71b..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86DisablePaging64Null.c +++ /dev/null @@ -1,53 +0,0 @@ -/** @file - IA-32/x64 AsmDisablePaging64() - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Disables the 64-bit paging mode on the CPU. - - Disables the 64-bit paging mode on the CPU and returns to 32-bit protected - mode. This function assumes the current execution mode is 64-paging mode. - This function is only available on x64. After the 64-bit paging mode is - disabled, control is transferred to the function specified by EntryPoint - using the new stack specified by NewStack and passing in the parameters - specified by Context1 and Context2. Context1 and Context2 are optional and - may be 0. The function EntryPoint must never return. - - If the current execution mode is not 64-bit paged mode, then ASSERT(). - If EntryPoint is 0, then ASSERT(). - If NewStack is 0, then ASSERT(). - - @param Cs The 16-bit selector to load in the CS before EntryPoint - is called. The descriptor in the GDT that this selector - references must be setup for 32-bit protected mode. - @param EntryPoint The 64-bit virtual address of the function to call with - the new stack after paging is disabled. - @param Context1 The 64-bit virtual address of the context to pass into - the EntryPoint function as the first parameter after - paging is disabled. - @param Context2 The 64-bit virtual address of the context to pass into - the EntryPoint function as the second parameter after - paging is disabled. - @param NewStack The 64-bit virtual address of the new stack to use for - the EntryPoint function after paging is disabled. - -**/ -VOID -EFIAPI -AsmDisablePaging64 ( - IN UINT16 Cs, - IN UINT32 EntryPoint, - IN UINT32 Context1, OPTIONAL - IN UINT32 Context2, OPTIONAL - IN UINT32 NewStack - ) -{ - ASSERT (FALSE); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c deleted file mode 100644 index 057ec9781f9..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86Dr.c +++ /dev/null @@ -1,170 +0,0 @@ -/** @file - Base Library CPU Functions for all architectures. - - Copyright (c) 2006 - 2010, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -UINTN gDr0; -UINTN gDr1; -UINTN gDr2; -UINTN gDr3; -UINTN gDr4; -UINTN gDr5; -UINTN gDr6; -UINTN gDr7; - -UINTN -EFIAPI -AsmReadDr0 ( - VOID - ) -{ - return gDr0; -} - -UINTN -EFIAPI -AsmReadDr1 ( - VOID - ) -{ - return gDr1; -} - -UINTN -EFIAPI -AsmReadDr2 ( - VOID - ) -{ - return gDr2; -} - -UINTN -EFIAPI -AsmReadDr3 ( - VOID - ) -{ - return gDr3; -} - -UINTN -EFIAPI -AsmReadDr4 ( - VOID - ) -{ - return gDr4; -} - -UINTN -EFIAPI -AsmReadDr5 ( - VOID - ) -{ - return gDr5; -} - -UINTN -EFIAPI -AsmReadDr6 ( - VOID - ) -{ - return gDr6; -} - -UINTN -EFIAPI -AsmReadDr7 ( - VOID - ) -{ - return gDr7; -} - -UINTN -EFIAPI -AsmWriteDr0 ( - UINTN Dr0 - ) -{ - gDr0 = Dr0; - return Dr0; -} - -UINTN -EFIAPI -AsmWriteDr1 ( - UINTN Dr1 - ) -{ - gDr1 = Dr1; - return Dr1; -} - -UINTN -EFIAPI -AsmWriteDr2 ( - UINTN Dr2 - ) -{ - gDr2 = Dr2; - return Dr2; -} - -UINTN -EFIAPI -AsmWriteDr3 ( - UINTN Dr3 - ) -{ - gDr3 = Dr3; - return Dr3; -} - -UINTN -EFIAPI -AsmWriteDr4 ( - UINTN Dr4 - ) -{ - gDr4 = Dr4; - return Dr4; -} - -UINTN -EFIAPI -AsmWriteDr5 ( - UINTN Dr5 - ) -{ - gDr5 = Dr5; - return Dr5; -} - -UINTN -EFIAPI -AsmWriteDr6 ( - UINTN Dr6 - ) -{ - gDr6 = Dr6; - return Dr6; -} - -UINTN -EFIAPI -AsmWriteDr7 ( - UINTN Dr7 - ) -{ - gDr7 = Dr7; - return Dr7; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c deleted file mode 100644 index 9a7a7dad4da..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86GdtrNull.c +++ /dev/null @@ -1,50 +0,0 @@ -/** @file - IA-32/x64 AsmReadGdtr() - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Reads the current Global Descriptor Table Register(GDTR) descriptor. - - Reads and returns the current GDTR descriptor and returns it in Gdtr. This - function is only available on IA-32 and x64. - - If Gdtr is NULL, then ASSERT(). - - @param Gdtr The pointer to a GDTR descriptor. - -**/ -VOID -EFIAPI -AsmReadGdtr ( - OUT IA32_DESCRIPTOR *Gdtr - ) -{ - ASSERT (FALSE); -} - -/** - Writes the current Global Descriptor Table Register (GDTR) descriptor. - - Writes and the current GDTR descriptor specified by Gdtr. This function is - only available on IA-32 and x64. - - If Gdtr is NULL, then ASSERT(). - - @param Gdtr The pointer to a GDTR descriptor. - -**/ -VOID -EFIAPI -AsmWriteGdtr ( - IN CONST IA32_DESCRIPTOR *Gdtr - ) -{ - ASSERT (FALSE); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c deleted file mode 100644 index 3fb1aa835a1..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86IdtrNull.c +++ /dev/null @@ -1,50 +0,0 @@ -/** @file - IA-32/x64 AsmReadIdtr() - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Reads the current Interrupt Descriptor Table Register(IDTR) descriptor. - - Reads and returns the current IDTR descriptor and returns it in Idtr. This - function is only available on IA-32 and x64. - - If Idtr is NULL, then ASSERT(). - - @param Idtr The pointer to a IDTR descriptor. - -**/ -VOID -EFIAPI -AsmReadIdtr ( - OUT IA32_DESCRIPTOR *Idtr - ) -{ - ASSERT (FALSE); -} - -/** - Writes the current Interrupt Descriptor Table Register(IDTR) descriptor. - - Writes the current IDTR descriptor and returns it in Idtr. This function is - only available on IA-32 and x64. - - If Idtr is NULL, then ASSERT(). - - @param Idtr The pointer to a IDTR descriptor. - -**/ -VOID -EFIAPI -AsmWriteIdtr ( - IN CONST IA32_DESCRIPTOR *Idtr - ) -{ - ASSERT (FALSE); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c deleted file mode 100644 index da85c1bd451..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceGcc.c +++ /dev/null @@ -1,29 +0,0 @@ -/** @file - GCC inline implementation of BaseLib processor specific functions. - - Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.
- Portions copyright (c) 2008 - 2009, Apple Inc. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - - -/** - Used to serialize load and store operations. - - All loads and stores that proceed calls to this function are guaranteed to be - globally visible when this function returns. - -**/ -VOID -EFIAPI -MemoryFence ( - VOID - ) -{ - // This is a little bit of overkill and it is more about the compiler that it is - // actually processor synchronization. This is like the _ReadWriteBarrier - // Microsoft specific intrinsic - __asm__ __volatile__ ("":::"memory"); -} - diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c deleted file mode 100644 index 5e61a4a782b..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86MemoryFenceMsvc.c +++ /dev/null @@ -1,27 +0,0 @@ -/** @file - IA-32/x64 MemoryFence(). - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -void _ReadWriteBarrier (void); -#pragma intrinsic(_ReadWriteBarrier) - -/** - Used to serialize load and store operations. - - All loads and stores that proceed calls to this function are guaranteed to be - globally visible when this function returns. - -**/ -VOID -EFIAPI -MemoryFence ( - VOID - ) -{ - _ReadWriteBarrier (); - return; -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c deleted file mode 100644 index e833afb955f..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86PatchInstruction.c +++ /dev/null @@ -1,84 +0,0 @@ -/** @file - IA-32/x64 PatchInstructionX86() - - Copyright (C) 2018, Intel Corporation. All rights reserved.
- Copyright (C) 2018, Red Hat, Inc. - - SPDX-License-Identifier: BSD-2-Clause-Patent -**/ - -#include -#include - -/** - Patch the immediate operand of an IA32 or X64 instruction such that the byte, - word, dword or qword operand is encoded at the end of the instruction's - binary representation. - - This function should be used to update object code that was compiled with - NASM from assembly source code. Example: - - NASM source code: - - mov eax, strict dword 0 ; the imm32 zero operand will be patched - ASM_PFX(gPatchCr3): - mov cr3, eax - - C source code: - - X86_ASSEMBLY_PATCH_LABEL gPatchCr3; - PatchInstructionX86 (gPatchCr3, AsmReadCr3 (), 4); - - @param[out] InstructionEnd Pointer right past the instruction to patch. The - immediate operand to patch is expected to - comprise the trailing bytes of the instruction. - If InstructionEnd is closer to address 0 than - ValueSize permits, then ASSERT(). - - @param[in] PatchValue The constant to write to the immediate operand. - The caller is responsible for ensuring that - PatchValue can be represented in the byte, word, - dword or qword operand (as indicated through - ValueSize); otherwise ASSERT(). - - @param[in] ValueSize The size of the operand in bytes; must be 1, 2, - 4, or 8. ASSERT() otherwise. -**/ -VOID -EFIAPI -PatchInstructionX86 ( - OUT X86_ASSEMBLY_PATCH_LABEL *InstructionEnd, - IN UINT64 PatchValue, - IN UINTN ValueSize - ) -{ - // - // The equality ((UINTN)InstructionEnd == ValueSize) would assume a zero-size - // instruction at address 0; forbid it. - // - ASSERT ((UINTN)InstructionEnd > ValueSize); - - switch (ValueSize) { - case 1: - ASSERT (PatchValue <= MAX_UINT8); - *((UINT8 *)(UINTN)InstructionEnd - 1) = (UINT8)PatchValue; - break; - - case 2: - ASSERT (PatchValue <= MAX_UINT16); - WriteUnaligned16 ((UINT16 *)(UINTN)InstructionEnd - 1, (UINT16)PatchValue); - break; - - case 4: - ASSERT (PatchValue <= MAX_UINT32); - WriteUnaligned32 ((UINT32 *)(UINTN)InstructionEnd - 1, (UINT32)PatchValue); - break; - - case 8: - WriteUnaligned64 ((UINT64 *)(UINTN)InstructionEnd - 1, PatchValue); - break; - - default: - ASSERT (FALSE); - } -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c deleted file mode 100644 index 5f5fa85e413..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86RdRand.c +++ /dev/null @@ -1,121 +0,0 @@ -/** @file - IA-32/x64 AsmRdRandxx() - Generates random number through CPU RdRand instruction. - - Copyright (c) 2016, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -/** - Generates a 16-bit random number through RDRAND instruction. - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - - **/ -BOOLEAN -EFIAPI -InternalX86RdRand16 ( - OUT UINT16 *Rand - ); - -/** - Generates a 32-bit random number through RDRAND instruction. - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -InternalX86RdRand32 ( - OUT UINT32 *Rand - ); - -/** - Generates a 64-bit random number through RDRAND instruction. - - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -InternalX86RdRand64 ( - OUT UINT64 *Rand - ); - -/** - Generates a 16-bit random number through RDRAND instruction. - - if Rand is NULL, then ASSERT(). - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - - **/ -BOOLEAN -EFIAPI -AsmRdRand16 ( - OUT UINT16 *Rand - ) -{ - ASSERT (Rand != NULL); - return InternalX86RdRand16 (Rand); -} - -/** - Generates a 32-bit random number through RDRAND instruction. - - if Rand is NULL, then ASSERT(). - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -AsmRdRand32 ( - OUT UINT32 *Rand - ) -{ - ASSERT (Rand != NULL); - return InternalX86RdRand32 (Rand); -} - -/** - Generates a 64-bit random number through RDRAND instruction. - - if Rand is NULL, then ASSERT(). - - @param[out] Rand Buffer pointer to store the random result. - - @retval TRUE RDRAND call was successful. - @retval FALSE Failed attempts to call RDRAND. - -**/ -BOOLEAN -EFIAPI -AsmRdRand64 ( - OUT UINT64 *Rand - ) -{ - ASSERT (Rand != NULL); - return InternalX86RdRand64 (Rand); -} diff --git a/MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c b/MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c deleted file mode 100644 index b3690956373..00000000000 --- a/MdePkg/Test/HostLibrary/BaseLibHost/X86SegmentNull.c +++ /dev/null @@ -1,163 +0,0 @@ -/** @file - IA-32/x64 AsmReadGdtr() - - Copyright (c) 2006 - 2008, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include - -/** - Reads the current value of Code Segment Register (CS). - - Reads and returns the current value of CS. This function is only available on - IA-32 and x64. - - @return The current value of CS. - -**/ -UINT16 -EFIAPI -AsmReadCs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of Data Segment Register (DS). - - Reads and returns the current value of DS. This function is only available on - IA-32 and x64. - - @return The current value of DS. - -**/ -UINT16 -EFIAPI -AsmReadDs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of Extra Segment Register (ES). - - Reads and returns the current value of ES. This function is only available on - IA-32 and x64. - - @return The current value of ES. - -**/ -UINT16 -EFIAPI -AsmReadEs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of FS Data Segment Register (FS). - - Reads and returns the current value of FS. This function is only available on - IA-32 and x64. - - @return The current value of FS. - -**/ -UINT16 -EFIAPI -AsmReadFs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of GS Data Segment Register (GS). - - Reads and returns the current value of GS. This function is only available on - IA-32 and x64. - - @return The current value of GS. - -**/ -UINT16 -EFIAPI -AsmReadGs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of Stack Segment Register (SS). - - Reads and returns the current value of SS. This function is only available on - IA-32 and x64. - - @return The current value of SS. - -**/ -UINT16 -EFIAPI -AsmReadSs ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - - -/** - Reads the current value of Task Register (TR). - - Reads and returns the current value of TR. This function is only available on - IA-32 and x64. - - @return The current value of TR. - -**/ -UINT16 -EFIAPI -AsmReadTr ( - VOID - ) -{ - ASSERT (FALSE); - return 0; -} - -/** - Load given selector into TR register. - - @param[in] Selector Task segment selector -**/ -VOID -EFIAPI -AsmWriteTr ( - IN UINT16 Selector - ) -{ - ASSERT (FALSE); -} \ No newline at end of file diff --git a/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c b/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c deleted file mode 100644 index 712fe1500ee..00000000000 --- a/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.c +++ /dev/null @@ -1,160 +0,0 @@ -/** @file - -Copyright (c) 2018, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include - -#include - -VOID * -EFIAPI -SetMem ( - OUT VOID *Buffer, - IN UINTN Length, - IN UINT8 Value - ) -{ - memset (Buffer, Value, Length); - return Buffer; -} - -VOID * -EFIAPI -SetMem16 ( - OUT VOID *Buffer, - IN UINTN Length, - IN UINT16 Value - ) -{ - for (; Length != 0; Length--) { - ((UINT16*)Buffer)[Length - 1] = Value; - } - return Buffer; -} - -VOID * -EFIAPI -SetMem32 ( - OUT VOID *Buffer, - IN UINTN Length, - IN UINT32 Value - ) -{ - for (; Length != 0; Length--) { - ((UINT32*)Buffer)[Length - 1] = Value; - } - return Buffer; -} - -VOID * -EFIAPI -SetMem64 ( - OUT VOID *Buffer, - IN UINTN Length, - IN UINT64 Value - ) -{ - for (; Length != 0; Length--) { - ((UINT64*)Buffer)[Length - 1] = Value; - } - return Buffer; -} - -VOID * -EFIAPI -SetMemN ( - OUT VOID *Buffer, - IN UINTN Length, - IN UINTN Value - ) -{ - if (sizeof (UINTN) == sizeof (UINT64)) { - return SetMem64 (Buffer, Length, (UINT64)Value); - } else { - return SetMem32 (Buffer, Length, (UINT32)Value); - } -} - -VOID * -EFIAPI -ZeroMem ( - OUT VOID *Buffer, - IN UINTN Length - ) -{ - memset (Buffer, 0, Length); - return Buffer; -} - -VOID * -EFIAPI -CopyMem ( - OUT VOID *DestinationBuffer, - IN CONST VOID *SourceBuffer, - IN UINTN Length - ) -{ - memmove (DestinationBuffer, SourceBuffer, Length); - return DestinationBuffer; -} - -INTN -EFIAPI -CompareMem ( - IN CONST VOID *DestinationBuffer, - IN CONST VOID *SourceBuffer, - IN UINTN Length - ) -{ - return memcmp (DestinationBuffer, SourceBuffer, Length); -} - -BOOLEAN -EFIAPI -CompareGuid ( - IN CONST GUID *Guid1, - IN CONST GUID *Guid2 - ) -{ - return ((BOOLEAN)(memcmp (Guid1, Guid2, sizeof (GUID)) == 0)); -} - -GUID * -EFIAPI -CopyGuid ( - OUT GUID *DestinationGuid, - IN CONST GUID *SourceGuid - ) -{ - memmove (DestinationGuid, SourceGuid, sizeof(GUID)); - return DestinationGuid; -} - -UINT8 mZeroGuid[sizeof(GUID)] = {0}; - -BOOLEAN -EFIAPI -IsZeroGuid ( - IN CONST GUID *Guid - ) -{ - return ((BOOLEAN)(memcmp (Guid, mZeroGuid, sizeof (GUID)) == 0)); -} - -VOID * -EFIAPI -ScanMem8 ( - IN CONST VOID *Buffer, - IN UINTN Length, - IN UINT8 Value - ) -{ - return memchr (Buffer, Value, Length); -} - diff --git a/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf b/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf deleted file mode 100644 index 35c7234aa55..00000000000 --- a/MdePkg/Test/HostLibrary/BaseMemoryLibHost/BaseMemoryLibHost.inf +++ /dev/null @@ -1,24 +0,0 @@ -## @file -# -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = BaseMemoryLibHost - FILE_GUID = 90B7948B-DFED-46FB-BABE-770A5A464BA5 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = BaseMemoryLib | HOST_APPLICATION - -[Sources] - BaseMemoryLibHost.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseLib - From 76cba4b352ad5c582cfa79814c1e1ee6add76d32 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 2 Jan 2020 17:41:21 -0800 Subject: [PATCH 242/384] UnitTestFrameworkPkg/Library: Add Posix libs Move DebugLib for Posix host evncironments to UnitTestFrameworkPkg Move BaseMemoryLib for Posix host evncironments to UnitTestFrameworkPkg Signed-off-by: Michael D Kinney --- MdePkg/Test/MdePkgTest.dsc | 10 ++-------- .../Library/Posix/DebugLibPosix/DebugLibPosix.c | 0 .../Library/Posix/DebugLibPosix/DebugLibPosix.inf | 4 ++-- .../MemoryAllocationLibPosix.c | 0 .../MemoryAllocationLibPosix.inf | 4 ++-- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 2 ++ 6 files changed, 8 insertions(+), 12 deletions(-) rename MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.c => UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c (100%) rename MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf => UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf (86%) rename MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c => UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c (100%) rename MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf => UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf (81%) diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 34b24bf5ca0..27c9cf7647f 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -31,16 +31,10 @@ UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf UnitTestLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf - DebugLib|MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf - MemoryAllocationLib|MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf + DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf [Components] - # - # Build HostLibrary componments - # - MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf - MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf - # # Build HOST_APPLICATION that tests the SafeIntLib # diff --git a/MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.c b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c similarity index 100% rename from MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.c rename to UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c diff --git a/MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf similarity index 86% rename from MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf rename to UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf index 78f062ff5ff..c1ff5773c12 100644 --- a/MdePkg/Test/HostLibrary/DebugLibHost/DebugLibHost.inf +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf @@ -7,14 +7,14 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = DebugLibHost + BASE_NAME = DebugLibPosix FILE_GUID = 6A77CE89-C1B6-4A6B-9561-07D7127514A7 MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 LIBRARY_CLASS = DebugLib | HOST_APPLICATION [Sources] - DebugLibHost.c + DebugLibPosix.c [Packages] MdePkg/MdePkg.dec diff --git a/MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c similarity index 100% rename from MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.c rename to UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c diff --git a/MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf similarity index 81% rename from MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf rename to UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf index 37d4c00cff7..8d1e08994e4 100644 --- a/MdePkg/Test/HostLibrary/MemoryAllocationLibHost/MemoryAllocationLibHost.inf +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf @@ -7,14 +7,14 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = MemoryAllocationLibHost + BASE_NAME = MemoryAllocationLibPosix FILE_GUID = A1672454-A3D3-4AAC-A86B-8D63132BBB91 MODULE_TYPE = HOST_APPLICATION VERSION_STRING = 1.0 LIBRARY_CLASS = MemoryAllocationLib | HOST_APPLICATION [Sources] - MemoryAllocationLibHost.c + MemoryAllocationLibPosix.c [Packages] MdePkg/MdePkg.dec diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 3ed3ce5ec83..3c355b4f3b3 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -170,6 +170,8 @@ UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf [Components] + UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf From 218299f904511a79ec9932018631458472de7e32 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 10:53:18 -0800 Subject: [PATCH 243/384] UnitTestFrameworkPkg: Rename FrameworkInclude to PrivateInclude Rename private include directory to match other packages. Signed-off-by: Michael D Kinney --- .../Library/UnitTestBootLib.h | 0 .../Library/UnitTestPersistenceLib.h | 0 .../Library/UnitTestResultReportLib.h | 0 .../UnitTestFrameworkTypes.h | 0 UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 27 ++++++------------- 5 files changed, 8 insertions(+), 19 deletions(-) rename UnitTestFrameworkPkg/{FrameworkInclude => PrivateInclude}/Library/UnitTestBootLib.h (100%) rename UnitTestFrameworkPkg/{FrameworkInclude => PrivateInclude}/Library/UnitTestPersistenceLib.h (100%) rename UnitTestFrameworkPkg/{FrameworkInclude => PrivateInclude}/Library/UnitTestResultReportLib.h (100%) rename UnitTestFrameworkPkg/{FrameworkInclude => PrivateInclude}/UnitTestFrameworkTypes.h (100%) diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestBootLib.h rename to UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestPersistenceLib.h rename to UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h diff --git a/UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkInclude/Library/UnitTestResultReportLib.h rename to UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h diff --git a/UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h similarity index 100% rename from UnitTestFrameworkPkg/FrameworkInclude/UnitTestFrameworkTypes.h rename to UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index bce20c977ca..aa81cb076bf 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -1,50 +1,39 @@ -## @file UnitTestPkg.dec +## @file # -# This Package provides all definitions(including functions, MACROs, structures and library classes) -# and libraries instances, which are used to support Unit Testing and Interface testing +# This Package provides all definitions(including functions, MACROs, structures +# and library classes) and libraries instances, which are used to support Unit +# Testing and Interface testing # # Copyright (c) 2017, Microsoft Corporation. All rights reserved. # -# ## - [Defines] DEC_SPECIFICATION = 0x00010005 PACKAGE_NAME = UnitTestPkg PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 PACKAGE_VERSION = 1.00 - [Includes.Common.Private] - FrameworkInclude + PrivateInclude Library/HostCMocka/CmockaLib/cmocka/include Library/HostCMocka/CmockaLib/cmocka/include/cmockery [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state # - UnitTestPersistenceLib|FrameworkInclude/Library/UnitTestPersistenceLib.h + UnitTestPersistenceLib|PrivateInclude/Library/UnitTestPersistenceLib.h ## @libraryclass Provides a unit test result report # - UnitTestResultReportLib|FrameworkInclude/Library/UnitTestResultReportLib.h + UnitTestResultReportLib|PrivateInclude/Library/UnitTestResultReportLib.h ## @libraryclass Provides boot-option routines useful in shell-based tests. # - UnitTestBootLib|FrameworkInclude/Library/UnitTestBootLib.h + UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h [Guids] gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } -[Ppis] - -[Protocols] - -[PcdsFeatureFlag] - -[PcdsDynamic, PcdsDynamicEx] - [PcdsFixedAtBuild] gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 - \ No newline at end of file From eecfd410c64a5090d3782c106b2b5c49acec1b5c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 11:05:07 -0800 Subject: [PATCH 244/384] UnitTestFrameworkPkg/Library: Rename UEFI to Uefi Rename UnitTestFrameworkPkg/Library/UEFI to UnitTestFrameworkPkg/Library/Uefi to follow EFK II C Coding Style. Signed-off-by: Michael D Kinney --- .../UnitTestAssertLib/UnitTestAssertLib.c | 0 .../UnitTestAssertLib/UnitTestAssertLib.inf | 0 .../UnitTestBootLibNull/UnitTestBootLibNull.c | 0 .../UnitTestBootLibNull.inf | 0 .../{UEFI => Uefi}/UnitTestLib/UnitTestLib.c | 0 .../UnitTestLib/UnitTestLibDxe.inf | 0 .../UnitTestLib/UnitTestLibPei.inf | 0 .../UnitTestLib/UnitTestLibSmm.inf | 0 .../UnitTestLogLib/UnitTestLogLib.c | 0 .../UnitTestLogLib/UnitTestLogLib.inf | 0 .../UnitTestPersistenceLibNull.c | 0 .../UnitTestPersistenceLibNull.inf | 0 .../UnitTestResultReportLibDebug.c | 0 .../UnitTestResultReportLibDebug.inf | 0 UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 32 +++++++++---------- 15 files changed, 16 insertions(+), 16 deletions(-) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestAssertLib/UnitTestAssertLib.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestAssertLib/UnitTestAssertLib.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestBootLibNull/UnitTestBootLibNull.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestBootLibNull/UnitTestBootLibNull.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLib/UnitTestLib.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLib/UnitTestLibDxe.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLib/UnitTestLibPei.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLib/UnitTestLibSmm.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLogLib/UnitTestLogLib.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestLogLib/UnitTestLogLib.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c (100%) rename UnitTestFrameworkPkg/Library/{UEFI => Uefi}/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf (100%) diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf similarity index 100% rename from UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf rename to UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 3c355b4f3b3..aac69acaff2 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -153,33 +153,33 @@ # UnitTestFrameworkPkg # [LibraryClasses] - UnitTestAssertLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestLogLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestLogLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf [LibraryClasses.common.PEIM] - UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_SMM_DRIVER] - UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf [LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - UnitTestLib|UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf [Components] UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibDxe.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibPei.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestLib/UnitTestLibSmm.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestLogLib/UnitTestLogLib.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestFrameworkPkg/Library/UEFI/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf From bd77e86d93ebe2b08d32c1d0a42a9e6d7478ca18 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 11:16:46 -0800 Subject: [PATCH 245/384] UnitTestFrameworkPkg: Make case of 'Cmocka' consistent Signed-off-by: Michael D Kinney --- .gitmodules | 4 ++-- MdePkg/Test/MdePkgTest.dsc | 6 +++--- .../{HostCMocka => HostCmocka}/CmockaLib/CmockaLib.inf | 1 - .../{HostCMocka => HostCmocka}/CmockaLib/CmockaLib.uni | 0 .../Library/{HostCMocka => HostCmocka}/CmockaLib/cmocka | 0 .../UnitTestAssertLibCmocka}/UnitTestAssertLib.c | 0 .../UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf} | 2 +- .../UnitTestLibCmocka}/UnitTestLib.c | 0 .../UnitTestLibCmocka/UnitTestLibCmocka.inf} | 2 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml | 6 +++--- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 4 ++-- 11 files changed, 12 insertions(+), 13 deletions(-) rename UnitTestFrameworkPkg/Library/{HostCMocka => HostCmocka}/CmockaLib/CmockaLib.inf (98%) rename UnitTestFrameworkPkg/Library/{HostCMocka => HostCmocka}/CmockaLib/CmockaLib.uni (100%) rename UnitTestFrameworkPkg/Library/{HostCMocka => HostCmocka}/CmockaLib/cmocka (100%) rename UnitTestFrameworkPkg/Library/{HostCMocka/UnitTestAssertLibcmocka => HostCmocka/UnitTestAssertLibCmocka}/UnitTestAssertLib.c (100%) rename UnitTestFrameworkPkg/Library/{HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf => HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf} (91%) rename UnitTestFrameworkPkg/Library/{HostCMocka/UnitTestLibcmocka => HostCmocka/UnitTestLibCmocka}/UnitTestLib.c (100%) rename UnitTestFrameworkPkg/Library/{HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf => HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf} (92%) diff --git a/.gitmodules b/.gitmodules index 8226463f64b..bb34fb2b76c 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,6 +4,6 @@ [submodule "SoftFloat"] path = ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 url = https://github.com/ucb-bar/berkeley-softfloat-3.git -[submodule "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka"] - path = UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka +[submodule "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka"] + path = UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka url = https://git.cryptomilk.org/projects/cmocka.git diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 27c9cf7647f..2a435c6189f 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -27,9 +27,9 @@ SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf [LibraryClasses.common.HOST_APPLICATION] - CmockaLib|UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf - UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf - UnitTestLib|UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf + CmockaLib|UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf + UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf + UnitTestLib|UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf similarity index 98% rename from UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf rename to UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf index 20eaa2b9eca..a91d296fbb3 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf @@ -14,7 +14,6 @@ MODULE_TYPE = BASE VERSION_STRING = 0.1 LIBRARY_CLASS = CmockaLib - DEFINE CMOCKA_PATH = cmocka # # VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni similarity index 100% rename from UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.uni rename to UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka similarity index 100% rename from UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka rename to UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLib.c rename to UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf similarity index 91% rename from UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf rename to UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf index 79ed139d006..b6cf53c6079 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf @@ -7,7 +7,7 @@ [Defines] INF_VERSION = 0x00010017 - BASE_NAME = UnitTestAssertLibcmocka + BASE_NAME = UnitTestAssertLibCmocka FILE_GUID = 8841561C-ABF2-4989-9039-4C6485D61C23 VERSION_STRING = 1.0 MODULE_TYPE = BASE diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c similarity index 100% rename from UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLib.c rename to UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf similarity index 92% rename from UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf rename to UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf index 9b76efebaa9..f19201d943d 100644 --- a/UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf @@ -7,7 +7,7 @@ [Defines] INF_VERSION = 0x00010017 - BASE_NAME = UnitTestLibcmocka + BASE_NAME = UnitTestLibCmocka FILE_GUID = C800595F-45A3-45A1-8B50-28F01C2A5A4F VERSION_STRING = 1.0 MODULE_TYPE = BASE diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 610b4451d12..7cc680ba6c3 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,9 +30,9 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestLibcmocka/UnitTestLibcmocka.inf", - "UnitTestFrameworkPkg/Library/HostCMocka/UnitTestAssertLibcmocka/UnitTestAssertLibcmocka.inf", - "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/CmockaLib.inf" + "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf", + "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf", + "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf" ] }, "GuidCheck": { diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index aa81cb076bf..cc56b9f5f96 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -16,8 +16,8 @@ [Includes.Common.Private] PrivateInclude - Library/HostCMocka/CmockaLib/cmocka/include - Library/HostCMocka/CmockaLib/cmocka/include/cmockery + Library/HostCmocka/CmockaLib/cmocka/include + Library/HostCmocka/CmockaLib/cmocka/include/cmockery [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state From a41433248034335ffa88024b9f7f341606c51529 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 11:46:33 -0800 Subject: [PATCH 246/384] UnitTestFrameworkPkg: Fix trailing whitespace and line endings Signed-off-by: Michael D Kinney --- .../HostCmocka/CmockaLib/CmockaLib.inf | 64 +- .../HostCmocka/CmockaLib/CmockaLib.uni | 32 +- .../UnitTestAssertLib.c | 382 ++-- .../UnitTestAssertLibCmocka.inf | 50 +- .../UnitTestLibCmocka/UnitTestLib.c | 994 +++++----- .../UnitTestLibCmocka/UnitTestLibCmocka.inf | 52 +- .../MemoryAllocationLibPosix.c | 2 +- .../UnitTestAssertLib/UnitTestAssertLib.c | 470 ++--- .../UnitTestAssertLib/UnitTestAssertLib.inf | 76 +- .../UnitTestBootLibNull/UnitTestBootLibNull.c | 36 +- .../UnitTestBootLibNull.inf | 56 +- .../Library/Uefi/UnitTestLib/UnitTestLib.c | 1716 ++++++++--------- .../Uefi/UnitTestLib/UnitTestLibDxe.inf | 86 +- .../Uefi/UnitTestLib/UnitTestLibPei.inf | 82 +- .../Uefi/UnitTestLib/UnitTestLibSmm.inf | 84 +- .../Uefi/UnitTestLogLib/UnitTestLogLib.c | 432 ++--- .../Uefi/UnitTestLogLib/UnitTestLogLib.inf | 84 +- .../UnitTestPersistenceLibNull.c | 188 +- .../UnitTestPersistenceLibNull.inf | 88 +- .../UnitTestResultReportLibDebug.c | 420 ++-- .../UnitTestResultReportLibDebug.inf | 68 +- .../UnitTestBootLibUsbClass.c | 224 +-- .../UnitTestBootLibUsbClass.inf | 84 +- .../UnitTestPersistenceLibFileSystem.c | 832 ++++---- .../UnitTestPersistenceLibFileSystem.inf | 128 +- .../UnitTestResultReportLibPlainTextOutput.c | 454 ++--- ...UnitTestResultReportLibPlainTextOutput.inf | 74 +- .../PrivateInclude/Library/UnitTestBootLib.h | 50 +- .../Library/UnitTestPersistenceLib.h | 154 +- .../Library/UnitTestResultReportLib.h | 50 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 292 +-- UnitTestFrameworkPkg/ReadMe.md | 474 ++--- .../SampleUnitTestApp/SampleUnitTestApp.c | 420 ++-- .../SampleUnitTestApp/SampleUnitTestApp.inf | 82 +- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 422 ++-- .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 82 +- .../SampleUnitTestSmm/SampleUnitTestSmm.c | 418 ++-- .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 84 +- .../UnitTestFrameworkPkg.ci.yaml | 112 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 78 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 382 ++-- 41 files changed, 5179 insertions(+), 5179 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf index a91d296fbb3..3ef9bd9aa79 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf @@ -1,32 +1,32 @@ -## @file -# This module provides Cmocka Library implementation. -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = CmockaLib - MODULE_UNI_FILE = CmockaLib.uni - FILE_GUID = F1662152-3399-49AC-BE44-CAA97575FACE - MODULE_TYPE = BASE - VERSION_STRING = 0.1 - LIBRARY_CLASS = CmockaLib - -# -# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 -# - -[Sources] - cmocka/src/cmocka.c - -[Packages] - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[BuildOptions] - MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF - - GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H - GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H +## @file +# This module provides Cmocka Library implementation. +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = CmockaLib + MODULE_UNI_FILE = CmockaLib.uni + FILE_GUID = F1662152-3399-49AC-BE44-CAA97575FACE + MODULE_TYPE = BASE + VERSION_STRING = 0.1 + LIBRARY_CLASS = CmockaLib + +# +# VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 +# + +[Sources] + cmocka/src/cmocka.c + +[Packages] + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + + GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H + GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni index 5e24d33725e..5a114b93455 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni +++ b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni @@ -1,16 +1,16 @@ -// /** @file -// This module provides Cmocka Library implementation. -// -// This module provides Cmocka Library implementation. -// -// Copyright (c) 2019, Intel Corporation. All rights reserved.
-// -// SPDX-License-Identifier: BSD-2-Clause-Patent -// -// **/ - - -#string STR_MODULE_ABSTRACT #language en-US "Cmocka Library implementation" - -#string STR_MODULE_DESCRIPTION #language en-US "This module provides Cmocka Library implementation." - +// /** @file +// This module provides Cmocka Library implementation. +// +// This module provides Cmocka Library implementation. +// +// Copyright (c) 2019, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + + +#string STR_MODULE_ABSTRACT #language en-US "Cmocka Library implementation" + +#string STR_MODULE_DESCRIPTION #language en-US "This module provides Cmocka Library implementation." + diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c index d56fdee15f7..43190ff6aff 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c @@ -1,191 +1,191 @@ -/** @file - - Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#define MAX_STRING_SIZE 1025 - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); - _assert_true (Expression, Description, FileName, (INT32)LineNumber); - - return Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); - _assert_true (!Expression, Description, FileName, (INT32)LineNumber); - - return !Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); - _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); - - return !EFI_ERROR (Status); -} - - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); - - return (ValueA == ValueB); -} - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - BOOLEAN Result; - - Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); - _assert_true (Result, TempStr, FileName, (INT32)LineNumber); - - return Result; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); - - return (ValueA != ValueB); -} - - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); - _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); - - return (Status == Expected); -} - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); - _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); - - return (Pointer != NULL); -} +/** @file + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include + +#include +#include + +#define MAX_STRING_SIZE 1025 + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); + _assert_true (Expression, Description, FileName, (INT32)LineNumber); + + return Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); + _assert_true (!Expression, Description, FileName, (INT32)LineNumber); + + return !Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); + _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); + + return !EFI_ERROR (Status); +} + + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + BOOLEAN Result; + + Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); + _assert_true (Result, TempStr, FileName, (INT32)LineNumber); + + return Result; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA != ValueB); +} + + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); + _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); + + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); + _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); + + return (Pointer != NULL); +} diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf index b6cf53c6079..853c703b209 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf @@ -1,25 +1,25 @@ -## @file -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestAssertLibCmocka - FILE_GUID = 8841561C-ABF2-4989-9039-4C6485D61C23 - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestAssertLib - -[LibraryClasses] - BaseMemoryLib - CmockaLib - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[Sources] - UnitTestAssertLib.c +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestAssertLibCmocka + FILE_GUID = 8841561C-ABF2-4989-9039-4C6485D61C23 + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestAssertLib + +[LibraryClasses] + BaseMemoryLib + CmockaLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[Sources] + UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c index 80d3f87d072..29b0d06f47a 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c @@ -1,497 +1,497 @@ -/** @file - - Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#define MAX_STRING_SIZE 1025 - -int GroupSetupTemplate (void **state); -int GroupTeardownTemplate (void **state); -void TestFuncTemplate (void **state); -int SetupFuncTemplate (void **state); -int TeardownFuncTemplate (void **state); - -extern UINTN mGroupSetupTemplateSize; -extern UINTN mGroupTeardownTemplateSize; -extern UINTN mTestFuncTemplateSize; -extern UINTN mSetupFuncTemplateSize; -extern UINTN mTeardownFuncTemplateSize; - -// NOTE: Changing structure below requires NASM file update -typedef struct { - CHAR8 *TestName; - CMUnitTestFunction TestFunc; - CMFixtureFunction SetupFunc; - CMFixtureFunction TeardownFunc; - CHAR8 *Description; - CHAR8 *ClassName; //can't have spaces and should be short - UNIT_TEST_FUNCTION RunTest; - UNIT_TEST_PREREQ PreReq; - UNIT_TEST_CLEANUP CleanUp; - UNIT_TEST_CONTEXT Context; - UNIT_TEST_SUITE_HANDLE ParentSuite; - UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; -} MY_UNIT_TEST; - -typedef struct { - LIST_ENTRY Entry; - MY_UNIT_TEST UT; -} MY_UNIT_TEST_LIST_ENTRY; - -// NOTE: Changing structure below requires NASM file update -typedef struct { - UINTN NumTests; - CMFixtureFunction GroupSetup; - CMFixtureFunction GroupTeardown; - CHAR8 *Title; - CHAR8 *Package; - UNIT_TEST_SUITE_SETUP Setup; - UNIT_TEST_SUITE_TEARDOWN Teardown; - LIST_ENTRY TestCaseList; // MY_UNIT_TEST_LIST_ENTRY - UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; -} MY_UNIT_TEST_SUITE; - -typedef struct { - LIST_ENTRY Entry; - MY_UNIT_TEST_SUITE UTS; -} MY_UNIT_TEST_SUITE_LIST_ENTRY; - -typedef struct { - CHAR8 *Title; - CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. - CHAR8 *VersionString; - LIST_ENTRY TestSuiteList; // MY_UNIT_TEST_SUITE_LIST_ENTRY -} MY_UNIT_TEST_FRAMEWORK; - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - -/** - This function will determine whether the short name violates any rules that would - prevent it from being used as a reporting name or as a serialization name. - - Example: If the name cannot be serialized to a filesystem file name. - - @param[in] ShortTitleString A pointer to the short title string to be evaluated. - - @retval TRUE The string is acceptable. - @retval FALSE The string should not be used. - -**/ -STATIC -BOOLEAN -IsFrameworkShortNameValid ( - IN CHAR8 *ShortTitleString - ) -{ - // TODO: Finish this function. - return TRUE; -} // IsFrameworkShortNameValid() - -STATIC -CHAR8* -AllocateAndCopyString ( - IN CHAR8 *StringToCopy - ) -{ - CHAR8 *NewString = NULL; - UINTN NewStringLength; - - NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; - NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); - if (NewString != NULL) - { - AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); - } - - return NewString; -} // AllocateAndCopyString () - - -EFI_STATUS -EFIAPI -FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestFramework() - - -STATIC -EFI_STATUS -FreeUnitTestSuiteEntry ( - IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestSuiteEntry() - - -STATIC -EFI_STATUS -FreeUnitTestTestEntry ( - IN UNIT_TEST_LIST_ENTRY *TestEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestTestEntry() - - - -//============================================================================= -// -// ---------------- TEST SETUP FUNCTIONS ------------------------------------- -// -//============================================================================= - - -/* -Method to Initialize the Unit Test framework - -@retval Success - Unit Test init. -@retval EFI_ERROR - Unit Tests init failed. -*/ -EFI_STATUS -EFIAPI -InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_FRAMEWORK *NewFramework; - - Status = EFI_SUCCESS; - NewFramework = NULL; - - // - // First, check all pointers and make sure nothing's broked. - if (Framework == NULL || Title == NULL || - ShortTitle == NULL || VersionString == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, determine whether all of the strings are good to use. - if (!IsFrameworkShortNameValid( ShortTitle )) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, set aside some space to start messing with the framework. - NewFramework = AllocateZeroPool( sizeof( MY_UNIT_TEST_FRAMEWORK ) ); - if (NewFramework == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Next, set up all the test data. - NewFramework->Title = AllocateAndCopyString( Title ); - NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); - NewFramework->VersionString = AllocateAndCopyString( VersionString ); - if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || - NewFramework->VersionString == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - InitializeListHead( &(NewFramework->TestSuiteList) ); - -Exit: - // - // If we're good, then let's copy the framework. - if (!EFI_ERROR( Status )) - { - *Framework = (UNIT_TEST_FRAMEWORK *)NewFramework; - } - // Otherwise, we need to undo this horrible thing that we've done. - else - { - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); - } - - return Status; -} - -EFI_STATUS -EFIAPI -CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; - MY_UNIT_TEST_FRAMEWORK *MyFramework; - - Status = EFI_SUCCESS; - MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; - - // - // First, let's check to make sure that our parameters look good. - if ((MyFramework == NULL) || (Title == NULL) || (Package == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewSuiteEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_SUITE_LIST_ENTRY ) ); - if (NewSuiteEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewSuiteEntry->UTS.NumTests = 0; - NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); - NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); - NewSuiteEntry->UTS.Setup = Sup; - NewSuiteEntry->UTS.Teardown = Tdn; - NewSuiteEntry->UTS.ParentFramework = MyFramework; - InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. - InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. - if (NewSuiteEntry->UTS.Title == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - if (NewSuiteEntry->UTS.Package == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)Sup; - NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)Tdn; - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(MyFramework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); - *Suite = (UNIT_TEST_SUITE *)&NewSuiteEntry->UTS; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestSuiteEntry( (UNIT_TEST_SUITE_LIST_ENTRY *)NewSuiteEntry ); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_SUITE *MySuite; - MY_UNIT_TEST_LIST_ENTRY *NewTestEntry; - UINTN TestNameSize; - - Status = EFI_SUCCESS; - MySuite = (MY_UNIT_TEST_SUITE *)Suite; - - // - // First, let's check to make sure that our parameters look good. - if ((MySuite == NULL) || (Description == NULL) || (ClassName == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewTestEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_LIST_ENTRY ) ); - if (NewTestEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewTestEntry->UT.Description = AllocateAndCopyString( Description ); - NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); - NewTestEntry->UT.PreReq = PreReq; - NewTestEntry->UT.CleanUp = CleanUp; - NewTestEntry->UT.RunTest = Func; - NewTestEntry->UT.Context = Context; - NewTestEntry->UT.ParentSuite = MySuite; - NewTestEntry->UT.ParentFramework = MySuite->ParentFramework; - InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. - if (NewTestEntry->UT.Description == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - NewTestEntry->UT.TestFunc = (CMUnitTestFunction)Func; - NewTestEntry->UT.SetupFunc = (CMFixtureFunction)PreReq; - NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)CleanUp; - - TestNameSize = AsciiStrLen (Description) + 1; - NewTestEntry->UT.TestName = AllocatePool (TestNameSize); - ASSERT (NewTestEntry->UT.TestName != NULL); - - Status = AsciiStrCpyS (NewTestEntry->UT.TestName, TestNameSize, Description); - ASSERT_EFI_ERROR(Status); - - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(MySuite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); - MySuite->NumTests ++; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestTestEntry( (UNIT_TEST_LIST_ENTRY *)NewTestEntry ); - } - - return Status; -} - - -//============================================================================= -// -// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- -// -//============================================================================= - -EFI_STATUS -EFIAPI -RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_FRAMEWORK *MyFramework; - LIST_ENTRY *TestSuiteList; - LIST_ENTRY *TestSuiteLink; - MY_UNIT_TEST_SUITE_LIST_ENTRY *TestSuiteListEntry; - MY_UNIT_TEST_SUITE *TestSuite; - CHAR8 GroupName[MAX_STRING_SIZE]; - struct CMUnitTest *Tests; - LIST_ENTRY *UnitTestList; - LIST_ENTRY *UnitTestLink; - MY_UNIT_TEST_LIST_ENTRY *UnitTestListEntry; - MY_UNIT_TEST *UnitTest; - UINTN Index; - - // MU_CHANGE - We control this from our build system. - // May need to revisit. - // if (PcdGet8 (HostUnitTestMode) == 1) { - // cmocka_set_message_output (CM_OUTPUT_XML); - // } - - MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; - - TestSuiteList = &MyFramework->TestSuiteList; - for (TestSuiteLink = TestSuiteList->ForwardLink; - TestSuiteLink != TestSuiteList; - TestSuiteLink = TestSuiteLink->ForwardLink) { - TestSuiteListEntry = BASE_CR ( - TestSuiteLink, - MY_UNIT_TEST_SUITE_LIST_ENTRY, - Entry - ); - TestSuite = &TestSuiteListEntry->UTS; - Status = AsciiStrCpyS (GroupName, sizeof(GroupName), TestSuite->Title); - ASSERT_EFI_ERROR(Status); - - Tests = AllocateZeroPool (TestSuite->NumTests * sizeof(struct CMUnitTest)); - ASSERT (Tests != NULL); - Index = 0; - - UnitTestList = &TestSuite->TestCaseList; - for (UnitTestLink = UnitTestList->ForwardLink; - UnitTestLink != UnitTestList; - UnitTestLink = UnitTestLink->ForwardLink) { - UnitTestListEntry = BASE_CR ( - UnitTestLink, - MY_UNIT_TEST_LIST_ENTRY, - Entry - ); - UnitTest = &UnitTestListEntry->UT; - - Tests[Index].name = UnitTest->TestName; - Tests[Index].test_func = UnitTest->TestFunc; - Tests[Index].setup_func = UnitTest->SetupFunc; - Tests[Index].teardown_func = UnitTest->TeardownFunc; - Tests[Index].initial_state = NULL; - Index++; - } - ASSERT (Index == TestSuite->NumTests); - - _cmocka_run_group_tests (GroupName, Tests, TestSuite->NumTests, TestSuite->GroupSetup, TestSuite->GroupTeardown); - FreePool (Tests); - } - - return EFI_SUCCESS; -} - -//============================================================================= -// -// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- -// -//============================================================================= - -EFI_STATUS -EFIAPI -SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - return EFI_UNSUPPORTED; -} // SaveFrameworkState() +/** @file + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#define MAX_STRING_SIZE 1025 + +int GroupSetupTemplate (void **state); +int GroupTeardownTemplate (void **state); +void TestFuncTemplate (void **state); +int SetupFuncTemplate (void **state); +int TeardownFuncTemplate (void **state); + +extern UINTN mGroupSetupTemplateSize; +extern UINTN mGroupTeardownTemplateSize; +extern UINTN mTestFuncTemplateSize; +extern UINTN mSetupFuncTemplateSize; +extern UINTN mTeardownFuncTemplateSize; + +// NOTE: Changing structure below requires NASM file update +typedef struct { + CHAR8 *TestName; + CMUnitTestFunction TestFunc; + CMFixtureFunction SetupFunc; + CMFixtureFunction TeardownFunc; + CHAR8 *Description; + CHAR8 *ClassName; //can't have spaces and should be short + UNIT_TEST_FUNCTION RunTest; + UNIT_TEST_PREREQ PreReq; + UNIT_TEST_CLEANUP CleanUp; + UNIT_TEST_CONTEXT Context; + UNIT_TEST_SUITE_HANDLE ParentSuite; + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} MY_UNIT_TEST; + +typedef struct { + LIST_ENTRY Entry; + MY_UNIT_TEST UT; +} MY_UNIT_TEST_LIST_ENTRY; + +// NOTE: Changing structure below requires NASM file update +typedef struct { + UINTN NumTests; + CMFixtureFunction GroupSetup; + CMFixtureFunction GroupTeardown; + CHAR8 *Title; + CHAR8 *Package; + UNIT_TEST_SUITE_SETUP Setup; + UNIT_TEST_SUITE_TEARDOWN Teardown; + LIST_ENTRY TestCaseList; // MY_UNIT_TEST_LIST_ENTRY + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} MY_UNIT_TEST_SUITE; + +typedef struct { + LIST_ENTRY Entry; + MY_UNIT_TEST_SUITE UTS; +} MY_UNIT_TEST_SUITE_LIST_ENTRY; + +typedef struct { + CHAR8 *Title; + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR8 *VersionString; + LIST_ENTRY TestSuiteList; // MY_UNIT_TEST_SUITE_LIST_ENTRY +} MY_UNIT_TEST_FRAMEWORK; + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + +/** + This function will determine whether the short name violates any rules that would + prevent it from being used as a reporting name or as a serialization name. + + Example: If the name cannot be serialized to a filesystem file name. + + @param[in] ShortTitleString A pointer to the short title string to be evaluated. + + @retval TRUE The string is acceptable. + @retval FALSE The string should not be used. + +**/ +STATIC +BOOLEAN +IsFrameworkShortNameValid ( + IN CHAR8 *ShortTitleString + ) +{ + // TODO: Finish this function. + return TRUE; +} // IsFrameworkShortNameValid() + +STATIC +CHAR8* +AllocateAndCopyString ( + IN CHAR8 *StringToCopy + ) +{ + CHAR8 *NewString = NULL; + UINTN NewStringLength; + + NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; + NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); + if (NewString != NULL) + { + AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); + } + + return NewString; +} // AllocateAndCopyString () + + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestFramework() + + +STATIC +EFI_STATUS +FreeUnitTestSuiteEntry ( + IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestSuiteEntry() + + +STATIC +EFI_STATUS +FreeUnitTestTestEntry ( + IN UNIT_TEST_LIST_ENTRY *TestEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestTestEntry() + + + +//============================================================================= +// +// ---------------- TEST SETUP FUNCTIONS ------------------------------------- +// +//============================================================================= + + +/* +Method to Initialize the Unit Test framework + +@retval Success - Unit Test init. +@retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_FRAMEWORK *NewFramework; + + Status = EFI_SUCCESS; + NewFramework = NULL; + + // + // First, check all pointers and make sure nothing's broked. + if (Framework == NULL || Title == NULL || + ShortTitle == NULL || VersionString == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, determine whether all of the strings are good to use. + if (!IsFrameworkShortNameValid( ShortTitle )) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, set aside some space to start messing with the framework. + NewFramework = AllocateZeroPool( sizeof( MY_UNIT_TEST_FRAMEWORK ) ); + if (NewFramework == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Next, set up all the test data. + NewFramework->Title = AllocateAndCopyString( Title ); + NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); + NewFramework->VersionString = AllocateAndCopyString( VersionString ); + if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || + NewFramework->VersionString == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + InitializeListHead( &(NewFramework->TestSuiteList) ); + +Exit: + // + // If we're good, then let's copy the framework. + if (!EFI_ERROR( Status )) + { + *Framework = (UNIT_TEST_FRAMEWORK *)NewFramework; + } + // Otherwise, we need to undo this horrible thing that we've done. + else + { + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); + } + + return Status; +} + +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN CHAR8 *Title, + IN CHAR8 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + MY_UNIT_TEST_FRAMEWORK *MyFramework; + + Status = EFI_SUCCESS; + MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; + + // + // First, let's check to make sure that our parameters look good. + if ((MyFramework == NULL) || (Title == NULL) || (Package == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewSuiteEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_SUITE_LIST_ENTRY ) ); + if (NewSuiteEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewSuiteEntry->UTS.NumTests = 0; + NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); + NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); + NewSuiteEntry->UTS.Setup = Sup; + NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.ParentFramework = MyFramework; + InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. + InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. + if (NewSuiteEntry->UTS.Title == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + if (NewSuiteEntry->UTS.Package == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)Sup; + NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)Tdn; + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(MyFramework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); + *Suite = (UNIT_TEST_SUITE *)&NewSuiteEntry->UTS; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestSuiteEntry( (UNIT_TEST_SUITE_LIST_ENTRY *)NewSuiteEntry ); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE_HANDLE Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_SUITE *MySuite; + MY_UNIT_TEST_LIST_ENTRY *NewTestEntry; + UINTN TestNameSize; + + Status = EFI_SUCCESS; + MySuite = (MY_UNIT_TEST_SUITE *)Suite; + + // + // First, let's check to make sure that our parameters look good. + if ((MySuite == NULL) || (Description == NULL) || (ClassName == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewTestEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_LIST_ENTRY ) ); + if (NewTestEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewTestEntry->UT.Description = AllocateAndCopyString( Description ); + NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); + NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.CleanUp = CleanUp; + NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.Context = Context; + NewTestEntry->UT.ParentSuite = MySuite; + NewTestEntry->UT.ParentFramework = MySuite->ParentFramework; + InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. + if (NewTestEntry->UT.Description == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + NewTestEntry->UT.TestFunc = (CMUnitTestFunction)Func; + NewTestEntry->UT.SetupFunc = (CMFixtureFunction)PreReq; + NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)CleanUp; + + TestNameSize = AsciiStrLen (Description) + 1; + NewTestEntry->UT.TestName = AllocatePool (TestNameSize); + ASSERT (NewTestEntry->UT.TestName != NULL); + + Status = AsciiStrCpyS (NewTestEntry->UT.TestName, TestNameSize, Description); + ASSERT_EFI_ERROR(Status); + + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(MySuite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); + MySuite->NumTests ++; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestTestEntry( (UNIT_TEST_LIST_ENTRY *)NewTestEntry ); + } + + return Status; +} + + +//============================================================================= +// +// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- +// +//============================================================================= + +EFI_STATUS +EFIAPI +RunAllTestSuites( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ) +{ + EFI_STATUS Status; + MY_UNIT_TEST_FRAMEWORK *MyFramework; + LIST_ENTRY *TestSuiteList; + LIST_ENTRY *TestSuiteLink; + MY_UNIT_TEST_SUITE_LIST_ENTRY *TestSuiteListEntry; + MY_UNIT_TEST_SUITE *TestSuite; + CHAR8 GroupName[MAX_STRING_SIZE]; + struct CMUnitTest *Tests; + LIST_ENTRY *UnitTestList; + LIST_ENTRY *UnitTestLink; + MY_UNIT_TEST_LIST_ENTRY *UnitTestListEntry; + MY_UNIT_TEST *UnitTest; + UINTN Index; + + // MU_CHANGE - We control this from our build system. + // May need to revisit. + // if (PcdGet8 (HostUnitTestMode) == 1) { + // cmocka_set_message_output (CM_OUTPUT_XML); + // } + + MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; + + TestSuiteList = &MyFramework->TestSuiteList; + for (TestSuiteLink = TestSuiteList->ForwardLink; + TestSuiteLink != TestSuiteList; + TestSuiteLink = TestSuiteLink->ForwardLink) { + TestSuiteListEntry = BASE_CR ( + TestSuiteLink, + MY_UNIT_TEST_SUITE_LIST_ENTRY, + Entry + ); + TestSuite = &TestSuiteListEntry->UTS; + Status = AsciiStrCpyS (GroupName, sizeof(GroupName), TestSuite->Title); + ASSERT_EFI_ERROR(Status); + + Tests = AllocateZeroPool (TestSuite->NumTests * sizeof(struct CMUnitTest)); + ASSERT (Tests != NULL); + Index = 0; + + UnitTestList = &TestSuite->TestCaseList; + for (UnitTestLink = UnitTestList->ForwardLink; + UnitTestLink != UnitTestList; + UnitTestLink = UnitTestLink->ForwardLink) { + UnitTestListEntry = BASE_CR ( + UnitTestLink, + MY_UNIT_TEST_LIST_ENTRY, + Entry + ); + UnitTest = &UnitTestListEntry->UT; + + Tests[Index].name = UnitTest->TestName; + Tests[Index].test_func = UnitTest->TestFunc; + Tests[Index].setup_func = UnitTest->SetupFunc; + Tests[Index].teardown_func = UnitTest->TeardownFunc; + Tests[Index].initial_state = NULL; + Index++; + } + ASSERT (Index == TestSuite->NumTests); + + _cmocka_run_group_tests (GroupName, Tests, TestSuite->NumTests, TestSuite->GroupSetup, TestSuite->GroupTeardown); + FreePool (Tests); + } + + return EFI_SUCCESS; +} + +//============================================================================= +// +// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- +// +//============================================================================= + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + return EFI_UNSUPPORTED; +} // SaveFrameworkState() diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf index f19201d943d..a59f3c107b9 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf @@ -1,26 +1,26 @@ -## @file -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestLibCmocka - FILE_GUID = C800595F-45A3-45A1-8B50-28F01C2A5A4F - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestLib - -[LibraryClasses] - BaseLib - MemoryAllocationLib - CmockaLib - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[Sources] - UnitTestLib.c +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestLibCmocka + FILE_GUID = C800595F-45A3-45A1-8B50-28F01C2A5A4F + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestLib + +[LibraryClasses] + BaseLib + MemoryAllocationLib + CmockaLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[Sources] + UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c index 8a92a888065..9bc8838a438 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c @@ -225,7 +225,7 @@ AllocateCopyPool ( IN CONST VOID *Buffer ) { - VOID *Memory; + VOID *Memory; Memory = malloc (AllocationSize); if (Memory == NULL) { return NULL; diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c index 0473cb6fdcb..1491bb5b2d7 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c @@ -1,235 +1,235 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include - -#include -#include - - -STATIC -EFI_STATUS -AddUnitTestFailure( - IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR8 *FailureMessage, - IN FAILURE_TYPE FailureType - ) -{ - // - // Make sure that you're cooking with gas. - // - if (UnitTest == NULL || FailureMessage == NULL) - { - return EFI_INVALID_PARAMETER; - } - - UnitTest->FailureType = FailureType; - AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); - - return EFI_SUCCESS; -} // AddUnitTestFailure() - - -STATIC -VOID -UnitTestLogFailure( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN FAILURE_TYPE FailureType, - IN CONST CHAR8 *Format, - ... - ) -{ - CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - VA_LIST Marker; - - - // - // Convert the message to an ASCII String - // - VA_START(Marker, Format); - AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); - VA_END(Marker); - - // - // Finally, add the string to the log. - // - AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); - - return; -} // UnitTestLogFailure() - - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (!Expression) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); - } - return Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (Expression) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - } - return !Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (EFI_ERROR( Status )) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); - } - return !EFI_ERROR( Status ); -} - - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if ((ValueA != ValueB)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); - } - return (ValueA == ValueB); -} - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - return FALSE; - } - return TRUE; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if ((ValueA == ValueB)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); - } - return (ValueA != ValueB); -} - - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if ((Status != Expected)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); - } - return (Status == Expected); -} - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ) -{ - if (Pointer == NULL) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - } - return (Pointer != NULL); - -} +/** + +Implement UnitTestLib + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include + +#include +#include + + +STATIC +EFI_STATUS +AddUnitTestFailure( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR8 *FailureMessage, + IN FAILURE_TYPE FailureType + ) +{ + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || FailureMessage == NULL) + { + return EFI_INVALID_PARAMETER; + } + + UnitTest->FailureType = FailureType; + AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + + return EFI_SUCCESS; +} // AddUnitTestFailure() + + +STATIC +VOID +UnitTestLogFailure( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + VA_LIST Marker; + + + // + // Convert the message to an ASCII String + // + VA_START(Marker, Format); + AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); + VA_END(Marker); + + // + // Finally, add the string to the log. + // + AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); + + return; +} // UnitTestLogFailure() + + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (!Expression) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); + } + return Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (Expression) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + } + return !Expression; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (EFI_ERROR( Status )) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); + } + return !EFI_ERROR( Status ); +} + + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA != ValueB)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + return FALSE; + } + return TRUE; +} + + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA == ValueB)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA != ValueB); +} + + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if ((Status != Expected)) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); + UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); + } + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + if (Pointer == NULL) + { + UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + } + return (Pointer != NULL); + +} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf index 6ba5d177f33..a3a0df2fdf1 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf @@ -1,38 +1,38 @@ -## @file -# Library to support simple and readable Unit Test Assert -# -# -# @copyright -# Copyright (c) 2017 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestAssertLib -FILE_GUID = FDDB0735-04FE-447C-B987-305988BDC983 -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestAssertLib - - -[LibraryClasses] - DebugLib - BaseLib - BaseMemoryLib - UnitTestLogLib - PrintLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - -[Sources] - UnitTestAssertLib.c +## @file +# Library to support simple and readable Unit Test Assert +# +# +# @copyright +# Copyright (c) 2017 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestAssertLib +FILE_GUID = FDDB0735-04FE-447C-B987-305988BDC983 +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestAssertLib + + +[LibraryClasses] + DebugLib + BaseLib + BaseMemoryLib + UnitTestLogLib + PrintLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + +[Sources] + UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c index 349b229d63c..762543ed9db 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c @@ -1,18 +1,18 @@ -/** - -NULL implementation for UnitTestBootLib to allow simple compliation - - -Copyright (c) Microsoft -**/ - -#include - -EFI_STATUS -EFIAPI -SetBootNextDevice( - VOID -) -{ - return EFI_UNSUPPORTED; -} \ No newline at end of file +/** + +NULL implementation for UnitTestBootLib to allow simple compliation + + +Copyright (c) Microsoft +**/ + +#include + +EFI_STATUS +EFIAPI +SetBootNextDevice( + VOID +) +{ + return EFI_UNSUPPORTED; +} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf index 5b0ac87d5b6..b05a5fc7d48 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf @@ -1,28 +1,28 @@ -## @file -# NULL library for UnitTestBootUsb -# -# -# @copyright -# Copyright (c) 2018 Microsoft Corporation. All rights reserved -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestBootLibNull -FILE_GUID = f143e75d-76e1-4040-b134-8f4f0bd5e3bd -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestBootLib - - -[LibraryClasses] - -[Packages] - MdePkg/MdePkg.dec - -[Guids] - -[Sources] - UnitTestBootLibNull.c +## @file +# NULL library for UnitTestBootUsb +# +# +# @copyright +# Copyright (c) 2018 Microsoft Corporation. All rights reserved +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestBootLibNull +FILE_GUID = f143e75d-76e1-4040-b134-8f4f0bd5e3bd +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestBootLib + + +[LibraryClasses] + +[Packages] + MdePkg/MdePkg.dec + +[Guids] + +[Sources] + UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c index a47f4a59aac..bd3d956c1bb 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c @@ -1,858 +1,858 @@ -/** -Implement UnitTestLib - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - - -// Prototyped here so that it can be included near the functions that -// it logically goes with. -STATIC -VOID -UpdateTestFromSave ( - IN OUT UNIT_TEST *Test, - IN UNIT_TEST_SAVE_HEADER *SavedState - ); - - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - - -/** - This function will determine whether the short name violates any rules that would - prevent it from being used as a reporting name or as a serialization name. - - Example: If the name cannot be serialized to a filesystem file name. - - @param[in] ShortTitleString A pointer to the short title string to be evaluated. - - @retval TRUE The string is acceptable. - @retval FALSE The string should not be used. - -**/ -STATIC -BOOLEAN -IsFrameworkShortNameValid ( - IN CHAR8 *ShortTitleString - ) -{ - // TODO: Finish this function. - return TRUE; -} // IsFrameworkShortNameValid() - - -STATIC -CHAR8* -AllocateAndCopyString ( - IN CHAR8 *StringToCopy - ) -{ - CHAR8 *NewString = NULL; - UINTN NewStringLength; - - NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; - NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); - if (NewString != NULL) - { - AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); - } - - return NewString; -} // AllocateAndCopyString () - - -STATIC -VOID -SetFrameworkFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - UINT32 NewFingerprint; - - // For this one we'll just use the title and version as the unique fingerprint. - NewFingerprint = CalculateCrc32( Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetFrameworkFingerprint() - - -STATIC -VOID -SetSuiteFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_FRAMEWORK *Framework, - IN UNIT_TEST_SUITE *Suite - ) -{ - UINT32 NewFingerprint; - - // For this one, we'll use the fingerprint from the framework, and the title of the suite. - NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetSuiteFingerprint() - - -STATIC -VOID -SetTestFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_SUITE *Suite, - IN UNIT_TEST *Test - ) -{ - UINT32 NewFingerprint; - - // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. - NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetTestFingerprint() - - -STATIC -BOOLEAN -CompareFingerprints ( - IN UINT8 *FingerprintA, - IN UINT8 *FingerprintB - ) -{ - return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); -} // SetTestFingerprint() - - -EFI_STATUS -EFIAPI -FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestFramework() - - -STATIC -EFI_STATUS -FreeUnitTestSuiteEntry ( - IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestSuiteEntry() - - -STATIC -EFI_STATUS -FreeUnitTestTestEntry ( - IN UNIT_TEST_LIST_ENTRY *TestEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestTestEntry() - - -//============================================================================= -// -// ---------------- TEST SETUP FUNCTIONS ------------------------------------- -// -//============================================================================= - - -/* -Method to Initialize the Unit Test framework - -@retval Success - Unit Test init. -@retval EFI_ERROR - Unit Tests init failed. -*/ -EFI_STATUS -EFIAPI -InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_FRAMEWORK *NewFramework = NULL; - - // - // First, check all pointers and make sure nothing's broked. - if (Framework == NULL || Title == NULL || - ShortTitle == NULL || VersionString == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, determine whether all of the strings are good to use. - if (!IsFrameworkShortNameValid( ShortTitle )) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, set aside some space to start messing with the framework. - NewFramework = AllocateZeroPool( sizeof( UNIT_TEST_FRAMEWORK ) ); - if (NewFramework == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Next, set up all the test data. - NewFramework->Title = AllocateAndCopyString( Title ); - NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); - NewFramework->VersionString = AllocateAndCopyString( VersionString ); - NewFramework->Log = NULL; - NewFramework->CurrentTest = NULL; - NewFramework->SavedState = NULL; - if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || - NewFramework->VersionString == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - InitializeListHead( &(NewFramework->TestSuiteList) ); - - // - // Create the framework fingerprint. - SetFrameworkFingerprint( &NewFramework->Fingerprint[0], NewFramework ); - - // - // If there is a persisted context, load it now. - if (DoesCacheExist( NewFramework )) - { - UNIT_TEST_SAVE_HEADER *SavedState = (UNIT_TEST_SAVE_HEADER*)NewFramework->SavedState; - Status = LoadUnitTestCache( NewFramework, &SavedState ); - if (EFI_ERROR( Status )) - { - // Don't actually report it as an error, but emit a warning. - DEBUG(( DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__ )); - Status = EFI_SUCCESS; - } - } - -Exit: - // - // If we're good, then let's copy the framework. - if (!EFI_ERROR( Status )) - { - *Framework = NewFramework; - } - // Otherwise, we need to undo this horrible thing that we've done. - else - { - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; - UNIT_TEST_FRAMEWORK *Framework; - - Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - - // - // First, let's check to make sure that our parameters look good. - if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewSuiteEntry = AllocateZeroPool( sizeof( UNIT_TEST_SUITE_LIST_ENTRY ) ); - if (NewSuiteEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); - NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); - NewSuiteEntry->UTS.Setup = Sup; - NewSuiteEntry->UTS.Teardown = Tdn; - NewSuiteEntry->UTS.ParentFramework = Framework; - InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. - InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. - if (NewSuiteEntry->UTS.Title == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - if (NewSuiteEntry->UTS.Package == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Create the suite fingerprint. - SetSuiteFingerprint( &NewSuiteEntry->UTS.Fingerprint[0], Framework, &NewSuiteEntry->UTS ); - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(Framework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); - *Suite = &NewSuiteEntry->UTS; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestSuiteEntry( NewSuiteEntry ); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE SuiteHandle, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_LIST_ENTRY *NewTestEntry; - UNIT_TEST_FRAMEWORK *ParentFramework; - UNIT_TEST_SUITE *Suite; - - Suite = (UNIT_TEST_SUITE*)SuiteHandle; - ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; - - // - // First, let's check to make sure that our parameters look good. - if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewTestEntry = AllocateZeroPool( sizeof( UNIT_TEST_LIST_ENTRY ) ); - if (NewTestEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewTestEntry->UT.Description = AllocateAndCopyString( Description ); - NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); - NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; - NewTestEntry->UT.FailureMessage[0] = '\0'; - NewTestEntry->UT.Log = NULL; - NewTestEntry->UT.PreReq = PreReq; - NewTestEntry->UT.CleanUp = CleanUp; - NewTestEntry->UT.RunTest = Func; - NewTestEntry->UT.Context = Context; - NewTestEntry->UT.Result = UNIT_TEST_PENDING; - NewTestEntry->UT.ParentSuite = Suite; - InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. - if (NewTestEntry->UT.Description == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Create the test fingerprint. - SetTestFingerprint( &NewTestEntry->UT.Fingerprint[0], Suite, &NewTestEntry->UT ); - - // TODO: Make sure that duplicate fingerprints cannot be created. - - // - // If there is saved test data, update this record. - if (ParentFramework->SavedState != NULL) - { - UpdateTestFromSave( &NewTestEntry->UT, ParentFramework->SavedState ); - } - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(Suite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestTestEntry( NewTestEntry ); - } - - return Status; -} - - -//============================================================================= -// -// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -EFI_STATUS -RunTestSuite ( - IN UNIT_TEST_SUITE *Suite - ) -{ - UNIT_TEST_LIST_ENTRY *TestEntry = NULL; - UNIT_TEST *Test; - UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; - - if (Suite == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - - if (Suite->Setup != NULL) - { - Suite->Setup( Suite->ParentFramework ); - } - - // - // Iterate all tests within the suite - // - for (TestEntry = (UNIT_TEST_LIST_ENTRY*)GetFirstNode( &(Suite->TestCaseList) ); // Start at the beginning. - (LIST_ENTRY*)TestEntry != &(Suite->TestCaseList); // Go until you loop back to the head. - TestEntry = (UNIT_TEST_LIST_ENTRY*)GetNextNode( &(Suite->TestCaseList), (LIST_ENTRY*)TestEntry) ) // Always get the next test. - { - Test = &TestEntry->UT; - ParentFramework->CurrentTest = Test; - - DEBUG((DEBUG_VERBOSE, "*********************************************************\n")); - DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %a:\n", Test->Description)); - DEBUG((DEBUG_VERBOSE, "**********************************************************\n")); - - // - // First, check to see whether the test has already been run. - // NOTE: This would generally only be the case if a saved state was detected and loaded. - if (Test->Result != UNIT_TEST_PENDING && Test->Result != UNIT_TEST_RUNNING) - { - DEBUG(( DEBUG_VERBOSE, "Test was run on a previous pass. Skipping.\n" )); - ParentFramework->CurrentTest = NULL; - continue; - } - - // - // Next, if we're still running, make sure that our test prerequisites are in place. - if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) - { - DEBUG(( DEBUG_VERBOSE, "PREREQ\n" )); - if (Test->PreReq( Suite->ParentFramework, Test->Context ) != UNIT_TEST_PASSED) - { - DEBUG(( DEBUG_ERROR, "PreReq Not Met\n" )); - Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; - ParentFramework->CurrentTest = NULL; - continue; - } - } - - // - // Now we should be ready to call the actual test. - // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot - // or quit. The UNIT_TEST_RUNNING state will allow the test to resume - // but will prevent the PreReq from being dispatched a second time. - Test->Result = UNIT_TEST_RUNNING; - Test->Result = Test->RunTest( Suite->ParentFramework, Test->Context ); - - // - // Finally, clean everything up, if need be. - if (Test->CleanUp != NULL) - { - DEBUG(( DEBUG_VERBOSE, "CLEANUP\n" )); - Test->CleanUp( Suite->ParentFramework, Test->Context ); - } - - // - // End the test. - ParentFramework->CurrentTest = NULL; - } // End Test iteration - - - if (Suite->Teardown != NULL) - { - Suite->Teardown( Suite->ParentFramework ); - } - - return EFI_SUCCESS; -} - -EFI_STATUS -EFIAPI -RunAllTestSuites ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - UNIT_TEST_FRAMEWORK *Framework; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - EFI_STATUS Status; - - Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - Status = RunTestSuite(&(Suite->UTS)); - if (EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); - } - } // End Suite iteration - - //Save current state so if test is started again it doesn't have to run. It will just report - SaveFrameworkState(Framework, NULL, 0); - OutputUnitTestFrameworkReport(Framework); - - return EFI_SUCCESS; -} - -//============================================================================= -// -// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- -// -//============================================================================= - - -STATIC -VOID -UpdateTestFromSave ( - IN OUT UNIT_TEST *Test, - IN UNIT_TEST_SAVE_HEADER *SavedState - ) -{ - UNIT_TEST_SAVE_TEST *CurrentTest, *MatchingTest; - UINT8 *FloatingPointer; - UNIT_TEST_SAVE_CONTEXT *SavedContext; - UINTN Index; - - // - // First, evaluate the inputs. - if (Test == NULL || SavedState == NULL) - { - return; - } - if (SavedState->TestCount == 0) - { - return; - } - - // - // Next, determine whether a matching test can be found. - // Start at the beginning. - MatchingTest = NULL; - FloatingPointer = (UINT8*)SavedState + sizeof( *SavedState ); - for (Index = 0; Index < SavedState->TestCount; Index++) - { - CurrentTest = (UNIT_TEST_SAVE_TEST*)FloatingPointer; - if (CompareFingerprints( &Test->Fingerprint[0], &CurrentTest->Fingerprint[0] )) - { - MatchingTest = CurrentTest; - // If there's a saved context, it's important that we iterate through the entire list. - if (!SavedState->HasSavedContext) - { - break; - } - } - - // If we didn't find it, we have to increment to the next test. - FloatingPointer = (UINT8*)CurrentTest + CurrentTest->Size; - } - - // - // If a matching test was found, copy the status. - if (MatchingTest) - { - // Override the test status with the saved status. - Test->Result = MatchingTest->Result; - - Test->FailureType = MatchingTest->FailureType; - AsciiStrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); - - // If there is a log string associated, grab that. - // We can tell that there's a log string because the "size" will be larger than - // the structure size. - // IMPORTANT NOTE: There are security implications here. - // This data is user-supplied and we're about to play kinda - // fast and loose with data buffers. - if (MatchingTest->Size > sizeof( UNIT_TEST_SAVE_TEST )) - { - UnitTestLogInit(Test, (UINT8*)MatchingTest->Log, MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); - } - } - - // - // If the saved context exists and matches this test, grab it, too. - if (SavedState->HasSavedContext) - { - // If there was a saved context, the "matching test" loop will have placed the FloatingPointer - // at the beginning of the context structure. - SavedContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - if ((SavedContext->Size - sizeof(UNIT_TEST_SAVE_CONTEXT)) > 0 && - CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) - { - // Override the test context with the saved context. - Test->Context = (VOID*)SavedContext->Data; - } - } - - return; -} // UpdateTestFromSave() - - -STATIC -UNIT_TEST_SAVE_HEADER* -SerializeState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - UNIT_TEST_FRAMEWORK *Framework = FrameworkHandle; - UNIT_TEST_SAVE_HEADER *Header = NULL; - LIST_ENTRY *SuiteListHead, *Suite, *TestListHead, *Test; - UINT32 TestCount, TotalSize; - UINTN LogSize; - UNIT_TEST_SAVE_TEST *TestSaveData; - UNIT_TEST_SAVE_CONTEXT *TestSaveContext; - UNIT_TEST *UnitTest; - UINT8 *FloatingPointer; - - // - // First, let's not make assumptions about the parameters. - if (Framework == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || - ContextToSaveSize > MAX_UINT32) - { - return NULL; - } - - // - // Next, we've gotta figure out the resources that will be required to serialize the - // the framework state so that we can persist it. - // To start with, we're gonna need a header. - TotalSize = sizeof( UNIT_TEST_SAVE_HEADER ); - // Now we need to figure out how many tests there are. - TestCount = 0; - // Iterate all suites. - SuiteListHead = &Framework->TestSuiteList; - for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) - { - // Iterate all tests within the suite. - TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; - for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) - { - UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; - // Account for the size of a test structure. - TotalSize += sizeof( UNIT_TEST_SAVE_TEST ); - // If there's a log, make sure to account for the log size. - if (UnitTest->Log != NULL) - { - // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); - ASSERT( LogSize < MAX_UINT32 ); - TotalSize += (UINT32)LogSize; - } - // Increment the test count. - TestCount++; - } - } - // If there are no tests, we're done here. - if (TestCount == 0) - { - return NULL; - } - // Add room for the context, if there is one. - if (ContextToSave != NULL) - { - TotalSize += sizeof( UNIT_TEST_SAVE_CONTEXT ) + (UINT32)ContextToSaveSize; - } - - // - // Now that we know the size, we need to allocate space for the serialized output. - Header = AllocateZeroPool( TotalSize ); - if (Header == NULL) - { - return NULL; - } - - // - // Alright, let's start setting up some data. - Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; - Header->SaveStateSize = TotalSize; - CopyMem( &Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - CopyMem( &Header->StartTime, &Framework->StartTime, sizeof( EFI_TIME ) ); - Header->TestCount = TestCount; - Header->HasSavedContext = FALSE; - - // - // Start adding all of the test cases. - // Set the floating pointer to the start of the current test save buffer. - FloatingPointer = (UINT8*)Header + sizeof( UNIT_TEST_SAVE_HEADER ); - // Iterate all suites. - SuiteListHead = &Framework->TestSuiteList; - for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) - { - // Iterate all tests within the suite. - TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; - for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) - { - TestSaveData = (UNIT_TEST_SAVE_TEST*)FloatingPointer; - UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; - - // Save the fingerprint. - CopyMem( &TestSaveData->Fingerprint[0], &UnitTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - - // Save the result. - TestSaveData->Result = UnitTest->Result; - TestSaveData->FailureType = UnitTest->FailureType; - AsciiStrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); - - - // If there is a log, save the log. - FloatingPointer += sizeof( UNIT_TEST_SAVE_TEST ); - if (UnitTest->Log != NULL) - { - // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); - CopyMem( FloatingPointer, UnitTest->Log, LogSize ); - FloatingPointer += LogSize; - } - - // Update the size once the structure is complete. - // NOTE: Should thise be a straight cast without validation? - // Maybe. - // Am I tired of writing code? - // Yes. - TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8*)TestSaveData); - } - } - - // - // If there is a context to save, let's do that now. - if (ContextToSave != NULL && Framework->CurrentTest != NULL) - { - TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - TestSaveContext->Size = (UINT32)ContextToSaveSize + sizeof(UNIT_TEST_SAVE_CONTEXT); - CopyMem( &TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - CopyMem( ((UINT8*)TestSaveContext + sizeof( UNIT_TEST_SAVE_CONTEXT )), ContextToSave, ContextToSaveSize ); - Header->HasSavedContext = TRUE; - } - - return Header; -} - - -EFI_STATUS -EFIAPI -SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - EFI_STATUS Status; - UNIT_TEST_SAVE_HEADER *Header = NULL; - - // - // First, let's not make assumptions about the parameters. - if (FrameworkHandle == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || - ContextToSaveSize > MAX_UINT32) - { - return EFI_INVALID_PARAMETER; - } - - // - // Now, let's package up all the data for saving. - Header = SerializeState( FrameworkHandle, ContextToSave, ContextToSaveSize ); - if (Header == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // All that should be left to do is save it using the associated persistence lib. - Status = SaveUnitTestCache( FrameworkHandle, Header ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status )); - Status = EFI_DEVICE_ERROR; - } - - // - // Free data that was used. - FreePool( Header ); - - return Status; -} // SaveFrameworkState() +/** +Implement UnitTestLib + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include + +#include +#include +#include +#include + + +// Prototyped here so that it can be included near the functions that +// it logically goes with. +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ); + + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + + +/** + This function will determine whether the short name violates any rules that would + prevent it from being used as a reporting name or as a serialization name. + + Example: If the name cannot be serialized to a filesystem file name. + + @param[in] ShortTitleString A pointer to the short title string to be evaluated. + + @retval TRUE The string is acceptable. + @retval FALSE The string should not be used. + +**/ +STATIC +BOOLEAN +IsFrameworkShortNameValid ( + IN CHAR8 *ShortTitleString + ) +{ + // TODO: Finish this function. + return TRUE; +} // IsFrameworkShortNameValid() + + +STATIC +CHAR8* +AllocateAndCopyString ( + IN CHAR8 *StringToCopy + ) +{ + CHAR8 *NewString = NULL; + UINTN NewStringLength; + + NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; + NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); + if (NewString != NULL) + { + AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); + } + + return NewString; +} // AllocateAndCopyString () + + +STATIC +VOID +SetFrameworkFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + UINT32 NewFingerprint; + + // For this one we'll just use the title and version as the unique fingerprint. + NewFingerprint = CalculateCrc32( Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} // SetFrameworkFingerprint() + + +STATIC +VOID +SetSuiteFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework, + IN UNIT_TEST_SUITE *Suite + ) +{ + UINT32 NewFingerprint; + + // For this one, we'll use the fingerprint from the framework, and the title of the suite. + NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} // SetSuiteFingerprint() + + +STATIC +VOID +SetTestFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_SUITE *Suite, + IN UNIT_TEST *Test + ) +{ + UINT32 NewFingerprint; + + // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. + NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} // SetTestFingerprint() + + +STATIC +BOOLEAN +CompareFingerprints ( + IN UINT8 *FingerprintA, + IN UINT8 *FingerprintB + ) +{ + return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); +} // SetTestFingerprint() + + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestFramework() + + +STATIC +EFI_STATUS +FreeUnitTestSuiteEntry ( + IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestSuiteEntry() + + +STATIC +EFI_STATUS +FreeUnitTestTestEntry ( + IN UNIT_TEST_LIST_ENTRY *TestEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} // FreeUnitTestTestEntry() + + +//============================================================================= +// +// ---------------- TEST SETUP FUNCTIONS ------------------------------------- +// +//============================================================================= + + +/* +Method to Initialize the Unit Test framework + +@retval Success - Unit Test init. +@retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_FRAMEWORK *NewFramework = NULL; + + // + // First, check all pointers and make sure nothing's broked. + if (Framework == NULL || Title == NULL || + ShortTitle == NULL || VersionString == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, determine whether all of the strings are good to use. + if (!IsFrameworkShortNameValid( ShortTitle )) + { + return EFI_INVALID_PARAMETER; + } + + // + // Next, set aside some space to start messing with the framework. + NewFramework = AllocateZeroPool( sizeof( UNIT_TEST_FRAMEWORK ) ); + if (NewFramework == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Next, set up all the test data. + NewFramework->Title = AllocateAndCopyString( Title ); + NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); + NewFramework->VersionString = AllocateAndCopyString( VersionString ); + NewFramework->Log = NULL; + NewFramework->CurrentTest = NULL; + NewFramework->SavedState = NULL; + if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || + NewFramework->VersionString == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + InitializeListHead( &(NewFramework->TestSuiteList) ); + + // + // Create the framework fingerprint. + SetFrameworkFingerprint( &NewFramework->Fingerprint[0], NewFramework ); + + // + // If there is a persisted context, load it now. + if (DoesCacheExist( NewFramework )) + { + UNIT_TEST_SAVE_HEADER *SavedState = (UNIT_TEST_SAVE_HEADER*)NewFramework->SavedState; + Status = LoadUnitTestCache( NewFramework, &SavedState ); + if (EFI_ERROR( Status )) + { + // Don't actually report it as an error, but emit a warning. + DEBUG(( DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__ )); + Status = EFI_SUCCESS; + } + } + +Exit: + // + // If we're good, then let's copy the framework. + if (!EFI_ERROR( Status )) + { + *Framework = NewFramework; + } + // Otherwise, we need to undo this horrible thing that we've done. + else + { + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN CHAR8 *Title, + IN CHAR8 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + UNIT_TEST_FRAMEWORK *Framework; + + Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; + + // + // First, let's check to make sure that our parameters look good. + if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewSuiteEntry = AllocateZeroPool( sizeof( UNIT_TEST_SUITE_LIST_ENTRY ) ); + if (NewSuiteEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); + NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); + NewSuiteEntry->UTS.Setup = Sup; + NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.ParentFramework = Framework; + InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. + InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. + if (NewSuiteEntry->UTS.Title == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + if (NewSuiteEntry->UTS.Package == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the suite fingerprint. + SetSuiteFingerprint( &NewSuiteEntry->UTS.Fingerprint[0], Framework, &NewSuiteEntry->UTS ); + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(Framework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); + *Suite = &NewSuiteEntry->UTS; + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestSuiteEntry( NewSuiteEntry ); + } + + return Status; +} + + +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE_HANDLE SuiteHandle, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ) +{ + EFI_STATUS Status = EFI_SUCCESS; + UNIT_TEST_LIST_ENTRY *NewTestEntry; + UNIT_TEST_FRAMEWORK *ParentFramework; + UNIT_TEST_SUITE *Suite; + + Suite = (UNIT_TEST_SUITE*)SuiteHandle; + ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; + + // + // First, let's check to make sure that our parameters look good. + if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) + { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewTestEntry = AllocateZeroPool( sizeof( UNIT_TEST_LIST_ENTRY ) ); + if (NewTestEntry == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewTestEntry->UT.Description = AllocateAndCopyString( Description ); + NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); + NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; + NewTestEntry->UT.FailureMessage[0] = '\0'; + NewTestEntry->UT.Log = NULL; + NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.CleanUp = CleanUp; + NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.Context = Context; + NewTestEntry->UT.Result = UNIT_TEST_PENDING; + NewTestEntry->UT.ParentSuite = Suite; + InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. + if (NewTestEntry->UT.Description == NULL) + { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the test fingerprint. + SetTestFingerprint( &NewTestEntry->UT.Fingerprint[0], Suite, &NewTestEntry->UT ); + + // TODO: Make sure that duplicate fingerprints cannot be created. + + // + // If there is saved test data, update this record. + if (ParentFramework->SavedState != NULL) + { + UpdateTestFromSave( &NewTestEntry->UT, ParentFramework->SavedState ); + } + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + if (!EFI_ERROR( Status )) + { + InsertTailList( &(Suite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); + } + // Otherwise, make with the destruction. + else + { + FreeUnitTestTestEntry( NewTestEntry ); + } + + return Status; +} + + +//============================================================================= +// +// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +EFI_STATUS +RunTestSuite ( + IN UNIT_TEST_SUITE *Suite + ) +{ + UNIT_TEST_LIST_ENTRY *TestEntry = NULL; + UNIT_TEST *Test; + UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; + + if (Suite == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + if (Suite->Setup != NULL) + { + Suite->Setup( Suite->ParentFramework ); + } + + // + // Iterate all tests within the suite + // + for (TestEntry = (UNIT_TEST_LIST_ENTRY*)GetFirstNode( &(Suite->TestCaseList) ); // Start at the beginning. + (LIST_ENTRY*)TestEntry != &(Suite->TestCaseList); // Go until you loop back to the head. + TestEntry = (UNIT_TEST_LIST_ENTRY*)GetNextNode( &(Suite->TestCaseList), (LIST_ENTRY*)TestEntry) ) // Always get the next test. + { + Test = &TestEntry->UT; + ParentFramework->CurrentTest = Test; + + DEBUG((DEBUG_VERBOSE, "*********************************************************\n")); + DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %a:\n", Test->Description)); + DEBUG((DEBUG_VERBOSE, "**********************************************************\n")); + + // + // First, check to see whether the test has already been run. + // NOTE: This would generally only be the case if a saved state was detected and loaded. + if (Test->Result != UNIT_TEST_PENDING && Test->Result != UNIT_TEST_RUNNING) + { + DEBUG(( DEBUG_VERBOSE, "Test was run on a previous pass. Skipping.\n" )); + ParentFramework->CurrentTest = NULL; + continue; + } + + // + // Next, if we're still running, make sure that our test prerequisites are in place. + if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) + { + DEBUG(( DEBUG_VERBOSE, "PREREQ\n" )); + if (Test->PreReq( Suite->ParentFramework, Test->Context ) != UNIT_TEST_PASSED) + { + DEBUG(( DEBUG_ERROR, "PreReq Not Met\n" )); + Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; + ParentFramework->CurrentTest = NULL; + continue; + } + } + + // + // Now we should be ready to call the actual test. + // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot + // or quit. The UNIT_TEST_RUNNING state will allow the test to resume + // but will prevent the PreReq from being dispatched a second time. + Test->Result = UNIT_TEST_RUNNING; + Test->Result = Test->RunTest( Suite->ParentFramework, Test->Context ); + + // + // Finally, clean everything up, if need be. + if (Test->CleanUp != NULL) + { + DEBUG(( DEBUG_VERBOSE, "CLEANUP\n" )); + Test->CleanUp( Suite->ParentFramework, Test->Context ); + } + + // + // End the test. + ParentFramework->CurrentTest = NULL; + } // End Test iteration + + + if (Suite->Teardown != NULL) + { + Suite->Teardown( Suite->ParentFramework ); + } + + return EFI_SUCCESS; +} + +EFI_STATUS +EFIAPI +RunAllTestSuites ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + EFI_STATUS Status; + + Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + Status = RunTestSuite(&(Suite->UTS)); + if (EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); + } + } // End Suite iteration + + //Save current state so if test is started again it doesn't have to run. It will just report + SaveFrameworkState(Framework, NULL, 0); + OutputUnitTestFrameworkReport(Framework); + + return EFI_SUCCESS; +} + +//============================================================================= +// +// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- +// +//============================================================================= + + +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ) +{ + UNIT_TEST_SAVE_TEST *CurrentTest, *MatchingTest; + UINT8 *FloatingPointer; + UNIT_TEST_SAVE_CONTEXT *SavedContext; + UINTN Index; + + // + // First, evaluate the inputs. + if (Test == NULL || SavedState == NULL) + { + return; + } + if (SavedState->TestCount == 0) + { + return; + } + + // + // Next, determine whether a matching test can be found. + // Start at the beginning. + MatchingTest = NULL; + FloatingPointer = (UINT8*)SavedState + sizeof( *SavedState ); + for (Index = 0; Index < SavedState->TestCount; Index++) + { + CurrentTest = (UNIT_TEST_SAVE_TEST*)FloatingPointer; + if (CompareFingerprints( &Test->Fingerprint[0], &CurrentTest->Fingerprint[0] )) + { + MatchingTest = CurrentTest; + // If there's a saved context, it's important that we iterate through the entire list. + if (!SavedState->HasSavedContext) + { + break; + } + } + + // If we didn't find it, we have to increment to the next test. + FloatingPointer = (UINT8*)CurrentTest + CurrentTest->Size; + } + + // + // If a matching test was found, copy the status. + if (MatchingTest) + { + // Override the test status with the saved status. + Test->Result = MatchingTest->Result; + + Test->FailureType = MatchingTest->FailureType; + AsciiStrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + + // If there is a log string associated, grab that. + // We can tell that there's a log string because the "size" will be larger than + // the structure size. + // IMPORTANT NOTE: There are security implications here. + // This data is user-supplied and we're about to play kinda + // fast and loose with data buffers. + if (MatchingTest->Size > sizeof( UNIT_TEST_SAVE_TEST )) + { + UnitTestLogInit(Test, (UINT8*)MatchingTest->Log, MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); + } + } + + // + // If the saved context exists and matches this test, grab it, too. + if (SavedState->HasSavedContext) + { + // If there was a saved context, the "matching test" loop will have placed the FloatingPointer + // at the beginning of the context structure. + SavedContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; + if ((SavedContext->Size - sizeof(UNIT_TEST_SAVE_CONTEXT)) > 0 && + CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) + { + // Override the test context with the saved context. + Test->Context = (VOID*)SavedContext->Data; + } + } + + return; +} // UpdateTestFromSave() + + +STATIC +UNIT_TEST_SAVE_HEADER* +SerializeState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + UNIT_TEST_FRAMEWORK *Framework = FrameworkHandle; + UNIT_TEST_SAVE_HEADER *Header = NULL; + LIST_ENTRY *SuiteListHead, *Suite, *TestListHead, *Test; + UINT32 TestCount, TotalSize; + UINTN LogSize; + UNIT_TEST_SAVE_TEST *TestSaveData; + UNIT_TEST_SAVE_CONTEXT *TestSaveContext; + UNIT_TEST *UnitTest; + UINT8 *FloatingPointer; + + // + // First, let's not make assumptions about the parameters. + if (Framework == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) + { + return NULL; + } + + // + // Next, we've gotta figure out the resources that will be required to serialize the + // the framework state so that we can persist it. + // To start with, we're gonna need a header. + TotalSize = sizeof( UNIT_TEST_SAVE_HEADER ); + // Now we need to figure out how many tests there are. + TestCount = 0; + // Iterate all suites. + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) + { + // Iterate all tests within the suite. + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) + { + UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; + // Account for the size of a test structure. + TotalSize += sizeof( UNIT_TEST_SAVE_TEST ); + // If there's a log, make sure to account for the log size. + if (UnitTest->Log != NULL) + { + // The +1 is for the NULL character. Can't forget the NULL character. + LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); + ASSERT( LogSize < MAX_UINT32 ); + TotalSize += (UINT32)LogSize; + } + // Increment the test count. + TestCount++; + } + } + // If there are no tests, we're done here. + if (TestCount == 0) + { + return NULL; + } + // Add room for the context, if there is one. + if (ContextToSave != NULL) + { + TotalSize += sizeof( UNIT_TEST_SAVE_CONTEXT ) + (UINT32)ContextToSaveSize; + } + + // + // Now that we know the size, we need to allocate space for the serialized output. + Header = AllocateZeroPool( TotalSize ); + if (Header == NULL) + { + return NULL; + } + + // + // Alright, let's start setting up some data. + Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; + Header->SaveStateSize = TotalSize; + CopyMem( &Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + CopyMem( &Header->StartTime, &Framework->StartTime, sizeof( EFI_TIME ) ); + Header->TestCount = TestCount; + Header->HasSavedContext = FALSE; + + // + // Start adding all of the test cases. + // Set the floating pointer to the start of the current test save buffer. + FloatingPointer = (UINT8*)Header + sizeof( UNIT_TEST_SAVE_HEADER ); + // Iterate all suites. + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) + { + // Iterate all tests within the suite. + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) + { + TestSaveData = (UNIT_TEST_SAVE_TEST*)FloatingPointer; + UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; + + // Save the fingerprint. + CopyMem( &TestSaveData->Fingerprint[0], &UnitTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + + // Save the result. + TestSaveData->Result = UnitTest->Result; + TestSaveData->FailureType = UnitTest->FailureType; + AsciiStrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + + + // If there is a log, save the log. + FloatingPointer += sizeof( UNIT_TEST_SAVE_TEST ); + if (UnitTest->Log != NULL) + { + // The +1 is for the NULL character. Can't forget the NULL character. + LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); + CopyMem( FloatingPointer, UnitTest->Log, LogSize ); + FloatingPointer += LogSize; + } + + // Update the size once the structure is complete. + // NOTE: Should thise be a straight cast without validation? + // Maybe. + // Am I tired of writing code? + // Yes. + TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8*)TestSaveData); + } + } + + // + // If there is a context to save, let's do that now. + if (ContextToSave != NULL && Framework->CurrentTest != NULL) + { + TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; + TestSaveContext->Size = (UINT32)ContextToSaveSize + sizeof(UNIT_TEST_SAVE_CONTEXT); + CopyMem( &TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + CopyMem( ((UINT8*)TestSaveContext + sizeof( UNIT_TEST_SAVE_CONTEXT )), ContextToSave, ContextToSaveSize ); + Header->HasSavedContext = TRUE; + } + + return Header; +} + + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ) +{ + EFI_STATUS Status; + UNIT_TEST_SAVE_HEADER *Header = NULL; + + // + // First, let's not make assumptions about the parameters. + if (FrameworkHandle == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) + { + return EFI_INVALID_PARAMETER; + } + + // + // Now, let's package up all the data for saving. + Header = SerializeState( FrameworkHandle, ContextToSave, ContextToSaveSize ); + if (Header == NULL) + { + return EFI_OUT_OF_RESOURCES; + } + + // + // All that should be left to do is save it using the associated persistence lib. + Status = SaveUnitTestCache( FrameworkHandle, Header ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status )); + Status = EFI_DEVICE_ERROR; + } + + // + // Free data that was used. + FreePool( Header ); + + return Status; +} // SaveFrameworkState() diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf index 3b4be9598ae..b9576db4359 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf @@ -1,43 +1,43 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibDxe -FILE_GUID = 98CEF9CA-15CE-40A3-ADE8-C299953CD0F6 -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UefiRuntimeServicesTableLib - UefiLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibDxe +FILE_GUID = 98CEF9CA-15CE-40A3-ADE8-C299953CD0F6 +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UefiRuntimeServicesTableLib + UefiLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf index 15b34fb8b55..910acb5229e 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf @@ -1,41 +1,41 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibPei -FILE_GUID = 7DDA6F03-CD2D-4B5D-BC67-E5EA5AE3014B -VERSION_STRING = 1.0 -MODULE_TYPE = PEIM -LIBRARY_CLASS = UnitTestLib|PEIM - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibPei +FILE_GUID = 7DDA6F03-CD2D-4B5D-BC67-E5EA5AE3014B +VERSION_STRING = 1.0 +MODULE_TYPE = PEIM +LIBRARY_CLASS = UnitTestLib|PEIM + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf index ea0b475cafc..32c554d5c5a 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf @@ -1,42 +1,42 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibSmm -FILE_GUID = 9A991713-AE25-4C41-9E3D-F72D6E0E7CEE -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_SMM_DRIVER -PI_SPECIFICATION_VERSION = 0x0001000A -LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c +## @file +# Library to support Unit Testing from UEFI shell +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLibSmm +FILE_GUID = 9A991713-AE25-4C41-9E3D-F72D6E0E7CEE +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_SMM_DRIVER +PI_SPECIFICATION_VERSION = 0x0001000A +LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER + + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + UnitTestLogLib + UnitTestPersistenceLib + UnitTestResultReportLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c index 7daac4950ab..c8234eacd3c 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c @@ -1,216 +1,216 @@ -/** - -Implement UnitTestLogLib - Unit test debugging log - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) -#define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) - - -struct _UNIT_TEST_LOG_PREFIX_STRING -{ - UNIT_TEST_STATUS LogLevel; - CHAR8 *String; -}; - -struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = -{ - { DEBUG_ERROR, "[ERROR] " }, - { DEBUG_WARN, "[WARNING] " }, - { DEBUG_INFO, "[INFO] " }, - { DEBUG_VERBOSE, "[VERBOSE] " } -}; -UINTN mLogPrefixStringsCount = sizeof( mLogPrefixStrings ) / sizeof( mLogPrefixStrings[0] ); - - - - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForStatusLogPrefix ( - IN UINTN LogLevel - ) -{ - UINTN Index; - CHAR8 *Result = NULL; - - for (Index = 0; Index < mLogPrefixStringsCount; Index++) - { - if (mLogPrefixStrings[Index].LogLevel == LogLevel) - { - Result = mLogPrefixStrings[Index].String; - break; - } - } - - return Result; -} - - - -STATIC -EFI_STATUS -AddStringToUnitTestLog ( - IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR8 *String - ) -{ - EFI_STATUS Status; - - // - // Make sure that you're cooking with gas. - // - if (UnitTest == NULL || String == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // If this is the first log for the test allocate log space - if (UnitTest->Log == NULL) - { - UnitTestLogInit(UnitTest, NULL, 0); - } - - if (UnitTest->Log == NULL) - { - DEBUG((DEBUG_ERROR, "Failed to allocate space for unit test log\n")); - ASSERT(UnitTest->Log != NULL); - return EFI_OUT_OF_RESOURCES; - } - - Status = AsciiStrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER / sizeof(CHAR8), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); - if(EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); - return Status; - } - - return EFI_SUCCESS; -} - - -//============================================================================= -// -// ---------------- PUBLIC FUNCTIONS ------------------------------------ -// -//============================================================================= - -/** - This function is responsible for initializing the log buffer for a single test. It can - be used internally, but may also be consumed by the test framework to add pre-existing - data to a log before it's used. - - @param[in,out] TestHandle A handle to the test being initialized. - @param[in] Buffer [Optional] A pointer to pre-existing log data that should - be used to initialize the log. Should include a NULL terminator. - @param[in] BufferSize [Optional] The size of the pre-existing log data. - -**/ -VOID -EFIAPI -UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer OPTIONAL, - IN UINTN BufferSize OPTIONAL - ) -{ - UNIT_TEST *Test; - - Test = (UNIT_TEST*)TestHandle; - - // - // Make sure that you're cooking with gas. - // - if (Test == NULL) - { - DEBUG((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); - return; - } - - // If this is the first log for the test allocate log space - if (Test->Log == NULL) - { - Test->Log = AllocateZeroPool(UNIT_TEST_MAX_LOG_BUFFER); - } - - //check again to make sure allocate worked - if(Test->Log == NULL) - { - DEBUG((DEBUG_ERROR, "Failed to allocate memory for the log\n")); - return; - } - - if((Buffer != NULL) && (BufferSize > 0) && ((BufferSize <= UNIT_TEST_MAX_LOG_BUFFER))) - { - CopyMem(Test->Log, Buffer, BufferSize); - } -} // UnitTestLogInit() - -VOID -EFIAPI -UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - ... - ) -{ - CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CONST CHAR8 *LogTypePrefix = NULL; - VA_LIST Marker; - UINTN LogLevel = (UINTN) PcdGet32(UnitTestLogLevel); - // - // Make sure that this debug mode is enabled. - // - if ((ErrorLevel & LogLevel) == 0) { - return; - } - - // - // If we need to define a new format string... - // well... get to it. - // - LogTypePrefix = GetStringForStatusLogPrefix( ErrorLevel ); - if (LogTypePrefix != NULL) - { - AsciiSPrint( NewFormatString, sizeof( NewFormatString ), "%a%a", LogTypePrefix, Format ); - } - else - { - AsciiStrCpyS( NewFormatString, sizeof( NewFormatString ), Format ); - } - - // - // Convert the message to an ASCII String - // - VA_START (Marker, Format); - AsciiVSPrint( LogString, sizeof( LogString ), NewFormatString, Marker ); - VA_END (Marker); - - // - // Finally, add the string to the log. - // - AddStringToUnitTestLog( ((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString ); - - return; -} +/** + +Implement UnitTestLogLib - Unit test debugging log + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include + +#include +#include + +#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) +#define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) + + +struct _UNIT_TEST_LOG_PREFIX_STRING +{ + UNIT_TEST_STATUS LogLevel; + CHAR8 *String; +}; + +struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = +{ + { DEBUG_ERROR, "[ERROR] " }, + { DEBUG_WARN, "[WARNING] " }, + { DEBUG_INFO, "[INFO] " }, + { DEBUG_VERBOSE, "[VERBOSE] " } +}; +UINTN mLogPrefixStringsCount = sizeof( mLogPrefixStrings ) / sizeof( mLogPrefixStrings[0] ); + + + + +//============================================================================= +// +// ---------------- TEST HELPER FUNCTIONS ------------------------------------ +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForStatusLogPrefix ( + IN UINTN LogLevel + ) +{ + UINTN Index; + CHAR8 *Result = NULL; + + for (Index = 0; Index < mLogPrefixStringsCount; Index++) + { + if (mLogPrefixStrings[Index].LogLevel == LogLevel) + { + Result = mLogPrefixStrings[Index].String; + break; + } + } + + return Result; +} + + + +STATIC +EFI_STATUS +AddStringToUnitTestLog ( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR8 *String + ) +{ + EFI_STATUS Status; + + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || String == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // If this is the first log for the test allocate log space + if (UnitTest->Log == NULL) + { + UnitTestLogInit(UnitTest, NULL, 0); + } + + if (UnitTest->Log == NULL) + { + DEBUG((DEBUG_ERROR, "Failed to allocate space for unit test log\n")); + ASSERT(UnitTest->Log != NULL); + return EFI_OUT_OF_RESOURCES; + } + + Status = AsciiStrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER / sizeof(CHAR8), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); + if(EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); + return Status; + } + + return EFI_SUCCESS; +} + + +//============================================================================= +// +// ---------------- PUBLIC FUNCTIONS ------------------------------------ +// +//============================================================================= + +/** + This function is responsible for initializing the log buffer for a single test. It can + be used internally, but may also be consumed by the test framework to add pre-existing + data to a log before it's used. + + @param[in,out] TestHandle A handle to the test being initialized. + @param[in] Buffer [Optional] A pointer to pre-existing log data that should + be used to initialize the log. Should include a NULL terminator. + @param[in] BufferSize [Optional] The size of the pre-existing log data. + +**/ +VOID +EFIAPI +UnitTestLogInit ( + IN OUT UNIT_TEST_HANDLE TestHandle, + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize OPTIONAL + ) +{ + UNIT_TEST *Test; + + Test = (UNIT_TEST*)TestHandle; + + // + // Make sure that you're cooking with gas. + // + if (Test == NULL) + { + DEBUG((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); + return; + } + + // If this is the first log for the test allocate log space + if (Test->Log == NULL) + { + Test->Log = AllocateZeroPool(UNIT_TEST_MAX_LOG_BUFFER); + } + + //check again to make sure allocate worked + if(Test->Log == NULL) + { + DEBUG((DEBUG_ERROR, "Failed to allocate memory for the log\n")); + return; + } + + if((Buffer != NULL) && (BufferSize > 0) && ((BufferSize <= UNIT_TEST_MAX_LOG_BUFFER))) + { + CopyMem(Test->Log, Buffer, BufferSize); + } +} // UnitTestLogInit() + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CONST CHAR8 *LogTypePrefix = NULL; + VA_LIST Marker; + UINTN LogLevel = (UINTN) PcdGet32(UnitTestLogLevel); + // + // Make sure that this debug mode is enabled. + // + if ((ErrorLevel & LogLevel) == 0) { + return; + } + + // + // If we need to define a new format string... + // well... get to it. + // + LogTypePrefix = GetStringForStatusLogPrefix( ErrorLevel ); + if (LogTypePrefix != NULL) + { + AsciiSPrint( NewFormatString, sizeof( NewFormatString ), "%a%a", LogTypePrefix, Format ); + } + else + { + AsciiStrCpyS( NewFormatString, sizeof( NewFormatString ), Format ); + } + + // + // Convert the message to an ASCII String + // + VA_START (Marker, Format); + AsciiVSPrint( LogString, sizeof( LogString ), NewFormatString, Marker ); + VA_END (Marker); + + // + // Finally, add the string to the log. + // + AddStringToUnitTestLog( ((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString ); + + return; +} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf index a0996d59ea0..90f70ea5c7c 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf @@ -1,42 +1,42 @@ -## @file -# Library to support Logging in the Unit Tests -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLogLib -FILE_GUID = D5F2DF71-6378-4E17-AE59-AE4109D34B5A -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestLogLib - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - PrintLib - PcdLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLogLib.c - -[Pcd] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES - +## @file +# Library to support Logging in the Unit Tests +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestLogLib +FILE_GUID = D5F2DF71-6378-4E17-AE59-AE4109D34B5A +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestLogLib + +[LibraryClasses] + DebugLib + MemoryAllocationLib + BaseMemoryLib + BaseLib + PrintLib + PcdLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestLogLib.c + +[Pcd] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES + diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index fff53b3f80f..0e487ebc2bc 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -1,94 +1,94 @@ -/** @file -- UnitTestNullPersistenceLib.c -This is an instance of the Unit Test Persistence Lib that does nothing. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ - -#include - -#include -#include -#include - - -/** - Determines whether a persistence cache already exists for - the given framework. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - - @retval TRUE - @retval FALSE Cache doesn't exist or an error occurred. - -**/ -BOOLEAN -EFIAPI -DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - return FALSE; -} // DoesCacheExist() - - -/** - Will save the data associated with an internal Unit Test Framework - state in a manner that can persist a Unit Test Application quit or - even a system reboot. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer to the buffer containing the serialized - framework internal state. - - @retval EFI_SUCCESS Data is persisted and the test can be safely quit. - @retval Others Data is not persisted and test cannot be resumed upon exit. - -**/ -EFI_STATUS -EFIAPI -SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData - ) -{ - return EFI_UNSUPPORTED; -} // SaveUnitTestCache() - - -/** - Will retrieve any cached state associated with the given framework. - Will allocate a buffer to hold the loaded data. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address - of the loaded data buffer. - - @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated - with a pointer to the buffer. - @retval Others An error has occurred and no data has been loaded. SaveData - is set to NULL. - -**/ -EFI_STATUS -EFIAPI -LoadUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData - ) -{ - return EFI_UNSUPPORTED; -} // LoadUnitTestCache() +/** @file -- UnitTestNullPersistenceLib.c +This is an instance of the Unit Test Persistence Lib that does nothing. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include + +#include +#include +#include + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + return FALSE; +} // DoesCacheExist() + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + return EFI_UNSUPPORTED; +} // SaveUnitTestCache() + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + return EFI_UNSUPPORTED; +} // LoadUnitTestCache() diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf index a39e99b43a8..3b1090fa25c 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -1,44 +1,44 @@ -## @file UnitTestPersistenceLibNull.inf -# This is an instance of the Unit Test Persistence Lib does nothing. -# -# @copyright -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -# THE POSSIBILITY OF SUCH DAMAGE. -# -# -# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. -# -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestPersistenceLibNull - FILE_GUID = B8553C7A-0B0B-4BBD-9DF3-825804BF26AB - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestPersistenceLib - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - - -[Sources] - UnitTestPersistenceLibNull.c - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +## @file UnitTestPersistenceLibNull.inf +# This is an instance of the Unit Test Persistence Lib does nothing. +# +# @copyright +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +# +# +# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibNull + FILE_GUID = B8553C7A-0B0B-4BBD-9DF3-825804BF26AB + VERSION_STRING = 1.0 + MODULE_TYPE = BASE + LIBRARY_CLASS = UnitTestPersistenceLib + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + UnitTestPersistenceLibNull.c + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c index 3d74bc6dcfa..0b1cf98b299 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c @@ -1,210 +1,210 @@ -/** - -Implement UnitTestResultReportLib doing plain txt out to console - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include - -#include -#include -#include - - - -struct _UNIT_TEST_STATUS_STRING -{ - UNIT_TEST_STATUS Status; - CHAR8 *String; -}; - -struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = -{ - { UNIT_TEST_PASSED, "PASSED" }, - { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, - { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, - { UNIT_TEST_RUNNING, "RUNNING" }, - { UNIT_TEST_PENDING, "PENDING" } -}; -UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); -CHAR8 *mUnknownStatus = "**UNKNOWN**"; - -struct _UNIT_TEST_FAILURE_TYPE_STRING -{ - FAILURE_TYPE Type; - CHAR8 *String; -}; - -struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= -{ - { FAILURETYPE_NOFAILURE, "NO FAILURE"}, - { FAILURETYPE_OTHER, "OTHER FAILURE" }, - { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, - { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, - { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, - { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } -}; -UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); -CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; - -//============================================================================= -// -// ---------------- TEST REPORTING FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForUnitTestStatus ( - IN UNIT_TEST_STATUS Status - ) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownStatus; - for (Index = 0; Index < mStatusStringsCount; Index++) - { - if (mStatusStrings[Index].Status == Status) - { - Result = mStatusStrings[Index].String; - break; - } - } - - return Result; -} - -STATIC -CONST CHAR8* -GetStringForFailureType( - IN FAILURE_TYPE Failure -) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownFailureType; - for (Index = 0; Index < mFailureTypeStringsCount; Index++) - { - if (mFailureTypeStrings[Index].Type == Failure) - { - Result = mFailureTypeStrings[Index].String; - break; - } - } - if (Result == mUnknownFailureType) - { - DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); - } - - return Result; -} - -/* -Method to print the Unit Test run results - -@retval Success -*/ -EFI_STATUS -EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - INTN Passed = 0; - INTN Failed = 0; - INTN NotRun = 0; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); - DEBUG((DEBUG_INFO, "------------- UNIT TEST FRAMEWORK RESULTS ---------------\n")); - DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); - - //print the version and time - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - UNIT_TEST_LIST_ENTRY *Test = NULL; - INTN SPassed = 0; - INTN SFailed = 0; - INTN SNotRun = 0; - - DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); - DEBUG((DEBUG_INFO, " SUITE: %a\n", Suite->UTS.Title)); - DEBUG((DEBUG_INFO, " PACKAGE: %a\n", Suite->UTS.Package)); - DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); - - // - // Iterate all tests within the suite - // - for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); - (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); - Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) - { - - DEBUG((DEBUG_INFO, "*********************************************************\n")); - DEBUG((DEBUG_INFO, " CLASS NAME: %a\n", Test->UT.ClassName)); - DEBUG((DEBUG_INFO, " TEST: %a\n", Test->UT.Description)); - DEBUG((DEBUG_INFO, " STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ))); - DEBUG((DEBUG_INFO, " FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType))); - DEBUG((DEBUG_INFO, " FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage)); - - if (Test->UT.Log != NULL) - { - DEBUG((DEBUG_INFO, " LOG:\n")); - // NOTE: This has to be done directly because all of the other - // "formatted" print statements have caps on the string size. - DEBUG((DEBUG_INFO, "%a", Test->UT.Log)); - } - - switch (Test->UT.Result) - { - case UNIT_TEST_PASSED: SPassed++; break; - case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; - case UNIT_TEST_PENDING: // Fall through... - case UNIT_TEST_RUNNING: // Fall through... - case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; - default: break; - } - DEBUG((DEBUG_INFO, "**********************************************************\n")); - } //End Test iteration - - DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); - DEBUG((DEBUG_INFO, "Suite Stats\n")); - DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun))); - DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun))); - DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun))); - DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); - - Passed += SPassed; //add to global counters - Failed += SFailed; //add to global counters - NotRun += SNotRun; //add to global coutners - }//End Suite iteration - - DEBUG((DEBUG_INFO, "=========================================================\n")); - DEBUG((DEBUG_INFO, "Total Stats\n")); - DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, "=========================================================\n")); - - return EFI_SUCCESS; -} \ No newline at end of file +/** + +Implement UnitTestResultReportLib doing plain txt out to console + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include + +#include +#include +#include + + + +struct _UNIT_TEST_STATUS_STRING +{ + UNIT_TEST_STATUS Status; + CHAR8 *String; +}; + +struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = +{ + { UNIT_TEST_PASSED, "PASSED" }, + { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, + { UNIT_TEST_RUNNING, "RUNNING" }, + { UNIT_TEST_PENDING, "PENDING" } +}; +UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); +CHAR8 *mUnknownStatus = "**UNKNOWN**"; + +struct _UNIT_TEST_FAILURE_TYPE_STRING +{ + FAILURE_TYPE Type; + CHAR8 *String; +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= +{ + { FAILURETYPE_NOFAILURE, "NO FAILURE"}, + { FAILURETYPE_OTHER, "OTHER FAILURE" }, + { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, + { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, + { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, + { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } +}; +UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); +CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; + +//============================================================================= +// +// ---------------- TEST REPORTING FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForUnitTestStatus ( + IN UNIT_TEST_STATUS Status + ) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownStatus; + for (Index = 0; Index < mStatusStringsCount; Index++) + { + if (mStatusStrings[Index].Status == Status) + { + Result = mStatusStrings[Index].String; + break; + } + } + + return Result; +} + +STATIC +CONST CHAR8* +GetStringForFailureType( + IN FAILURE_TYPE Failure +) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownFailureType; + for (Index = 0; Index < mFailureTypeStringsCount; Index++) + { + if (mFailureTypeStrings[Index].Type == Failure) + { + Result = mFailureTypeStrings[Index].String; + break; + } + } + if (Result == mUnknownFailureType) + { + DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + } + + return Result; +} + +/* +Method to print the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + INTN Passed = 0; + INTN Failed = 0; + INTN NotRun = 0; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); + DEBUG((DEBUG_INFO, "------------- UNIT TEST FRAMEWORK RESULTS ---------------\n")); + DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); + + //print the version and time + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + UNIT_TEST_LIST_ENTRY *Test = NULL; + INTN SPassed = 0; + INTN SFailed = 0; + INTN SNotRun = 0; + + DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); + DEBUG((DEBUG_INFO, " SUITE: %a\n", Suite->UTS.Title)); + DEBUG((DEBUG_INFO, " PACKAGE: %a\n", Suite->UTS.Package)); + DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); + + // + // Iterate all tests within the suite + // + for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); + (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); + Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) + { + + DEBUG((DEBUG_INFO, "*********************************************************\n")); + DEBUG((DEBUG_INFO, " CLASS NAME: %a\n", Test->UT.ClassName)); + DEBUG((DEBUG_INFO, " TEST: %a\n", Test->UT.Description)); + DEBUG((DEBUG_INFO, " STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ))); + DEBUG((DEBUG_INFO, " FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType))); + DEBUG((DEBUG_INFO, " FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage)); + + if (Test->UT.Log != NULL) + { + DEBUG((DEBUG_INFO, " LOG:\n")); + // NOTE: This has to be done directly because all of the other + // "formatted" print statements have caps on the string size. + DEBUG((DEBUG_INFO, "%a", Test->UT.Log)); + } + + switch (Test->UT.Result) + { + case UNIT_TEST_PASSED: SPassed++; break; + case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; + case UNIT_TEST_PENDING: // Fall through... + case UNIT_TEST_RUNNING: // Fall through... + case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; + default: break; + } + DEBUG((DEBUG_INFO, "**********************************************************\n")); + } //End Test iteration + + DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); + DEBUG((DEBUG_INFO, "Suite Stats\n")); + DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun))); + DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun))); + DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun))); + DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); + + Passed += SPassed; //add to global counters + Failed += SFailed; //add to global counters + NotRun += SNotRun; //add to global coutners + }//End Suite iteration + + DEBUG((DEBUG_INFO, "=========================================================\n")); + DEBUG((DEBUG_INFO, "Total Stats\n")); + DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun))); + DEBUG((DEBUG_INFO, "=========================================================\n")); + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf index 644c6032a08..a0215630e37 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf +++ b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf @@ -1,34 +1,34 @@ -## @file -# Library to support printing out the unit test report using printlib and conout -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestResultReportLibDebug -FILE_GUID = BED736D4-D197-475F-B7CE-0D828FF2C9A6 -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestResultReportLib - -[LibraryClasses] - DebugLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestResultReportLibDebug.c +## @file +# Library to support printing out the unit test report using printlib and conout +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestResultReportLibDebug +FILE_GUID = BED736D4-D197-475F-B7CE-0D828FF2C9A6 +VERSION_STRING = 1.0 +MODULE_TYPE = BASE +LIBRARY_CLASS = UnitTestResultReportLib + +[LibraryClasses] + DebugLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c index d1fc9cccb9e..7a18df0919c 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -1,112 +1,112 @@ -/** - -Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should -work on all platforms - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include -#include -#include - -EFI_STATUS -EFIAPI -SetBootNextDevice( - VOID -) -{ - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION NewOption; - UINT32 Attributes; - UINT8 *OptionalData = NULL; - UINT32 OptionalDataSize = 0; - UINT16 BootNextValue = 0xABCD; // this should be a safe number... - USB_CLASS_DEVICE_PATH UsbDp; - EFI_DEVICE_PATH_PROTOCOL *DpEnd = NULL; - EFI_DEVICE_PATH_PROTOCOL *Dp = NULL; - BOOLEAN NewOptionValid = FALSE; - - UsbDp.Header.Length[0] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) & 0xff); - UsbDp.Header.Length[1] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) >> 8); - UsbDp.Header.Type = MESSAGING_DEVICE_PATH; - UsbDp.Header.SubType = MSG_USB_CLASS_DP; - UsbDp.VendorId = 0xFFFF; - UsbDp.ProductId = 0xFFFF; - UsbDp.DeviceClass = 0xFF; - UsbDp.DeviceSubClass = 0xFF; - UsbDp.DeviceProtocol = 0xFF; - - Attributes = LOAD_OPTION_ACTIVE; - - DpEnd = AppendDevicePathNode(NULL, NULL); - if (DpEnd == NULL) - { - DEBUG((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); - Status = EFI_OUT_OF_RESOURCES; - goto CLEANUP; - } - - Dp = AppendDevicePathNode(DpEnd, (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp); //@MRT --- Is this memory leak becasue we lose the old Dp memory - if (Dp == NULL) - { - DEBUG((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); - Status = EFI_OUT_OF_RESOURCES; - goto CLEANUP; - } - - Status = EfiBootManagerInitializeLoadOption( - &NewOption, - (UINTN) BootNextValue, - LoadOptionTypeBoot, - Attributes, - L"Generic USB Class Device", - Dp, - OptionalData, - OptionalDataSize - ); - - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); - goto CLEANUP; - } - - NewOptionValid = TRUE; - DEBUG((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); - Status = EfiBootManagerLoadOptionToVariable(&NewOption); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); - goto CLEANUP; - } - - //Set Boot Next - Status = gRT->SetVariable(L"BootNext", - &gEfiGlobalVariableGuid, - (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE), - sizeof(BootNextValue), - &(BootNextValue)); - - DEBUG((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); - -CLEANUP: - if (Dp != NULL) - { - FreePool(Dp); - } - - if (DpEnd != NULL) - { - FreePool(DpEnd); - } - - if (NewOptionValid) - { - EfiBootManagerFreeLoadOption(&NewOption); - } - - return Status; -} \ No newline at end of file +/** + +Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should +work on all platforms + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include + +EFI_STATUS +EFIAPI +SetBootNextDevice( + VOID +) +{ + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION NewOption; + UINT32 Attributes; + UINT8 *OptionalData = NULL; + UINT32 OptionalDataSize = 0; + UINT16 BootNextValue = 0xABCD; // this should be a safe number... + USB_CLASS_DEVICE_PATH UsbDp; + EFI_DEVICE_PATH_PROTOCOL *DpEnd = NULL; + EFI_DEVICE_PATH_PROTOCOL *Dp = NULL; + BOOLEAN NewOptionValid = FALSE; + + UsbDp.Header.Length[0] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) & 0xff); + UsbDp.Header.Length[1] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) >> 8); + UsbDp.Header.Type = MESSAGING_DEVICE_PATH; + UsbDp.Header.SubType = MSG_USB_CLASS_DP; + UsbDp.VendorId = 0xFFFF; + UsbDp.ProductId = 0xFFFF; + UsbDp.DeviceClass = 0xFF; + UsbDp.DeviceSubClass = 0xFF; + UsbDp.DeviceProtocol = 0xFF; + + Attributes = LOAD_OPTION_ACTIVE; + + DpEnd = AppendDevicePathNode(NULL, NULL); + if (DpEnd == NULL) + { + DEBUG((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + Dp = AppendDevicePathNode(DpEnd, (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp); //@MRT --- Is this memory leak becasue we lose the old Dp memory + if (Dp == NULL) + { + DEBUG((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + Status = EfiBootManagerInitializeLoadOption( + &NewOption, + (UINTN) BootNextValue, + LoadOptionTypeBoot, + Attributes, + L"Generic USB Class Device", + Dp, + OptionalData, + OptionalDataSize + ); + + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + NewOptionValid = TRUE; + DEBUG((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); + Status = EfiBootManagerLoadOptionToVariable(&NewOption); + if (EFI_ERROR(Status)) { + DEBUG((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + //Set Boot Next + Status = gRT->SetVariable(L"BootNext", + &gEfiGlobalVariableGuid, + (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE), + sizeof(BootNextValue), + &(BootNextValue)); + + DEBUG((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); + +CLEANUP: + if (Dp != NULL) + { + FreePool(Dp); + } + + if (DpEnd != NULL) + { + FreePool(DpEnd); + } + + if (NewOptionValid) + { + EfiBootManagerFreeLoadOption(&NewOption); + } + + return Status; +} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index a4932f6e11f..5fb2b8f7829 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -1,42 +1,42 @@ -## @file -# Library to support booting to USB on the next boot -# This instance uses the industry standard usb class boot option. -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestBootLibUsbClass -FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 -VERSION_STRING = 1.0 -MODULE_TYPE = UEFI_APPLICATION -LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION - - -[LibraryClasses] - DebugLib - UefiRuntimeServicesTableLib - MemoryAllocationLib - DevicePathLib - UefiBootManagerLib - - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. - - -[Sources] - UnitTestBootLibUsbClass.c +## @file +# Library to support booting to USB on the next boot +# This instance uses the industry standard usb class boot option. +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestBootLibUsbClass +FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 +VERSION_STRING = 1.0 +MODULE_TYPE = UEFI_APPLICATION +LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + UefiRuntimeServicesTableLib + MemoryAllocationLib + DevicePathLib + UefiBootManagerLib + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. + + +[Sources] + UnitTestBootLibUsbClass.c diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c index 204552e8554..3c4aafb6eaa 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c @@ -1,416 +1,416 @@ -/** @file -- UnitTestPersistenceFilesystemLib.c - -This is an instance of the Unit Test Persistence Lib that will utilize -the filesystem that a test application is running from to save a serialized -version of the internal test state in case the test needs to quit and restore. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include - -/** - TODO: STUFF!! - - @retval !NULL A pointer to the EFI_FILE protocol instance for the filesystem. - @retval NULL Filesystem could not be found or an error occurred. - -**/ -STATIC -EFI_DEVICE_PATH_PROTOCOL* -GetCacheFileDevicePath ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - CHAR16 *AppPath = NULL, *CacheFilePath = NULL; - CHAR16 *TestName = NULL; - CHAR16 *FileSuffix = L"_Cache.dat"; - UINTN DirectorySlashOffset, CacheFilePathLength; - EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath = NULL; - - // - // First, we need to get some information from the loaded image. - // Namely, where the hell are you? - // - Status = gBS->HandleProtocol( gImageHandle, - &gEfiLoadedImageProtocolGuid, - (VOID**)&LoadedImage ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status )); - return NULL; - } - - // Before we can start, we should change our test name from ASCII to Unicode. - CacheFilePathLength = AsciiStrLen( Framework->ShortTitle ) + 1; - TestName = AllocatePool( CacheFilePathLength ); - if (!TestName) { - goto Exit; - } - AsciiStrToUnicodeStrS( Framework->ShortTitle, TestName, CacheFilePathLength ); - - // - // Now we should have the device path of the root device and a file path for the rest. - // In order to target the directory for the test application, we must process - // the file path a little. - // - // NOTE: This may not be necessary... Path processing functions exist... - // PathCleanUpDirectories (FileNameCopy); - // if (PathRemoveLastItem (FileNameCopy)) { - AppPath = ConvertDevicePathToText( LoadedImage->FilePath, TRUE, TRUE ); // NOTE: This must be freed. - DirectorySlashOffset = StrLen( AppPath ); - // Make sure we didn't get any weird data. - if (DirectorySlashOffset == 0) - { - DEBUG(( DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__ )); - goto Exit; - } - // Now that we know we have a decent string, let's take a deeper look. - do - { - if (AppPath[DirectorySlashOffset] == L'\\') - { - break; - } - DirectorySlashOffset--; - } while (DirectorySlashOffset > 0); - - // - // After that little maneuver, DirectorySlashOffset should be pointing at the last '\' in AppString. - // That would be the path to the parent directory that the test app is executing from. - // Let's check and make sure that's right. - // - if (AppPath[DirectorySlashOffset] != L'\\') - { - DEBUG(( DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__ )); - goto Exit; - } - - // - // Now we know some things, we're ready to produce our output string, I think. - // - CacheFilePathLength = DirectorySlashOffset + 1; - CacheFilePathLength += StrLen( TestName ); - CacheFilePathLength += StrLen( FileSuffix ); - CacheFilePathLength += 1; // Don't forget the NULL terminator. - CacheFilePath = AllocateZeroPool( CacheFilePathLength * sizeof( CHAR16 ) ); - if (!CacheFilePath) { - goto Exit; - } - - // - // Let's produce our final path string, shall we? - // - StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. - StrCatS( CacheFilePath, CacheFilePathLength, TestName ); // Copy the base name for the test cache. - StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. - - // - // Finally, try to create the device path for the thing thing. - // - CacheFileDevicePath = FileDevicePath( LoadedImage->DeviceHandle, CacheFilePath ); - -Exit: - // Always put away your toys. - if (AppPath != NULL) - { - FreePool( AppPath ); - } - if (CacheFilePath != NULL) - { - FreePool( CacheFilePath); - } - if (TestName != NULL) - { - FreePool( TestName); - } - - return CacheFileDevicePath; -} // GetCacheFileDevicePath() - - -/** - Determines whether a persistence cache already exists for - the given framework. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - - @retval TRUE - @retval FALSE Cache doesn't exist or an error occurred. - -**/ -BOOLEAN -EFIAPI -DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - EFI_STATUS Status; - SHELL_FILE_HANDLE FileHandle; - - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // Check to see whether the file exists. - // If the file can be opened for reading, it exists. - // Otherwise, probably not. - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - EFI_FILE_MODE_READ, - 0 ); - if (!EFI_ERROR( Status )) - { - ShellCloseFile( &FileHandle ); - } - - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - - DEBUG(( DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR( Status ) )); - - return !EFI_ERROR( Status ); -} // DoesCacheExist() - - -/** - Will save the data associated with an internal Unit Test Framework - state in a manner that can persist a Unit Test Application quit or - even a system reboot. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer to the buffer containing the serialized - framework internal state. - - @retval EFI_SUCCESS Data is persisted and the test can be safely quit. - @retval Others Data is not persisted and test cannot be resumed upon exit. - -**/ -EFI_STATUS -EFIAPI -SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData - ) -{ - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - EFI_STATUS Status; - SHELL_FILE_HANDLE FileHandle; - UINTN WriteCount; - - // - // Check the inputs for sanity. - if (FrameworkHandle == NULL || SaveData == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Determine the path for the cache file. - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // - //First lets open the file if it exists so we can delete it...This is the work around for truncation - // - Status = ShellOpenFileByDevicePath(&FileDevicePath, - &FileHandle, - (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE), - 0); - - if (!EFI_ERROR(Status)) - { - //if file handle above was opened it will be closed by the delete. - Status = ShellDeleteFile(&FileHandle); - if (EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); - } - } - - // - // Now that we know the path to the file... let's open it for writing. - // - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE), - 0 ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); - goto Exit; - } - - // - // Write the data to the file. - // - WriteCount = SaveData->SaveStateSize; - DEBUG(( DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount )); - Status = ShellWriteFile( FileHandle, - &WriteCount, - SaveData ); - - if (EFI_ERROR( Status ) || WriteCount != SaveData->SaveStateSize) - { - DEBUG(( DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status )); - } - else - { - DEBUG(( DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__ )); - } - - // - // No matter what, we should probably close the file. - // - ShellCloseFile( &FileHandle ); - -Exit: - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - - return Status; -} // SaveUnitTestCache() - - -/** - Will retrieve any cached state associated with the given framework. - Will allocate a buffer to hold the loaded data. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address - of the loaded data buffer. - - @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated - with a pointer to the buffer. - @retval Others An error has occurred and no data has been loaded. SaveData - is set to NULL. - -**/ -EFI_STATUS -EFIAPI -LoadUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData - ) -{ - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - SHELL_FILE_HANDLE FileHandle; - BOOLEAN IsFileOpened = FALSE; - UINT64 LargeFileSize; - UINTN FileSize; - UNIT_TEST_SAVE_HEADER *Buffer = NULL; - - // - // Check the inputs for sanity. - if (FrameworkHandle == NULL || SaveData == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Determine the path for the cache file. - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // - // Now that we know the path to the file... let's open it for writing. - // - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - EFI_FILE_MODE_READ, - 0 ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); - goto Exit; - } - else - { - IsFileOpened = TRUE; - } - - // - // Now that the file is opened, we need to determine how large a buffer we need. - Status = ShellGetFileSize( FileHandle, &LargeFileSize ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status )); - goto Exit; - } - - // - // Now that we know the size, let's allocated a buffer to hold the contents. - FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. - Buffer = AllocatePool( FileSize ); - if (Buffer == NULL) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status )); - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Finally, let's read the bloody data. - Status = ShellReadFile( FileHandle, &FileSize, Buffer ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status )); - } - -Exit: - // - // Always put away your toys. - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - if (IsFileOpened) - { - ShellCloseFile( &FileHandle ); - } - - // - // If we're returning an error, make sure - // the state is sane. - if (EFI_ERROR( Status ) && Buffer != NULL) - { - FreePool( Buffer ); - Buffer = NULL; - } - - *SaveData = Buffer; - return Status; -} // LoadUnitTestCache() +/** @file -- UnitTestPersistenceFilesystemLib.c + +This is an instance of the Unit Test Persistence Lib that will utilize +the filesystem that a test application is running from to save a serialized +version of the internal test state in case the test needs to quit and restore. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ +#include +#include +#include +#include +#include +#include +#include + +#include + +#include +#include +#include + +/** + TODO: STUFF!! + + @retval !NULL A pointer to the EFI_FILE protocol instance for the filesystem. + @retval NULL Filesystem could not be found or an error occurred. + +**/ +STATIC +EFI_DEVICE_PATH_PROTOCOL* +GetCacheFileDevicePath ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + CHAR16 *AppPath = NULL, *CacheFilePath = NULL; + CHAR16 *TestName = NULL; + CHAR16 *FileSuffix = L"_Cache.dat"; + UINTN DirectorySlashOffset, CacheFilePathLength; + EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath = NULL; + + // + // First, we need to get some information from the loaded image. + // Namely, where the hell are you? + // + Status = gBS->HandleProtocol( gImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID**)&LoadedImage ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status )); + return NULL; + } + + // Before we can start, we should change our test name from ASCII to Unicode. + CacheFilePathLength = AsciiStrLen( Framework->ShortTitle ) + 1; + TestName = AllocatePool( CacheFilePathLength ); + if (!TestName) { + goto Exit; + } + AsciiStrToUnicodeStrS( Framework->ShortTitle, TestName, CacheFilePathLength ); + + // + // Now we should have the device path of the root device and a file path for the rest. + // In order to target the directory for the test application, we must process + // the file path a little. + // + // NOTE: This may not be necessary... Path processing functions exist... + // PathCleanUpDirectories (FileNameCopy); + // if (PathRemoveLastItem (FileNameCopy)) { + AppPath = ConvertDevicePathToText( LoadedImage->FilePath, TRUE, TRUE ); // NOTE: This must be freed. + DirectorySlashOffset = StrLen( AppPath ); + // Make sure we didn't get any weird data. + if (DirectorySlashOffset == 0) + { + DEBUG(( DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__ )); + goto Exit; + } + // Now that we know we have a decent string, let's take a deeper look. + do + { + if (AppPath[DirectorySlashOffset] == L'\\') + { + break; + } + DirectorySlashOffset--; + } while (DirectorySlashOffset > 0); + + // + // After that little maneuver, DirectorySlashOffset should be pointing at the last '\' in AppString. + // That would be the path to the parent directory that the test app is executing from. + // Let's check and make sure that's right. + // + if (AppPath[DirectorySlashOffset] != L'\\') + { + DEBUG(( DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__ )); + goto Exit; + } + + // + // Now we know some things, we're ready to produce our output string, I think. + // + CacheFilePathLength = DirectorySlashOffset + 1; + CacheFilePathLength += StrLen( TestName ); + CacheFilePathLength += StrLen( FileSuffix ); + CacheFilePathLength += 1; // Don't forget the NULL terminator. + CacheFilePath = AllocateZeroPool( CacheFilePathLength * sizeof( CHAR16 ) ); + if (!CacheFilePath) { + goto Exit; + } + + // + // Let's produce our final path string, shall we? + // + StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. + StrCatS( CacheFilePath, CacheFilePathLength, TestName ); // Copy the base name for the test cache. + StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. + + // + // Finally, try to create the device path for the thing thing. + // + CacheFileDevicePath = FileDevicePath( LoadedImage->DeviceHandle, CacheFilePath ); + +Exit: + // Always put away your toys. + if (AppPath != NULL) + { + FreePool( AppPath ); + } + if (CacheFilePath != NULL) + { + FreePool( CacheFilePath); + } + if (TestName != NULL) + { + FreePool( TestName); + } + + return CacheFileDevicePath; +} // GetCacheFileDevicePath() + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // Check to see whether the file exists. + // If the file can be opened for reading, it exists. + // Otherwise, probably not. + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 ); + if (!EFI_ERROR( Status )) + { + ShellCloseFile( &FileHandle ); + } + + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + + DEBUG(( DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR( Status ) )); + + return !EFI_ERROR( Status ); +} // DoesCacheExist() + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + UINTN WriteCount; + + // + // Check the inputs for sanity. + if (FrameworkHandle == NULL || SaveData == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // + //First lets open the file if it exists so we can delete it...This is the work around for truncation + // + Status = ShellOpenFileByDevicePath(&FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE), + 0); + + if (!EFI_ERROR(Status)) + { + //if file handle above was opened it will be closed by the delete. + Status = ShellDeleteFile(&FileHandle); + if (EFI_ERROR(Status)) + { + DEBUG((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); + } + } + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE), + 0 ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); + goto Exit; + } + + // + // Write the data to the file. + // + WriteCount = SaveData->SaveStateSize; + DEBUG(( DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount )); + Status = ShellWriteFile( FileHandle, + &WriteCount, + SaveData ); + + if (EFI_ERROR( Status ) || WriteCount != SaveData->SaveStateSize) + { + DEBUG(( DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status )); + } + else + { + DEBUG(( DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__ )); + } + + // + // No matter what, we should probably close the file. + // + ShellCloseFile( &FileHandle ); + +Exit: + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + + return Status; +} // SaveUnitTestCache() + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + SHELL_FILE_HANDLE FileHandle; + BOOLEAN IsFileOpened = FALSE; + UINT64 LargeFileSize; + UINTN FileSize; + UNIT_TEST_SAVE_HEADER *Buffer = NULL; + + // + // Check the inputs for sanity. + if (FrameworkHandle == NULL || SaveData == NULL) + { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath( &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); + goto Exit; + } + else + { + IsFileOpened = TRUE; + } + + // + // Now that the file is opened, we need to determine how large a buffer we need. + Status = ShellGetFileSize( FileHandle, &LargeFileSize ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status )); + goto Exit; + } + + // + // Now that we know the size, let's allocated a buffer to hold the contents. + FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. + Buffer = AllocatePool( FileSize ); + if (Buffer == NULL) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status )); + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Finally, let's read the bloody data. + Status = ShellReadFile( FileHandle, &FileSize, Buffer ); + if (EFI_ERROR( Status )) + { + DEBUG(( DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status )); + } + +Exit: + // + // Always put away your toys. + if (FileDevicePath != NULL) + { + FreePool( FileDevicePath ); + } + if (IsFileOpened) + { + ShellCloseFile( &FileHandle ); + } + + // + // If we're returning an error, make sure + // the state is sane. + if (EFI_ERROR( Status ) && Buffer != NULL) + { + FreePool( Buffer ); + Buffer = NULL; + } + + *SaveData = Buffer; + return Status; +} // LoadUnitTestCache() diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf index 0b57b61fd84..acd37f7227c 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf @@ -1,64 +1,64 @@ -## @file UnitTestPersistenceLibFileSystem.inf -# This is an instance of the Unit Test Persistence Lib that will utilize -# the filesystem that a test application is running from to save a serialized -# version of the internal test state in case the test needs to quit and restore. -# -# @copyright -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -# THE POSSIBILITY OF SUCH DAMAGE. -# -# -# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. -# -## - - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestPersistenceLibFileSystem - FILE_GUID = 9200844A-CDFD-4368-B4BD-106354702605 - VERSION_STRING = 1.0 - MODULE_TYPE = UEFI_APPLICATION - LIBRARY_CLASS = UnitTestPersistenceLib|UEFI_APPLICATION - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - - -[Sources] - UnitTestPersistenceLibFileSystem.c - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - ShellPkg/ShellPkg.dec - - -[LibraryClasses] - DebugLib - UefiBootServicesTableLib - BaseLib - ShellLib - - -[Protocols] - gEfiLoadedImageProtocolGuid - gEfiSimpleFileSystemProtocolGuid - - -[Guids] - gEfiFileInfoGuid - gEfiFileSystemInfoGuid +## @file UnitTestPersistenceLibFileSystem.inf +# This is an instance of the Unit Test Persistence Lib that will utilize +# the filesystem that a test application is running from to save a serialized +# version of the internal test state in case the test needs to quit and restore. +# +# @copyright +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +# THE POSSIBILITY OF SUCH DAMAGE. +# +# +# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# +## + + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibFileSystem + FILE_GUID = 9200844A-CDFD-4368-B4BD-106354702605 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_APPLICATION + LIBRARY_CLASS = UnitTestPersistenceLib|UEFI_APPLICATION + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + + +[Sources] + UnitTestPersistenceLibFileSystem.c + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + ShellPkg/ShellPkg.dec + + +[LibraryClasses] + DebugLib + UefiBootServicesTableLib + BaseLib + ShellLib + + +[Protocols] + gEfiLoadedImageProtocolGuid + gEfiSimpleFileSystemProtocolGuid + + +[Guids] + gEfiFileInfoGuid + gEfiFileSystemInfoGuid diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c index 33d37c4fbcb..15410c203bf 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c @@ -1,227 +1,227 @@ -/** - -Implement UnitTestResultReportLib doing plain txt out to console - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include - -#include -#include -#include - - - -struct _UNIT_TEST_STATUS_STRING -{ - UNIT_TEST_STATUS Status; - CHAR8 *String; -}; - -struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = -{ - { UNIT_TEST_PASSED, "PASSED" }, - { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, - { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, - { UNIT_TEST_RUNNING, "RUNNING" }, - { UNIT_TEST_PENDING, "PENDING" } -}; -UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); -CHAR8 *mUnknownStatus = "**UNKNOWN**"; - -struct _UNIT_TEST_FAILURE_TYPE_STRING -{ - FAILURE_TYPE Type; - CHAR8 *String; -}; - -struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= -{ - { FAILURETYPE_NOFAILURE, "NO FAILURE"}, - { FAILURETYPE_OTHER, "OTHER FAILURE" }, - { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, - { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, - { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, - { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } -}; -UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); -CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; - -//============================================================================= -// -// ---------------- TEST REPORTING FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForUnitTestStatus ( - IN UNIT_TEST_STATUS Status - ) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownStatus; - for (Index = 0; Index < mStatusStringsCount; Index++) - { - if (mStatusStrings[Index].Status == Status) - { - Result = mStatusStrings[Index].String; - break; - } - } - - return Result; -} - -STATIC -CONST CHAR8* -GetStringForFailureType( - IN FAILURE_TYPE Failure -) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownFailureType; - for (Index = 0; Index < mFailureTypeStringsCount; Index++) - { - if (mFailureTypeStrings[Index].Type == Failure) - { - Result = mFailureTypeStrings[Index].String; - break; - } - } - if (Result == mUnknownFailureType) - { - DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); - } - - return Result; -} - -/* -Method to print the Unit Test run results - -@retval Success -*/ -EFI_STATUS -EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - INTN Passed = 0; - INTN Failed = 0; - INTN NotRun = 0; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - UINT16 *LogString = NULL; - UINTN LogStringLength = 0; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - Print( L"---------------------------------------------------------\n" ); - Print( L"------------- UNIT TEST FRAMEWORK RESULTS ---------------\n" ); - Print( L"---------------------------------------------------------\n" ); - - //print the version and time - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - UNIT_TEST_LIST_ENTRY *Test = NULL; - INTN SPassed = 0; - INTN SFailed = 0; - INTN SNotRun = 0; - - Print( L"/////////////////////////////////////////////////////////\n" ); - Print( L" SUITE: %a\n", Suite->UTS.Title ); - Print( L" PACKAGE: %a\n", Suite->UTS.Package); - Print( L"/////////////////////////////////////////////////////////\n" ); - - // - // Iterate all tests within the suite - // - for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); - (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); - Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) - { - - Print (L"*********************************************************\n" ); - Print (L" CLASS NAME: %a\n", Test->UT.ClassName); - Print( L" TEST: %a\n", Test->UT.Description ); - Print( L" STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ) ); - Print( L" FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType)); - Print( L" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); - - if (Test->UT.Log != NULL) - { - // Make sure that we can expand the string into the unicode buffer. - if (LogStringLength <= AsciiStrnLenS( Test->UT.Log, MAX_UINT32 )) { - LogStringLength = AsciiStrnLenS( Test->UT.Log, MAX_UINT32 ) + 1; - if (LogString) { - FreePool( LogString ); - } - LogString = AllocatePool( LogStringLength * sizeof(CHAR16) ); - } - AsciiStrToUnicodeStrS( Test->UT.Log, LogString, LogStringLength ); - - Print( L" LOG:\n" ); - // NOTE: This has to be done directly because all of the other - // "formatted" print statements have caps on the string size. - gST->ConOut->OutputString( gST->ConOut, LogString ); - } - - switch (Test->UT.Result) - { - case UNIT_TEST_PASSED: SPassed++; break; - case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; - case UNIT_TEST_PENDING: // Fall through... - case UNIT_TEST_RUNNING: // Fall through... - case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; - default: break; - } - Print( L"**********************************************************\n" ); - } //End Test iteration - - Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); - Print( L"Suite Stats\n" ); - Print( L" Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun) ); - Print( L" Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun) ); - Print( L" Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun) ); - Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); - - Passed += SPassed; //add to global counters - Failed += SFailed; //add to global counters - NotRun += SNotRun; //add to global coutners - }//End Suite iteration - - Print( L"=========================================================\n" ); - Print( L"Total Stats\n" ); - Print( L" Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun) ); - Print( L" Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun) ); - Print( L" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun) ); - Print( L"=========================================================\n" ); - - if (LogString) { - FreePool( LogString ); - } - - return EFI_SUCCESS; -} \ No newline at end of file +/** + +Implement UnitTestResultReportLib doing plain txt out to console + +Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include + +#include +#include +#include + + + +struct _UNIT_TEST_STATUS_STRING +{ + UNIT_TEST_STATUS Status; + CHAR8 *String; +}; + +struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = +{ + { UNIT_TEST_PASSED, "PASSED" }, + { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, + { UNIT_TEST_RUNNING, "RUNNING" }, + { UNIT_TEST_PENDING, "PENDING" } +}; +UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); +CHAR8 *mUnknownStatus = "**UNKNOWN**"; + +struct _UNIT_TEST_FAILURE_TYPE_STRING +{ + FAILURE_TYPE Type; + CHAR8 *String; +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= +{ + { FAILURETYPE_NOFAILURE, "NO FAILURE"}, + { FAILURETYPE_OTHER, "OTHER FAILURE" }, + { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, + { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, + { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, + { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } +}; +UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); +CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; + +//============================================================================= +// +// ---------------- TEST REPORTING FUNCTIONS --------------------------------- +// +//============================================================================= + +STATIC +CONST CHAR8* +GetStringForUnitTestStatus ( + IN UNIT_TEST_STATUS Status + ) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownStatus; + for (Index = 0; Index < mStatusStringsCount; Index++) + { + if (mStatusStrings[Index].Status == Status) + { + Result = mStatusStrings[Index].String; + break; + } + } + + return Result; +} + +STATIC +CONST CHAR8* +GetStringForFailureType( + IN FAILURE_TYPE Failure +) +{ + UINTN Index; + CHAR8 *Result; + + Result = mUnknownFailureType; + for (Index = 0; Index < mFailureTypeStringsCount; Index++) + { + if (mFailureTypeStrings[Index].Type == Failure) + { + Result = mFailureTypeStrings[Index].String; + break; + } + } + if (Result == mUnknownFailureType) + { + DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + } + + return Result; +} + +/* +Method to print the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + INTN Passed = 0; + INTN Failed = 0; + INTN NotRun = 0; + UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; + UINT16 *LogString = NULL; + UINTN LogStringLength = 0; + + if (Framework == NULL) + { + return EFI_INVALID_PARAMETER; + } + + Print( L"---------------------------------------------------------\n" ); + Print( L"------------- UNIT TEST FRAMEWORK RESULTS ---------------\n" ); + Print( L"---------------------------------------------------------\n" ); + + //print the version and time + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) + { + UNIT_TEST_LIST_ENTRY *Test = NULL; + INTN SPassed = 0; + INTN SFailed = 0; + INTN SNotRun = 0; + + Print( L"/////////////////////////////////////////////////////////\n" ); + Print( L" SUITE: %a\n", Suite->UTS.Title ); + Print( L" PACKAGE: %a\n", Suite->UTS.Package); + Print( L"/////////////////////////////////////////////////////////\n" ); + + // + // Iterate all tests within the suite + // + for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); + (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); + Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) + { + + Print (L"*********************************************************\n" ); + Print (L" CLASS NAME: %a\n", Test->UT.ClassName); + Print( L" TEST: %a\n", Test->UT.Description ); + Print( L" STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ) ); + Print( L" FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType)); + Print( L" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); + + if (Test->UT.Log != NULL) + { + // Make sure that we can expand the string into the unicode buffer. + if (LogStringLength <= AsciiStrnLenS( Test->UT.Log, MAX_UINT32 )) { + LogStringLength = AsciiStrnLenS( Test->UT.Log, MAX_UINT32 ) + 1; + if (LogString) { + FreePool( LogString ); + } + LogString = AllocatePool( LogStringLength * sizeof(CHAR16) ); + } + AsciiStrToUnicodeStrS( Test->UT.Log, LogString, LogStringLength ); + + Print( L" LOG:\n" ); + // NOTE: This has to be done directly because all of the other + // "formatted" print statements have caps on the string size. + gST->ConOut->OutputString( gST->ConOut, LogString ); + } + + switch (Test->UT.Result) + { + case UNIT_TEST_PASSED: SPassed++; break; + case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; + case UNIT_TEST_PENDING: // Fall through... + case UNIT_TEST_RUNNING: // Fall through... + case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; + default: break; + } + Print( L"**********************************************************\n" ); + } //End Test iteration + + Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); + Print( L"Suite Stats\n" ); + Print( L" Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun) ); + Print( L" Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun) ); + Print( L" Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun) ); + Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); + + Passed += SPassed; //add to global counters + Failed += SFailed; //add to global counters + NotRun += SNotRun; //add to global coutners + }//End Suite iteration + + Print( L"=========================================================\n" ); + Print( L"Total Stats\n" ); + Print( L" Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun) ); + Print( L" Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun) ); + Print( L" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun) ); + Print( L"=========================================================\n" ); + + if (LogString) { + FreePool( LogString ); + } + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf index 12a00f63814..6620f85f296 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf +++ b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf @@ -1,37 +1,37 @@ -## @file -# Library to support printing out the unit test report using printlib and conout -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestResultReportLibPlainTextOutput -FILE_GUID = C659641D-BA1F-4B58-946E-B1E1103903F9 -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestResultReportLib|DXE_DRIVER UEFI_APPLICATION - - -[LibraryClasses] - DebugLib - UefiLib - UefiBootServicesTableLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestResultReportLibPlainTextOutput.c +## @file +# Library to support printing out the unit test report using printlib and conout +# +# +# @copyright +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +# @par Specification Reference: +# +## + + +[Defines] +INF_VERSION = 0x00010017 +BASE_NAME = UnitTestResultReportLibPlainTextOutput +FILE_GUID = C659641D-BA1F-4B58-946E-B1E1103903F9 +VERSION_STRING = 1.0 +MODULE_TYPE = DXE_DRIVER +LIBRARY_CLASS = UnitTestResultReportLib|DXE_DRIVER UEFI_APPLICATION + + +[LibraryClasses] + DebugLib + UefiLib + UefiBootServicesTableLib + + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[Guids] + + +[Sources] + UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h index 133456b2045..a65b0506be5 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h @@ -1,25 +1,25 @@ -/** @file - Provides a library function that can be customized to set the platform to boot from USB on the next boot. - This allows the test framework to reboot back to USB. Since boot managers are not all the same creating a lib to - support platform customization will make porting to new code base/platform easier. - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_BOOT_LIB_H__ -#define __UNIT_TEST_BOOT_LIB_H__ - -/** -Set the boot manager to boot from a specific device on the next boot. -This should be set only for the next boot and shouldn't -require any manual clean up -**/ -EFI_STATUS -EFIAPI -SetBootNextDevice ( VOID ); - - -#endif \ No newline at end of file +/** @file + Provides a library function that can be customized to set the platform to boot from USB on the next boot. + This allows the test framework to reboot back to USB. Since boot managers are not all the same creating a lib to + support platform customization will make porting to new code base/platform easier. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_BOOT_LIB_H__ +#define __UNIT_TEST_BOOT_LIB_H__ + +/** +Set the boot manager to boot from a specific device on the next boot. +This should be set only for the next boot and shouldn't +require any manual clean up +**/ +EFI_STATUS +EFIAPI +SetBootNextDevice ( VOID ); + + +#endif diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h index 27bfb16bc38..fdec8dead59 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h @@ -1,77 +1,77 @@ -/** @file -- UnitTestPersistenceLib.h - This header file describes a library that contains functions to save and - restore unit test internal state, in case the test needs to pause and resume - (eg. a reboot-based test). - - Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef _UNIT_TEST_PERSISTENCE_LIB_H_ -#define _UNIT_TEST_PERSISTENCE_LIB_H_ - -#define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 - - -/** - Determines whether a persistence cache already exists for - the given framework. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - - @retval TRUE - @retval FALSE Cache doesn't exist or an error occurred. - -**/ -BOOLEAN -EFIAPI -DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ); - - -/** - Will save the data associated with an internal Unit Test Framework - state in a manner that can persist a Unit Test Application quit or - even a system reboot. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer to the buffer containing the serialized - framework internal state. - - @retval EFI_SUCCESS Data is persisted and the test can be safely quit. - @retval Others Data is not persisted and test cannot be resumed upon exit. - -**/ -EFI_STATUS -EFIAPI -SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData - ); - - -/** - Will retrieve any cached state associated with the given framework. - Will allocate a buffer to hold the loaded data. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address - of the loaded data buffer. - - @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated - with a pointer to the buffer. - @retval Others An error has occurred and no data has been loaded. SaveData - is set to NULL. - -**/ -EFI_STATUS -EFIAPI -LoadUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData - ); - -#endif // _UNIT_TEST_PERSISTENCE_LIB_H_ +/** @file -- UnitTestPersistenceLib.h + This header file describes a library that contains functions to save and + restore unit test internal state, in case the test needs to pause and resume + (eg. a reboot-based test). + + Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef _UNIT_TEST_PERSISTENCE_LIB_H_ +#define _UNIT_TEST_PERSISTENCE_LIB_H_ + +#define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 + + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ); + + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ); + + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ); + +#endif // _UNIT_TEST_PERSISTENCE_LIB_H_ diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h index 96b5da7eeae..cd12e8831c8 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h @@ -1,25 +1,25 @@ -/** @file - Provides a unit test result report. This allows new result output formats to be easily - customized. - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_RESULT_REPORT_LIB_H__ -#define __UNIT_TEST_RESULT_REPORT_LIB_H__ - -/* -Method to produce the Unit Test run results - -@retval Success -*/ -EFI_STATUS -EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework -); - -#endif \ No newline at end of file +/** @file + Provides a unit test result report. This allows new result output formats to be easily + customized. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_RESULT_REPORT_LIB_H__ +#define __UNIT_TEST_RESULT_REPORT_LIB_H__ + +/* +Method to produce the Unit Test run results + +@retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport( + IN UNIT_TEST_FRAMEWORK *Framework +); + +#endif diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index d161db61aa8..9b1509029f1 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -1,146 +1,146 @@ -/** @file - Provides the basic types and common elements of the unit test framework - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_TYPES_H__ -#define __UNIT_TEST_TYPES_H__ - -///================================================================================================ -///================================================================================================ -/// -/// HANDY DEFINITIONS -/// -///================================================================================================ -///================================================================================================ -#define UNIT_TEST_MAX_STRING_LENGTH (120) - -#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. -#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) - -typedef UINT32 FAILURE_TYPE; -#define FAILURETYPE_NOFAILURE (0) -#define FAILURETYPE_OTHER (1) -#define FAILURETYPE_ASSERTTRUE (2) -#define FAILURETYPE_ASSERTFALSE (3) -#define FAILURETYPE_ASSERTEQUAL (4) -#define FAILURETYPE_ASSERTNOTEQUAL (5) -#define FAILURETYPE_ASSERTNOTEFIERROR (6) -#define FAILURETYPE_ASSERTSTATUSEQUAL (7) -#define FAILURETYPE_ASSERTNOTNULL (8) - - -///================================================================================================ -///================================================================================================ -/// -/// UNIT TEST DATA STRUCTURE DEFINITIONS -/// -///================================================================================================ -///================================================================================================ - -typedef struct { - CHAR8 *Description; - CHAR8 *ClassName; //can't have spaces and should be short - CHAR8 *Log; - FAILURE_TYPE FailureType; - CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; - UNIT_TEST_STATUS Result; - UNIT_TEST_FUNCTION RunTest; - UNIT_TEST_PREREQ PreReq; - UNIT_TEST_CLEANUP CleanUp; - UNIT_TEST_CONTEXT Context; - UNIT_TEST_SUITE_HANDLE ParentSuite; -} UNIT_TEST; - -typedef struct { - LIST_ENTRY Entry; - UNIT_TEST UT; -} UNIT_TEST_LIST_ENTRY; - -typedef struct { - CHAR8 *Title; - CHAR8 *Package; - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; - UNIT_TEST_SUITE_SETUP Setup; - UNIT_TEST_SUITE_TEARDOWN Teardown; - LIST_ENTRY TestCaseList; // UNIT_TEST_LIST_ENTRY - UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; -} UNIT_TEST_SUITE; - -typedef struct { - LIST_ENTRY Entry; - UNIT_TEST_SUITE UTS; -} UNIT_TEST_SUITE_LIST_ENTRY; - -typedef struct { - CHAR8 *Title; - CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. - CHAR8 *VersionString; - CHAR8 *Log; - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; - LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY - EFI_TIME StartTime; - EFI_TIME EndTime; - UNIT_TEST *CurrentTest; - VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. -} UNIT_TEST_FRAMEWORK; - -// -//Structures for the framework to serializing unit test status -// - -typedef struct -{ - UINT32 Size; // Size of the UNIT_TEST_SAVE_TEST including Log[] - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. - CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - FAILURE_TYPE FailureType; - UNIT_TEST_STATUS Result; - CHAR8 Log[]; -} UNIT_TEST_SAVE_TEST; - -typedef struct -{ - UINT32 Size; // Size of the UNIT_TEST_SAVE_CONTEXT including Data[] - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. - UINT8 Data[]; // Actual data of the context. -} UNIT_TEST_SAVE_CONTEXT; - -typedef struct -{ - UINT8 Version; - UINT32 SaveStateSize; // Size of the entire serialized buffer. - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. - EFI_TIME StartTime; - UINT32 TestCount; - BOOLEAN HasSavedContext; - // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. - // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. - // CHAR8 Log[]; // NOTE: Not yet implemented!! -} UNIT_TEST_SAVE_HEADER; - -/** - This function is responsible for initializing the log buffer for a single test. It can - be used internally, but may also be consumed by the test framework to add pre-existing - data to a log before it's used. - - @param[in,out] TestHandle A handle to the test being initialized. - @param[in] Buffer [Optional] A pointer to pre-existing log data that should - be used to initialize the log. Should include a NULL terminator. - @param[in] BufferSize [Optional] The size of the pre-existing log data. - -**/ -VOID -EFIAPI -UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer OPTIONAL, - IN UINTN BufferSize OPTIONAL - ); - -#endif \ No newline at end of file +/** @file + Provides the basic types and common elements of the unit test framework + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_TYPES_H__ +#define __UNIT_TEST_TYPES_H__ + +///================================================================================================ +///================================================================================================ +/// +/// HANDY DEFINITIONS +/// +///================================================================================================ +///================================================================================================ +#define UNIT_TEST_MAX_STRING_LENGTH (120) + +#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. +#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) + +typedef UINT32 FAILURE_TYPE; +#define FAILURETYPE_NOFAILURE (0) +#define FAILURETYPE_OTHER (1) +#define FAILURETYPE_ASSERTTRUE (2) +#define FAILURETYPE_ASSERTFALSE (3) +#define FAILURETYPE_ASSERTEQUAL (4) +#define FAILURETYPE_ASSERTNOTEQUAL (5) +#define FAILURETYPE_ASSERTNOTEFIERROR (6) +#define FAILURETYPE_ASSERTSTATUSEQUAL (7) +#define FAILURETYPE_ASSERTNOTNULL (8) + + +///================================================================================================ +///================================================================================================ +/// +/// UNIT TEST DATA STRUCTURE DEFINITIONS +/// +///================================================================================================ +///================================================================================================ + +typedef struct { + CHAR8 *Description; + CHAR8 *ClassName; //can't have spaces and should be short + CHAR8 *Log; + FAILURE_TYPE FailureType; + CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + UNIT_TEST_STATUS Result; + UNIT_TEST_FUNCTION RunTest; + UNIT_TEST_PREREQ PreReq; + UNIT_TEST_CLEANUP CleanUp; + UNIT_TEST_CONTEXT Context; + UNIT_TEST_SUITE_HANDLE ParentSuite; +} UNIT_TEST; + +typedef struct { + LIST_ENTRY Entry; + UNIT_TEST UT; +} UNIT_TEST_LIST_ENTRY; + +typedef struct { + CHAR8 *Title; + CHAR8 *Package; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + UNIT_TEST_SUITE_SETUP Setup; + UNIT_TEST_SUITE_TEARDOWN Teardown; + LIST_ENTRY TestCaseList; // UNIT_TEST_LIST_ENTRY + UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; +} UNIT_TEST_SUITE; + +typedef struct { + LIST_ENTRY Entry; + UNIT_TEST_SUITE UTS; +} UNIT_TEST_SUITE_LIST_ENTRY; + +typedef struct { + CHAR8 *Title; + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR8 *VersionString; + CHAR8 *Log; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY + EFI_TIME StartTime; + EFI_TIME EndTime; + UNIT_TEST *CurrentTest; + VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. +} UNIT_TEST_FRAMEWORK; + +// +//Structures for the framework to serializing unit test status +// + +typedef struct +{ + UINT32 Size; // Size of the UNIT_TEST_SAVE_TEST including Log[] + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. + CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + FAILURE_TYPE FailureType; + UNIT_TEST_STATUS Result; + CHAR8 Log[]; +} UNIT_TEST_SAVE_TEST; + +typedef struct +{ + UINT32 Size; // Size of the UNIT_TEST_SAVE_CONTEXT including Data[] + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. + UINT8 Data[]; // Actual data of the context. +} UNIT_TEST_SAVE_CONTEXT; + +typedef struct +{ + UINT8 Version; + UINT32 SaveStateSize; // Size of the entire serialized buffer. + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. + EFI_TIME StartTime; + UINT32 TestCount; + BOOLEAN HasSavedContext; + // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. + // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. + // CHAR8 Log[]; // NOTE: Not yet implemented!! +} UNIT_TEST_SAVE_HEADER; + +/** + This function is responsible for initializing the log buffer for a single test. It can + be used internally, but may also be consumed by the test framework to add pre-existing + data to a log before it's used. + + @param[in,out] TestHandle A handle to the test being initialized. + @param[in] Buffer [Optional] A pointer to pre-existing log data that should + be used to initialize the log. Should include a NULL terminator. + @param[in] BufferSize [Optional] The size of the pre-existing log data. + +**/ +VOID +EFIAPI +UnitTestLogInit ( + IN OUT UNIT_TEST_HANDLE TestHandle, + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize OPTIONAL + ); + +#endif diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index abd3cbf295f..2d8b3c76551 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -1,237 +1,237 @@ -# Unit Test Framework Package - -## About - -This package adds a unit test framework capable of building tests for multiple contexts including -the UEFI shell environment and host-based environments. It allows for unit test development to focus -on the tests and leave error logging, result formatting, context persistance, and test running to the framework. -The unit test framework works well for low level unit tests as well as system level tests and -fits easily in automation frameworks. - -The code is designed for a unit test application to leverage the framework which is made -up of a number of libraries which allow for easy customization of the different elements. -A few different instances are created to both show how easy some behaviors can be customized as -well as provide different implementations that support different use cases. - -### UnitTestLib - -The main "framework" library. This provides the framework init, suite init, and add test case -functionality. It also supports the running of the suites and logging/reporting of results. - -### UnitTestAssetLib - -The UnitTestAssetLib provides helper macros and functions for checking test conditions and -reporting errors. Status and error info will be logged into the test context. There are a number -of Assert macros that make the unit test code friendly to view and easy to understand. - -### UnitTestLogLib - -Library to support logging information during the test execution. This data is logged to the test -context and will be available in the test reporting phase. This should be used for logging test -details and helpful messages to resolve test failures. - -### UnitTestPersistenceLib - -Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests -that require exiting the active process and then resuming state can be maintained. This is critical -in supporting a system reboot in the middle of a test run. - -### UnitTestResultReportLib - -Library provides function to run at the end of a framework test run and handles formatting the report. -This is a common customization point and allows the unit test framework to fit its output reports into -other test infrastructure. In this package a simple library instances has been supplied to output test -results to the console as plain text. - -### UnitTestTerminationLib - -Sometimes a given test case will need to exit the test in progress to allow system state to change and -will check for that state change on re-entry. This is most common when a Dxe- or Shell-based test wants to -reboot the system and check for a different system state after reboot. Since the method of exiting rebooting -may vary depending on context (PEI, SMM, DXE, Shell, etc.), this functionality is abstracted. - -## Samples - -There is a sample unit test provided as both an example of how to write a unit test and leverage -many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. - -## Usage - -This section is built a lot like a "Getting Started". We'll go through some of the components that are needed -when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe -how to check for expected conditions in test cases and a bit of the logging characteristics. - -Most of these examples will refer to the SampleUnitTestApp found in this package. - -### Requirements - INF - -In our INF file, we'll need to bring in some libraries. At a bare minimum, we'll need an instance of `UnitTestLib`, -however, since Test Assertions are implemented in their own lib in order to allow for framework flexibility, we -will also have to bring in `UnitTestAssertLib` as well. - -See this example in 'SampleUnitTestApp.inf'... - -``` -[LibraryClasses] - BaseLib - UefiApplicationEntryPoint - DebugLib - UnitTestLib - UnitTestAssertLib - PrintLib -``` - -And in order to bring in the headers we'll need, go ahead and add 'UnitTestPkg/UnitTestPkg.dec' to your -`Packages` list as well. - -### Requirements - Code - -Not to state the obvious, but let's make sure we have the following includes before getting too far along... - -```c -#include -``` - -Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). - -### Configuring the Framework - -Everything in the UnitTestPkg framework is built around an object called -- conveniently -- the Framework. -This Framework object will contain all the information about our test, the test suites and test cases associated -with it, the current location within the test pass, and any results that have been recorded so far. - -To get started with a test, we must first create a Framework instance. The function for this is -`InitUnitTestFramework`. It takes in `CHAR16` strings for the long name, short name, and test version. -The long name and version strings are just for user presentation and relatively flexible. The short name -will be used to name any cache files and/or test results, so should be a name that makes sense in that context. -These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. - -In the 'SampleUnitTestApp', the module name is used as the short name, so the init looks like this. - -```c -DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); - -// -// Start setting up the test framework for running the tests. -// -Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); -``` - -The `&Fw` returned here is the handle to the Framework. If it's successfully returned, we can start adding -test suites and test cases. - -Test suites exist purely to help organize test cases and to differentiate the results in reports. If you're writing -a small unit test, you can conceivably put all test cases into a single suite. However, if you end up with 20+ test -cases, it may be beneficial to organize them according to purpose. You _must_ have at least one test suite, even if -it's just a catch-all. The function to create a test suite is `CreateUnitTestSuite`. It takes in a handle to -the Framework object, a `CHAR16` string for the suite title and package name, and optional function pointers for -a setup function and a teardown function. - -The suite title is for user presentation. The package name is for xUnit type reporting and uses a '.'-separated -hierarchical format (see 'SampleUnitTestApp' for example). If provided, the setup and teardown functions will be -called once at the start of the suite (before _any_ tests have run) and once at the end of the suite (after _all_ -tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are -`UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`. - -Looking at 'SampleUnitTestApp', you can see that the first test suite is created as below... - -```c -// -// Populate the SimpleMathTests Unit Test Suite. -// -Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); -``` - -This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and -will be used when adding test cases. - -Alrighty! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test -to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; -a `CHAR16` string for the description and class name; a function pointer for the test case itself; additional, optional -function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. - -Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in -usage to the suite title and package name strings in the test suites. The former is for user presentation and the -latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the -prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining. - -The prerequisite check function has a prototype of `UNIT_TEST_PREREQ` and -- if provided -- will be called -immediately before the test case. If this function returns any error, the test case will not be run and will be -recorded as `UNIT_TEST_ERROR_PREREQ_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called -immediately after the test case to provide an opportunity to reset any global state that may have been changed in the -test case. In the event of a prerequisite failure, the cleanup function will also be skipped. If either of these -functions is not needed, pass `NULL`. - -The context pointer is entirely case-specific. It will be passed to the test case upon execution. One of the purposes -of the context pointer is to allow test case reuse with different input data. (Another use is for testing that wraps -around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context -pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`. - -In 'SampleUnitTestApp', the first test case is added using the code below... - -```c -AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); -``` - -This test case calls the function `OnePlusOneShouldEqualTwo` and has no prerequisite, cleanup, or context. - -Once all the suites and cases are added, it's time to run the Framework. - -```c -// -// Execute the tests. -// -Status = RunAllTestSuites( Fw ); -``` - -### A Simple Test Case - -We'll take a look at the below test case from 'SampleUnitTestApp'... - -```c -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() -``` - -The prototype for this function matches the `UNIT_TEST_FUNCTION` prototype. It takes in a handle to the Framework -itself and the context pointer. The context pointer could be cast and interpreted as anything within this test case, -which is why it's important to configure contexts carefully. The test case returns a value of `UNIT_TEST_STATUS`, which -will be recorded in the Framework and reported at the end of all suites. - -In this test case, the `UT_ASSERT_EQUAL` assertion is being used to establish that the business logic has functioned -correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your -intended test criterium as possible, because the logging is specific to the macro and more specific macros have more -detailed logs. When in doubt, there are always `UT_ASSERT_TRUE` and `UT_ASSERT_FALSE`. Assertion macros that fail their -test criterium will immediately return from the test case with `UNIT_TEST_ERROR_TEST_FAILED` and log an error string. -_Note_ that this early return can have implications for memory leakage. - -At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. - -## Development - -When using the EDK2 Pytools for CI testing, the host-based unit tests will be built and run on any build that includes the `NOOPT` build target. - -If you are trying to iterate on a single test, a convenient pattern is to build only that test module. For example, the following command will build only the SafeIntLib host-based test from the MdePkg... - -```bash -stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf -``` - -## Copyright - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent +# Unit Test Framework Package + +## About + +This package adds a unit test framework capable of building tests for multiple contexts including +the UEFI shell environment and host-based environments. It allows for unit test development to focus +on the tests and leave error logging, result formatting, context persistance, and test running to the framework. +The unit test framework works well for low level unit tests as well as system level tests and +fits easily in automation frameworks. + +The code is designed for a unit test application to leverage the framework which is made +up of a number of libraries which allow for easy customization of the different elements. +A few different instances are created to both show how easy some behaviors can be customized as +well as provide different implementations that support different use cases. + +### UnitTestLib + +The main "framework" library. This provides the framework init, suite init, and add test case +functionality. It also supports the running of the suites and logging/reporting of results. + +### UnitTestAssetLib + +The UnitTestAssetLib provides helper macros and functions for checking test conditions and +reporting errors. Status and error info will be logged into the test context. There are a number +of Assert macros that make the unit test code friendly to view and easy to understand. + +### UnitTestLogLib + +Library to support logging information during the test execution. This data is logged to the test +context and will be available in the test reporting phase. This should be used for logging test +details and helpful messages to resolve test failures. + +### UnitTestPersistenceLib + +Persistence lib has the main job of saving and restoring test context to a storage medium so that for tests +that require exiting the active process and then resuming state can be maintained. This is critical +in supporting a system reboot in the middle of a test run. + +### UnitTestResultReportLib + +Library provides function to run at the end of a framework test run and handles formatting the report. +This is a common customization point and allows the unit test framework to fit its output reports into +other test infrastructure. In this package a simple library instances has been supplied to output test +results to the console as plain text. + +### UnitTestTerminationLib + +Sometimes a given test case will need to exit the test in progress to allow system state to change and +will check for that state change on re-entry. This is most common when a Dxe- or Shell-based test wants to +reboot the system and check for a different system state after reboot. Since the method of exiting rebooting +may vary depending on context (PEI, SMM, DXE, Shell, etc.), this functionality is abstracted. + +## Samples + +There is a sample unit test provided as both an example of how to write a unit test and leverage +many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. + +## Usage + +This section is built a lot like a "Getting Started". We'll go through some of the components that are needed +when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe +how to check for expected conditions in test cases and a bit of the logging characteristics. + +Most of these examples will refer to the SampleUnitTestApp found in this package. + +### Requirements - INF + +In our INF file, we'll need to bring in some libraries. At a bare minimum, we'll need an instance of `UnitTestLib`, +however, since Test Assertions are implemented in their own lib in order to allow for framework flexibility, we +will also have to bring in `UnitTestAssertLib` as well. + +See this example in 'SampleUnitTestApp.inf'... + +``` +[LibraryClasses] + BaseLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib +``` + +And in order to bring in the headers we'll need, go ahead and add 'UnitTestPkg/UnitTestPkg.dec' to your +`Packages` list as well. + +### Requirements - Code + +Not to state the obvious, but let's make sure we have the following includes before getting too far along... + +```c +#include +``` + +Now that we've got that squared away, let's look at our 'Main()'' routine (or DriverEntryPoint() or whatever). + +### Configuring the Framework + +Everything in the UnitTestPkg framework is built around an object called -- conveniently -- the Framework. +This Framework object will contain all the information about our test, the test suites and test cases associated +with it, the current location within the test pass, and any results that have been recorded so far. + +To get started with a test, we must first create a Framework instance. The function for this is +`InitUnitTestFramework`. It takes in `CHAR16` strings for the long name, short name, and test version. +The long name and version strings are just for user presentation and relatively flexible. The short name +will be used to name any cache files and/or test results, so should be a name that makes sense in that context. +These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. + +In the 'SampleUnitTestApp', the module name is used as the short name, so the init looks like this. + +```c +DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + +// +// Start setting up the test framework for running the tests. +// +Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); +``` + +The `&Fw` returned here is the handle to the Framework. If it's successfully returned, we can start adding +test suites and test cases. + +Test suites exist purely to help organize test cases and to differentiate the results in reports. If you're writing +a small unit test, you can conceivably put all test cases into a single suite. However, if you end up with 20+ test +cases, it may be beneficial to organize them according to purpose. You _must_ have at least one test suite, even if +it's just a catch-all. The function to create a test suite is `CreateUnitTestSuite`. It takes in a handle to +the Framework object, a `CHAR16` string for the suite title and package name, and optional function pointers for +a setup function and a teardown function. + +The suite title is for user presentation. The package name is for xUnit type reporting and uses a '.'-separated +hierarchical format (see 'SampleUnitTestApp' for example). If provided, the setup and teardown functions will be +called once at the start of the suite (before _any_ tests have run) and once at the end of the suite (after _all_ +tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are +`UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`. + +Looking at 'SampleUnitTestApp', you can see that the first test suite is created as below... + +```c +// +// Populate the SimpleMathTests Unit Test Suite. +// +Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); +``` + +This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and +will be used when adding test cases. + +Alrighty! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test +to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; +a `CHAR16` string for the description and class name; a function pointer for the test case itself; additional, optional +function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. + +Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in +usage to the suite title and package name strings in the test suites. The former is for user presentation and the +latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the +prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining. + +The prerequisite check function has a prototype of `UNIT_TEST_PREREQ` and -- if provided -- will be called +immediately before the test case. If this function returns any error, the test case will not be run and will be +recorded as `UNIT_TEST_ERROR_PREREQ_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called +immediately after the test case to provide an opportunity to reset any global state that may have been changed in the +test case. In the event of a prerequisite failure, the cleanup function will also be skipped. If either of these +functions is not needed, pass `NULL`. + +The context pointer is entirely case-specific. It will be passed to the test case upon execution. One of the purposes +of the context pointer is to allow test case reuse with different input data. (Another use is for testing that wraps +around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context +pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`. + +In 'SampleUnitTestApp', the first test case is added using the code below... + +```c +AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); +``` + +This test case calls the function `OnePlusOneShouldEqualTwo` and has no prerequisite, cleanup, or context. + +Once all the suites and cases are added, it's time to run the Framework. + +```c +// +// Execute the tests. +// +Status = RunAllTestSuites( Fw ); +``` + +### A Simple Test Case + +We'll take a look at the below test case from 'SampleUnitTestApp'... + +```c +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() +``` + +The prototype for this function matches the `UNIT_TEST_FUNCTION` prototype. It takes in a handle to the Framework +itself and the context pointer. The context pointer could be cast and interpreted as anything within this test case, +which is why it's important to configure contexts carefully. The test case returns a value of `UNIT_TEST_STATUS`, which +will be recorded in the Framework and reported at the end of all suites. + +In this test case, the `UT_ASSERT_EQUAL` assertion is being used to establish that the business logic has functioned +correctly. There are several assertion macros, and you are encouraged to use one that matches as closely to your +intended test criterium as possible, because the logging is specific to the macro and more specific macros have more +detailed logs. When in doubt, there are always `UT_ASSERT_TRUE` and `UT_ASSERT_FALSE`. Assertion macros that fail their +test criterium will immediately return from the test case with `UNIT_TEST_ERROR_TEST_FAILED` and log an error string. +_Note_ that this early return can have implications for memory leakage. + +At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. + +## Development + +When using the EDK2 Pytools for CI testing, the host-based unit tests will be built and run on any build that includes the `NOOPT` build target. + +If you are trying to iterate on a single test, a convenient pattern is to build only that test module. For example, the following command will build only the SafeIntLib host-based test from the MdePkg... + +```bash +stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +``` + +## Copyright + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 877d7af0b4e..6affa13d3a4 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -1,210 +1,210 @@ -/** @file -- SampleUnitTestApp.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ -#include -#include -#include -#include - -#include - - -#define UNIT_TEST_APP_NAME "Sample Unit Test Library Application" -#define UNIT_TEST_APP_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Anything you think might be helpful that isn't a test itself. -// - -UNIT_TEST_STATUS -EFIAPI -MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); - return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() - - -VOID -EFIAPI -ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = NULL; - return; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - - -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - - -UNIT_TEST_STATUS -EFIAPI -GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); - - mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); - - return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - - -UNIT_TEST_STATUS -EFIAPI -GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); - return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -/** - SampleUnitTestApp - - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. - -**/ -EFI_STATUS -EFIAPI -SampleUnitTestApp ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the SimpleMathTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); - - // - // Populate the GlobalVarTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); - } - - return Status; -} \ No newline at end of file +/** @file -- SampleUnitTestApp.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ +#include +#include +#include +#include + +#include + + +#define UNIT_TEST_APP_NAME "Sample Unit Test Library Application" +#define UNIT_TEST_APP_VERSION "0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestApp + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestApp ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Framework ); + +EXIT: + if (Framework) + { + FreeUnitTestFramework( Framework ); + } + + return Status; +} diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf index aa45b88ea41..81756eea8e1 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -1,41 +1,41 @@ -## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
-## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestApp - FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = SampleUnitTestApp - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - -[Sources] - SampleUnitTestApp.c - -[Packages] - MdePkg/MdePkg.dec - -[Protocols] - - -[LibraryClasses] - BaseLib - UefiApplicationEntryPoint - DebugLib - UnitTestLib - UnitTestAssertLib - PrintLib - -[Guids] - - - - +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestApp + FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = SampleUnitTestApp + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestApp.c + +[Packages] + MdePkg/MdePkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + + + + diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index e4b9f637b42..45dda89b7e8 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -1,211 +1,211 @@ -/** @file -- SampleUnitTestPeim.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ - -#include -#include -#include - -#include - - -#define UNIT_TEST_PEIM_NAME "Sample Unit Test Library PEIM" -#define UNIT_TEST_PEIM_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Anything you think might be helpful that isn't a test itself. -// - -UNIT_TEST_STATUS -EFIAPI -MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); - return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() - - -VOID -EFIAPI -ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = NULL; - return; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - - -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - - -UNIT_TEST_STATUS -EFIAPI -GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); - - mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); - - return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - - -UNIT_TEST_STATUS -EFIAPI -GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); - return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -/** - SampleUnitTestPeim - - @param FileHandle Handle of the file being invoked. Type - EFI_PEI_FILE_HANDLE is defined in - FfsFindNextFile(). - @param PeiServices Describes the list of possible PEI Services. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. - -**/ -EFI_STATUS -EFIAPI -SampleUnitTestPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the SimpleMathTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); - - // - // Populate the GlobalVarTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); - } - - return Status; -} \ No newline at end of file +/** @file -- SampleUnitTestPeim.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include + +#include + + +#define UNIT_TEST_PEIM_NAME "Sample Unit Test Library PEIM" +#define UNIT_TEST_PEIM_VERSION "0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestPeim + + @param FileHandle Handle of the file being invoked. Type + EFI_PEI_FILE_HANDLE is defined in + FfsFindNextFile(). + @param PeiServices Describes the list of possible PEI Services. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestPeim ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Framework, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Framework ); + +EXIT: + if (Framework) + { + FreeUnitTestFramework( Framework ); + } + + return Status; +} diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf index 06e1729a1cc..e9e07a6d265 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -1,41 +1,41 @@ -## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
-## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestPeim - FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 - MODULE_TYPE = PEIM - VERSION_STRING = 1.0 - ENTRY_POINT = SampleUnitTestPeim - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - -[Sources] - SampleUnitTestPeim.c - -[Packages] - MdePkg/MdePkg.dec - -[Protocols] - - -[LibraryClasses] - BaseLib - PeimEntryPoint - DebugLib - UnitTestLib - UnitTestAssertLib - PrintLib - -[Guids] - -[Depex] - gEfiPeiMemoryDiscoveredPpiGuid - +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestPeim + FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = SampleUnitTestPeim + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestPeim.c + +[Packages] + MdePkg/MdePkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + PeimEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + +[Depex] + gEfiPeiMemoryDiscoveredPpiGuid + diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index d4ae0261705..d3005ed5f34 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -1,209 +1,209 @@ -/** @file -- SampleUnitTestSmm.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ - -#include -#include -#include - -#include - - -#define UNIT_TEST_SMM_NAME "Sample Unit Test Library SMM" -#define UNIT_TEST_SMM_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Anything you think might be helpful that isn't a test itself. -// - -UNIT_TEST_STATUS -EFIAPI -MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); - return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() - - -VOID -EFIAPI -ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = NULL; - return; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - - -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - - -UNIT_TEST_STATUS -EFIAPI -GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); - - mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); - - return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - - -UNIT_TEST_STATUS -EFIAPI -GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID *)-1)); - return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -/** - SampleUnitTestSmm - - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. - -**/ -EFI_STATUS -EFIAPI -SampleUnitTestSmm ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the SimpleMathTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); - - // - // Populate the GlobalVarTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); - } - - return Status; -} \ No newline at end of file +/** @file -- SampleUnitTestSmm.c +This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE +LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR +CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF +SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN +CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) +ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF +THE POSSIBILITY OF SUCH DAMAGE. + + +Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include + +#include + + +#define UNIT_TEST_SMM_NAME "Sample Unit Test Library SMM" +#define UNIT_TEST_SMM_VERSION "0.1" + + +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + + +// +// Anything you think might be helpful that isn't a test itself. +// + +UNIT_TEST_STATUS +EFIAPI +MakeSureThatPointerIsNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); + return UNIT_TEST_PASSED; +} // ListsShouldHaveTheSameDescriptorSize() + + +VOID +EFIAPI +ClearThePointer ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = NULL; + return; +} // ClearThePointer() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + + +UNIT_TEST_STATUS +EFIAPI +OnePlusOneShouldEqualTwo ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + UINTN A, B, C; + + A = 1; + B = 1; + C = A + B; + + UT_ASSERT_EQUAL(C, 2); + return UNIT_TEST_PASSED; +} // OnePlusOneShouldEqualTwo() + + +UNIT_TEST_STATUS +EFIAPI +GlobalBooleanShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestBoolean = TRUE; + UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + + mSampleGlobalTestBoolean = FALSE; + UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + + return UNIT_TEST_PASSED; +} // GlobalBooleanShouldBeChangeable() + + +UNIT_TEST_STATUS +EFIAPI +GlobalPointerShouldBeChangeable ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + mSampleGlobalTestPointer = (VOID*)-1; + UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID *)-1)); + return UNIT_TEST_PASSED; +} // GlobalPointerShouldBeChangeable() + + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +/** + SampleUnitTestSmm + + @param[in] ImageHandle The firmware allocated handle for the EFI image. + @param[in] SystemTable A pointer to the EFI System Table. + + @retval EFI_SUCCESS The entry point executed successfully. + @retval other Some error occured when executing this entry point. + +**/ +EFI_STATUS +EFIAPI +SampleUnitTestSmm ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Framework, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the SimpleMathTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + + // + // Populate the GlobalVarTests Unit Test Suite. + // + Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); + if (EFI_ERROR( Status )) + { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); + AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Framework ); + +EXIT: + if (Framework) + { + FreeUnitTestFramework( Framework ); + } + + return Status; +} diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf index f61165ee22b..3acc8dba2f3 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -1,42 +1,42 @@ -## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
-## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestSmm - FILE_GUID = 389B16DB-F622-424C-9000-9E43C69CBF71 - MODULE_TYPE = DXE_SMM_DRIVER - VERSION_STRING = 1.0 - PI_SPECIFICATION_VERSION = 0x0001000A - ENTRY_POINT = SampleUnitTestSmm - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 IPF EBC -# - -[Sources] - SampleUnitTestSmm.c - -[Packages] - MdePkg/MdePkg.dec - -[Protocols] - - -[LibraryClasses] - BaseLib - UefiDriverEntryPoint - DebugLib - UnitTestLib - UnitTestAssertLib - PrintLib - -[Guids] - -[Depex] - gEfiSmmCpuProtocolGuid - +## @file +## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestSmm + FILE_GUID = 389B16DB-F622-424C-9000-9E43C69CBF71 + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + PI_SPECIFICATION_VERSION = 0x0001000A + ENTRY_POINT = SampleUnitTestSmm + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# + +[Sources] + SampleUnitTestSmm.c + +[Packages] + MdePkg/MdePkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + UefiDriverEntryPoint + DebugLib + UnitTestLib + UnitTestAssertLib + PrintLib + +[Guids] + +[Depex] + gEfiSmmCpuProtocolGuid + diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 7cc680ba6c3..bffa17149b8 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -1,56 +1,56 @@ -## @file -# CI configuration for UnitTestPkg -# -# Copyright (c) Microsoft Corporation -# SPDX-License-Identifier: BSD-2-Clause-Patent -## -{ - "CompilerPlugin": { - "DscPath": "UnitTestFrameworkPkg.dsc" - }, - "CharEncodingCheck": { - "IgnoreFiles": [] - }, - "DependencyCheck": { - "AcceptableDependencies": [ - "MdePkg/MdePkg.dec", - "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" - ], - # For host based unit tests - "AcceptableDependencies-HOST_APPLICATION":[], - # For UEFI shell based apps - "AcceptableDependencies-UEFI_APPLICATION":[ - "MdeModulePkg/MdeModulePkg.dec", - "ShellPkg/ShellPkg.dec" - ], - "IgnoreInf": [] - }, - "DscCompleteCheck": { - "DscPath": "UnitTestFrameworkPkg.dsc", - "IgnoreInf": [ - # Don't need to build these. - # These are host-based only. - "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf", - "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf", - "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf" - ] - }, - "GuidCheck": { - "IgnoreGuidName": [], - "IgnoreGuidValue": [], - "IgnoreFoldersAndFiles": [], - "IgnoreDuplicates": [] - }, - "LibraryClassCheck": { - "IgnoreHeaderFile": [] - }, - - ## options defined ci/Plugin/SpellCheck - "SpellCheck": { - "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log - "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files - "ExtendWords": [], # words to extend to the dictionary for this package - "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore - "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) - } -} +## @file +# CI configuration for UnitTestPkg +# +# Copyright (c) Microsoft Corporation +# SPDX-License-Identifier: BSD-2-Clause-Patent +## +{ + "CompilerPlugin": { + "DscPath": "UnitTestFrameworkPkg.dsc" + }, + "CharEncodingCheck": { + "IgnoreFiles": [] + }, + "DependencyCheck": { + "AcceptableDependencies": [ + "MdePkg/MdePkg.dec", + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], + # For host based unit tests + "AcceptableDependencies-HOST_APPLICATION":[], + # For UEFI shell based apps + "AcceptableDependencies-UEFI_APPLICATION":[ + "MdeModulePkg/MdeModulePkg.dec", + "ShellPkg/ShellPkg.dec" + ], + "IgnoreInf": [] + }, + "DscCompleteCheck": { + "DscPath": "UnitTestFrameworkPkg.dsc", + "IgnoreInf": [ + # Don't need to build these. + # These are host-based only. + "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf", + "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf", + "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf" + ] + }, + "GuidCheck": { + "IgnoreGuidName": [], + "IgnoreGuidValue": [], + "IgnoreFoldersAndFiles": [], + "IgnoreDuplicates": [] + }, + "LibraryClassCheck": { + "IgnoreHeaderFile": [] + }, + + ## options defined ci/Plugin/SpellCheck + "SpellCheck": { + "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files + "ExtendWords": [], # words to extend to the dictionary for this package + "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore + "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) + } +} diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index cc56b9f5f96..007ddfd90fa 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -1,39 +1,39 @@ -## @file -# -# This Package provides all definitions(including functions, MACROs, structures -# and library classes) and libraries instances, which are used to support Unit -# Testing and Interface testing -# -# Copyright (c) 2017, Microsoft Corporation. All rights reserved. -# -## - -[Defines] - DEC_SPECIFICATION = 0x00010005 - PACKAGE_NAME = UnitTestPkg - PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 - PACKAGE_VERSION = 1.00 - -[Includes.Common.Private] - PrivateInclude - Library/HostCmocka/CmockaLib/cmocka/include - Library/HostCmocka/CmockaLib/cmocka/include/cmockery - -[LibraryClasses.Common.Private] - ## @libraryclass Allows save and restore unit test internal state - # - UnitTestPersistenceLib|PrivateInclude/Library/UnitTestPersistenceLib.h - - ## @libraryclass Provides a unit test result report - # - UnitTestResultReportLib|PrivateInclude/Library/UnitTestResultReportLib.h - - ## @libraryclass Provides boot-option routines useful in shell-based tests. - # - UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h - -[Guids] - gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } - -[PcdsFixedAtBuild] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 +## @file +# +# This Package provides all definitions(including functions, MACROs, structures +# and library classes) and libraries instances, which are used to support Unit +# Testing and Interface testing +# +# Copyright (c) 2017, Microsoft Corporation. All rights reserved. +# +## + +[Defines] + DEC_SPECIFICATION = 0x00010005 + PACKAGE_NAME = UnitTestPkg + PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 + PACKAGE_VERSION = 1.00 + +[Includes.Common.Private] + PrivateInclude + Library/HostCmocka/CmockaLib/cmocka/include + Library/HostCmocka/CmockaLib/cmocka/include/cmockery + +[LibraryClasses.Common.Private] + ## @libraryclass Allows save and restore unit test internal state + # + UnitTestPersistenceLib|PrivateInclude/Library/UnitTestPersistenceLib.h + + ## @libraryclass Provides a unit test result report + # + UnitTestResultReportLib|PrivateInclude/Library/UnitTestResultReportLib.h + + ## @libraryclass Provides boot-option routines useful in shell-based tests. + # + UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h + +[Guids] + gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } + +[PcdsFixedAtBuild] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index aac69acaff2..69232ed0c38 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -1,191 +1,191 @@ -## @file -# UnitTestFrameworkPkg -# -# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - PLATFORM_NAME = UnitTestFrameworkPkg - PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 - PLATFORM_VERSION = 1.00 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg - SUPPORTED_ARCHITECTURES = IA32|IPF|X64|EBC|ARM|AARCH64 - BUILD_TARGETS = DEBUG|RELEASE|NOOPT - SKUID_IDENTIFIER = DEFAULT - -################################################################################################### -# -# Components Section - list of the modules and components that will be processed by compilation -# tools and the EDK II tools to generate PE32/PE32+/Coff image files. -# -# Note: The EDK II DSC file is not used to specify how compiled binary images get placed -# into firmware volume images. This section is just a list of modules to compile from -# source into UEFI-compliant binaries. -# It is the FDF file that contains information on combining binary files into firmware -# volume images, whose concept is beyond UEFI and is described in PI specification. -# Binary modules do not need to be listed in this section, as they should be -# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), -# Logo (Logo.bmp), and etc. -# There may also be modules listed in this section that are not required in the FDF file, -# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be -# generated for it, but the binary will not be put into any firmware volume. -# -################################################################################################### - -[LibraryClasses] - # - # Entry point - # - PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf - PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf - DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf - UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf - UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf - # - # Basic - # - BaseLib|MdePkg/Library/BaseLib/BaseLib.inf - BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf - SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf - PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf - PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf - PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf - CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf - PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf - PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf - SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf - # - # UEFI & PI - # - UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf - UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf - UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf - UefiLib|MdePkg/Library/UefiLib/UefiLib.inf - UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf - HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf - DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf - PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf - PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf - DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf - DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf - SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf - UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf - # - # Generic Modules - # - UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf - UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf - SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf - TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf - SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf - CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf - FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf - # - # Misc - # - DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf - DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf - ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf - OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf - PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf - PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf - DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf - PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf - ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf - SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf - S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf - CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf - PlatformBootManagerLib|MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf - PciHostBridgeLib|MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf - TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf - AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf - VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf - FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf - FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - - # - # Shell - # - ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf - ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf - ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf - HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf - -[LibraryClasses.common.PEIM] - HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf - MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf - -[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf - MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - -[LibraryClasses.common.DXE_SMM_DRIVER] - HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf - MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf - -[LibraryClasses.ARM, LibraryClasses.AARCH64] - # - # It is not possible to prevent ARM compiler calls to generic intrinsic functions. - # This library provides the instrinsic functions generated by a given compiler. - # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. - # - NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf - - # - # Since software stack checking may be heuristically enabled by the compiler - # include BaseStackCheckLib unconditionally. - # - NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf - - # - # UnitTestFrameworkPkg - # -[LibraryClasses] - UnitTestAssertLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestLogLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - -[LibraryClasses.common.PEIM] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - -[LibraryClasses.common.DXE_SMM_DRIVER] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - -[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - -[Components] - UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf - UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf - -[BuildOptions] - *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES +## @file +# UnitTestFrameworkPkg +# +# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = UnitTestFrameworkPkg + PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 + PLATFORM_VERSION = 1.00 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg + SUPPORTED_ARCHITECTURES = IA32|IPF|X64|EBC|ARM|AARCH64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT + +################################################################################################### +# +# Components Section - list of the modules and components that will be processed by compilation +# tools and the EDK II tools to generate PE32/PE32+/Coff image files. +# +# Note: The EDK II DSC file is not used to specify how compiled binary images get placed +# into firmware volume images. This section is just a list of modules to compile from +# source into UEFI-compliant binaries. +# It is the FDF file that contains information on combining binary files into firmware +# volume images, whose concept is beyond UEFI and is described in PI specification. +# Binary modules do not need to be listed in this section, as they should be +# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), +# Logo (Logo.bmp), and etc. +# There may also be modules listed in this section that are not required in the FDF file, +# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be +# generated for it, but the binary will not be put into any firmware volume. +# +################################################################################################### + +[LibraryClasses] + # + # Entry point + # + PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf + PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf + DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + # + # Basic + # + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf + PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf + PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf + PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf + CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf + PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf + PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf + SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf + # + # UEFI & PI + # + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf + UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf + UefiLib|MdePkg/Library/UefiLib/UefiLib.inf + UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf + HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf + DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf + UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf + PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf + DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf + SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf + UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf + # + # Generic Modules + # + UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf + UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf + SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf + TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf + SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf + CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf + FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf + # + # Misc + # + DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf + DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf + ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf + OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf + PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf + PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf + ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf + SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf + S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf + CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf + PlatformBootManagerLib|MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf + PciHostBridgeLib|MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf + TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf + AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf + VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf + FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf + FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf + + # + # Shell + # + ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf + ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf + ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf + HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf + +[LibraryClasses.common.PEIM] + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf + +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf + +[LibraryClasses.common.DXE_SMM_DRIVER] + HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf + ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf + MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + # + # It is not possible to prevent ARM compiler calls to generic intrinsic functions. + # This library provides the instrinsic functions generated by a given compiler. + # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. + # + NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf + + # + # Since software stack checking may be heuristically enabled by the compiler + # include BaseStackCheckLib unconditionally. + # + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf + + # + # UnitTestFrameworkPkg + # +[LibraryClasses] + UnitTestAssertLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestLogLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + +[LibraryClasses.common.PEIM] + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + +[LibraryClasses.common.DXE_SMM_DRIVER] + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + +[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] + UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + +[Components] + UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf + UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf + UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf + +[BuildOptions] + *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 110af9c9f609139a66cb5098a9ca3347eca6f13b Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 11:47:30 -0800 Subject: [PATCH 247/384] MdePkg/Test: Fix trailing whitespace and line endings Signed-off-by: Michael D Kinney --- .../IA32/SafeIntLibUintnIntnUnitTests.c | 2 +- .../Library/BaseSafeIntLib/TestBaseSafeIntLib.c | 12 ++++++------ .../Library/BaseSafeIntLib/TestBaseSafeIntLib.h | 2 +- .../X64/SafeIntLibUintnIntnUnitTests.c | 2 +- 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c index a6910fe175f..0a6126079c8 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -535,4 +535,4 @@ TestSafeIntnMult( UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); return UNIT_TEST_PASSED; -} \ No newline at end of file +} diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index c6cb4bc895c..469b7e0c530 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -624,7 +624,7 @@ TestSafeInt32ToChar8( CHAR8 Result = 0; // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // CHAR8 is same as INT8, so same tests as above: // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast @@ -857,7 +857,7 @@ TestSafeUint32ToChar8( CHAR8 Result = 0; // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // CHAR8 is same as INT8, so same tests as above: // // If Operand is <= MAX_INT8, then it's a cast @@ -1037,7 +1037,7 @@ TestSafeIntnToChar8( CHAR8 Result = 0; // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // CHAR8 is same as INT8, so same tests as above: // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast @@ -1262,7 +1262,7 @@ TestSafeUintnToChar8( CHAR8 Result = 0; // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // CHAR8 is same as INT8, so same tests as above: // // If Operand is <= MAX_INT8, then it's a cast @@ -2745,8 +2745,8 @@ UefiTestMain ( Framework = NULL; ConversionTestSuite = NULL; AdditionSubtractionTestSuite = NULL; - MultiplicationTestSuite = NULL; - + MultiplicationTestSuite = NULL; + DEBUG((DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION)); // diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index 38d1664088e..51c58b943fa 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -157,4 +157,4 @@ TestSafeIntnMult( IN UNIT_TEST_CONTEXT Context ); -#endif \ No newline at end of file +#endif diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c index 372139f3d7e..1c89ad596bd 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -539,4 +539,4 @@ TestSafeIntnMult( UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); return UNIT_TEST_PASSED; -} \ No newline at end of file +} From 8d62b6f1829717952df3fc5781bf8a585f22a9b8 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 17:07:42 -0800 Subject: [PATCH 248/384] MdePkg/Test: Fix code style issues Signed-off-by: Michael D Kinney --- MdePkg/Test/MdePkgTest.dsc | 18 +- .../IA32/SafeIntLibUintnIntnUnitTests.c | 242 +++-- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 958 +++++++++++------- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 52 +- .../X64/SafeIntLibUintnIntnUnitTests.c | 242 +++-- 5 files changed, 887 insertions(+), 625 deletions(-) diff --git a/MdePkg/Test/MdePkgTest.dsc b/MdePkg/Test/MdePkgTest.dsc index 2a435c6189f..530cd465b64 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/MdePkg/Test/MdePkgTest.dsc @@ -1,4 +1,4 @@ -## @file MdePkgTest.dsc +## @file # # Copyright (c) 2019, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -6,14 +6,14 @@ ## [Defines] - PLATFORM_NAME = MdePkg - PLATFORM_GUID = 50652B4C-88CB-4481-96E8-37F2D0034440 - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/MdePkg - SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT + PLATFORM_NAME = MdePkgTest + PLATFORM_GUID = 50652B4C-88CB-4481-96E8-37F2D0034440 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdePkg/Test + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT [LibraryClasses] BaseLib|MdePkg/Library/BaseLib/BaseLib.inf diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c index 0a6126079c8..e2f90dfeb25 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -1,31 +1,29 @@ -/** -@file -IA32-specific functions for unit-testing INTN and UINTN functions in -SafeIntLib. - - -Copyright (c) 2017, Microsoft Corporation -Copyright (c) 2019, Intel Corporation. All rights reserved.
- -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** @file + IA32-specific functions for unit-testing INTN and UINTN functions in + SafeIntLib. + + Copyright (c) 2017, Microsoft Corporation + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ @@ -33,18 +31,20 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUintn( +TestSafeInt32ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5bababab; - UINTN Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINTN Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt32ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -61,18 +61,20 @@ TestSafeInt32ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToIntn( +TestSafeUint32ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0x5bababab; - INTN Result = 0; + EFI_STATUS Status; + UINT32 Operand; + INTN Result; // // If Operand is <= MAX_INTN, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUint32ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -89,18 +91,20 @@ TestSafeUint32ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToInt32( +TestSafeIntnToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + INTN Operand; + INT32 Result; // // INTN is same as INT32 in IA32, so this is just a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeIntnToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -110,18 +114,20 @@ TestSafeIntnToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUint32( +TestSafeIntnToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bababab; - UINT32 Result = 0; + EFI_STATUS Status; + INTN Operand; + UINT32 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeIntnToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -138,18 +144,20 @@ TestSafeIntnToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToUint32( +TestSafeUintnToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0xabababab; - UINT32 Result = 0; + EFI_STATUS Status; + UINTN Operand; + UINT32 Result; // // UINTN is same as UINT32 in IA32, so this is just a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUintnToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -159,18 +167,20 @@ TestSafeUintnToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToIntn( +TestSafeUintnToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5bababab; - INTN Result = 0; + EFI_STATUS Status; + UINTN Operand; + INTN Result; // // If Operand is <= MAX_INTN, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUintnToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -187,19 +197,21 @@ TestSafeUintnToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToInt64( +TestSafeUintnToInt64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0xabababab; - INT64 Result = 0; + EFI_STATUS Status; + UINTN Operand; + INT64 Result; // // UINTN is same as UINT32 in IA32, and UINT32 is a subset of // INT64, so this is just a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUintnToInt64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -209,18 +221,20 @@ TestSafeUintnToInt64( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToIntn( +TestSafeInt64ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5bababab; - INTN Result = 0; + EFI_STATUS Status; + INT64 Operand; + INTN Result; // // If Operand is between MIN_INTN and MAX_INTN2 inclusive, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt64ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -246,18 +260,20 @@ TestSafeInt64ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUintn( +TestSafeInt64ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0xabababab; - UINTN Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINTN Result; // // If Operand is between 0 and MAX_UINTN inclusive, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeInt64ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -278,18 +294,20 @@ TestSafeInt64ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToIntn( +TestSafeUint64ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5bababab; - INTN Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INTN Result; // // If Operand is <= MAX_INTN, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUint64ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -306,18 +324,20 @@ TestSafeUint64ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToUintn( +TestSafeUint64ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0xabababab; - UINTN Result = 0; + EFI_STATUS Status; + UINT64 Operand; + UINTN Result; // // If Operand is <= MAX_UINTN, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUint64ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -334,19 +354,22 @@ TestSafeUint64ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUintnAdd( +TestSafeUintnAdd ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Augend = 0x3a3a3a3a; - UINTN Addend = 0x3a3a3a3a; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Augend; + UINTN Addend; + UINTN Result; // // If the result of addition doesn't overflow MAX_UINTN, then it's addition // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; Status = SafeUintnAdd(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74747474, Result); @@ -364,20 +387,23 @@ TestSafeUintnAdd( UNIT_TEST_STATUS EFIAPI -TestSafeIntnAdd( +TestSafeIntnAdd ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Augend = 0x3a3a3a3a; - INTN Addend = 0x3a3a3a3a; - INTN Result = 0; + EFI_STATUS Status; + INTN Augend; + INTN Addend; + INTN Result; // // If the result of addition doesn't overflow MAX_INTN // and doesn't underflow MIN_INTN, then it's addition // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; Status = SafeIntnAdd(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74747474, Result); @@ -406,19 +432,22 @@ TestSafeIntnAdd( UNIT_TEST_STATUS EFIAPI -TestSafeUintnSub( +TestSafeUintnSub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Minuend = 0x5a5a5a5a; - UINTN Subtrahend = 0x3b3b3b3b; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Minuend; + UINTN Subtrahend; + UINTN Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3b3b3b3b; + Result = 0; Status = SafeUintnSub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f1f1f1f, Result); @@ -436,20 +465,23 @@ TestSafeUintnSub( UNIT_TEST_STATUS EFIAPI -TestSafeIntnSub( +TestSafeIntnSub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Minuend = 0x5a5a5a5a; - INTN Subtrahend = 0x3a3a3a3a; - INTN Result = 0; + EFI_STATUS Status; + INTN Minuend; + INTN Subtrahend; + INTN Result; // // If the result of subtractions doesn't overflow MAX_INTN or // underflow MIN_INTN, then it's subtraction // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3a3a3a3a; + Result = 0; Status = SafeIntnSub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x20202020, Result); @@ -478,19 +510,22 @@ TestSafeIntnSub( UNIT_TEST_STATUS EFIAPI -TestSafeUintnMult( +TestSafeUintnMult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Multiplicand = 0xa122a; - UINTN Multiplier = 0xd23; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Multiplicand; + UINTN Multiplier; + UINTN Result; // // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed // + Multiplicand = 0xa122a; + Multiplier = 0xd23; + Result = 0; Status = SafeUintnMult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x844c9dbe, Result); @@ -508,20 +543,23 @@ TestSafeUintnMult( UNIT_TEST_STATUS EFIAPI -TestSafeIntnMult( +TestSafeIntnMult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Multiplicand = 0x123456; - INTN Multiplier = 0x678; - INTN Result = 0; + EFI_STATUS Status; + INTN Multiplicand; + INTN Multiplier; + INTN Result; // // If the result of multiplication doesn't overflow MAX_INTN and doesn't // underflow MIN_UINTN, it will succeed // + Multiplicand = 0x123456; + Multiplier = 0x678; + Result = 0; Status = SafeIntnMult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x75c28c50, Result); diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 469b7e0c530..ad0ffd3ede4 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -1,30 +1,28 @@ -/** -@file -UEFI OS based application for unit testing the SafeIntLib. - - -Copyright (c) 2017, Microsoft Corporation -Copyright (c) 2018, Intel Corporation. All rights reserved.
- -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** @file + UEFI OS based application for unit testing the SafeIntLib. + + Copyright (c) 2017, Microsoft Corporation + Copyright (c) 2018, Intel Corporation. All rights reserved.
+ + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ @@ -38,18 +36,20 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // UNIT_TEST_STATUS EFIAPI -TestSafeInt8ToUint8( +TestSafeInt8ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Operand = 0x5b; - UINT8 Result = 0; + EFI_STATUS Status; + INT8 Operand; + UINT8 Result; // // Positive UINT8 should result in just a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt8ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -66,18 +66,20 @@ TestSafeInt8ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeInt8ToUint16( +TestSafeInt8ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Operand = 0x5b; - UINT16 Result = 0; + EFI_STATUS Status; + INT8 Operand; + UINT16 Result; // // Positive UINT8 should result in just a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt8ToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -94,18 +96,20 @@ TestSafeInt8ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeInt8ToUint32( +TestSafeInt8ToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Operand = 0x5b; - UINT32 Result = 0; + EFI_STATUS Status; + INT8 Operand; + UINT32 Result; // // Positive UINT8 should result in just a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt8ToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -122,18 +126,20 @@ TestSafeInt8ToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeInt8ToUintn( +TestSafeInt8ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Operand = 0x5b; - UINTN Result = 0; + EFI_STATUS Status; + INT8 Operand; + UINTN Result; // // Positive UINT8 should result in just a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt8ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -150,18 +156,20 @@ TestSafeInt8ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeInt8ToUint64( +TestSafeInt8ToUint64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Operand = 0x5b; - UINT64 Result = 0; + EFI_STATUS Status; + INT8 Operand; + UINT64 Result; // // Positive UINT8 should result in just a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt8ToUint64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -178,18 +186,20 @@ TestSafeInt8ToUint64( UNIT_TEST_STATUS EFIAPI -TestSafeUint8ToInt8( +TestSafeUint8ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT8 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + UINT8 Operand; + INT8 Result; // // Operand <= 0x7F (MAX_INT8) should result in a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint8ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -206,14 +216,14 @@ TestSafeUint8ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeUint8ToChar8( +TestSafeUint8ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT8 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + UINT8 Operand; + CHAR8 Result; // // CHAR8 is typedefed as char, which by default is signed, thus @@ -223,6 +233,8 @@ TestSafeUint8ToChar8( // // Operand <= 0x7F (MAX_INT8) should result in a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint8ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -239,18 +251,20 @@ TestSafeUint8ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToInt8( +TestSafeInt16ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + INT16 Operand; + INT8 Result; // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt16ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -276,14 +290,14 @@ TestSafeInt16ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToChar8( +TestSafeInt16ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + INT16 Operand; + CHAR8 Result; // // CHAR8 is typedefed as char, which by default is signed, thus @@ -293,6 +307,8 @@ TestSafeInt16ToChar8( // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt16ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -318,18 +334,20 @@ TestSafeInt16ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToUint8( +TestSafeInt16ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b; - UINT8 Result = 0; + EFI_STATUS Status; + INT16 Operand; + UINT8 Result; // // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt16ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -350,12 +368,12 @@ TestSafeInt16ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToUint16( +TestSafeInt16ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; + EFI_STATUS Status; INT16 Operand = 0x5b5b; UINT16 Result = 0; @@ -378,18 +396,20 @@ TestSafeInt16ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToUint32( +TestSafeInt16ToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b5b; - UINT32 Result = 0; + EFI_STATUS Status; + INT16 Operand; + UINT32 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5b5b; + Result = 0; Status = SafeInt16ToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b5b, Result); @@ -406,18 +426,20 @@ TestSafeInt16ToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToUintn( +TestSafeInt16ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b5b; - UINTN Result = 0; + EFI_STATUS Status; + INT16 Operand; + UINTN Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5b5b; + Result = 0; Status = SafeInt16ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b5b, Result); @@ -434,18 +456,20 @@ TestSafeInt16ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeInt16ToUint64( +TestSafeInt16ToUint64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Operand = 0x5b5b; - UINT64 Result = 0; + EFI_STATUS Status; + INT16 Operand; + UINT64 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5b5b; + Result = 0; Status = SafeInt16ToUint64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b5b, Result); @@ -462,18 +486,20 @@ TestSafeInt16ToUint64( UNIT_TEST_STATUS EFIAPI -TestSafeUint16ToInt8( +TestSafeUint16ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + UINT16 Operand; + INT8 Result; // // If Operand is <= MAX_INT8, it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint16ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -490,14 +516,14 @@ TestSafeUint16ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeUint16ToChar8( +TestSafeUint16ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + UINT16 Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -505,6 +531,8 @@ TestSafeUint16ToChar8( // // If Operand is <= MAX_INT8, it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint16ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -521,18 +549,20 @@ TestSafeUint16ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeUint16ToUint8( +TestSafeUint16ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + UINT16 Operand; + UINT8 Result; // // If Operand is <= MAX_UINT8 (0xff), it's a cast // + Operand = 0xab; + Result = 0; Status = SafeUint16ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -549,18 +579,20 @@ TestSafeUint16ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeUint16ToInt16( +TestSafeUint16ToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Operand = 0x5b5b; - INT16 Result = 0; + EFI_STATUS Status; + UINT16 Operand; + INT16 Result; // // If Operand is <= MAX_INT16 (0x7fff), it's a cast // + Operand = 0x5b5b; + Result = 0; Status = SafeUint16ToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b5b, Result); @@ -577,18 +609,20 @@ TestSafeUint16ToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToInt8( +TestSafeInt32ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + INT32 Operand; + INT8 Result; // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt32ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -614,14 +648,14 @@ TestSafeInt32ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToChar8( +TestSafeInt32ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + INT32 Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -629,6 +663,8 @@ TestSafeInt32ToChar8( // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt32ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -654,18 +690,20 @@ TestSafeInt32ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUint8( +TestSafeInt32ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5b; - UINT8 Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINT8 Result; // // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt32ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -690,18 +728,20 @@ TestSafeInt32ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToInt16( +TestSafeInt32ToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5b5b; - INT16 Result = 0; + EFI_STATUS Status; + INT32 Operand; + INT16 Result; // // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast // + Operand = 0x5b5b; + Result = 0; Status = SafeInt32ToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b5b, Result); @@ -727,18 +767,20 @@ TestSafeInt32ToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUint16( +TestSafeInt32ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINT16 Result; // // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeInt32ToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -763,18 +805,20 @@ TestSafeInt32ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUint32( +TestSafeInt32ToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5bababab; - UINT32 Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINT32 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt32ToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -791,18 +835,20 @@ TestSafeInt32ToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUint64( +TestSafeInt32ToUint64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5bababab; - UINT64 Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINT64 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt32ToUint64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -819,18 +865,20 @@ TestSafeInt32ToUint64( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToInt8( +TestSafeUint32ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + INT8 Result; // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint32ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -847,14 +895,14 @@ TestSafeUint32ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToChar8( +TestSafeUint32ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -862,6 +910,8 @@ TestSafeUint32ToChar8( // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint32ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -878,18 +928,20 @@ TestSafeUint32ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToUint8( +TestSafeUint32ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + UINT8 Result; // // If Operand is <= MAX_UINT8, then it's a cast // + Operand = 0xab; + Result = 0; Status = SafeUint32ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -906,18 +958,20 @@ TestSafeUint32ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToInt16( +TestSafeUint32ToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0x5bab; - INT16 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + INT16 Result; // // If Operand is <= MAX_INT16, then it's a cast // + Operand = 0x5bab; + Result = 0; Status = SafeUint32ToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bab, Result); @@ -934,18 +988,20 @@ TestSafeUint32ToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToUint16( +TestSafeUint32ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + UINT16 Result; // // If Operand is <= MAX_UINT16, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeUint32ToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -962,18 +1018,20 @@ TestSafeUint32ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToInt32( +TestSafeUint32ToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + UINT32 Operand; + INT32 Result; // // If Operand is <= MAX_INT32, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUint32ToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -990,18 +1048,20 @@ TestSafeUint32ToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToInt8( +TestSafeIntnToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + INTN Operand; + INT8 Result; // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeIntnToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1027,14 +1087,14 @@ TestSafeIntnToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToChar8( +TestSafeIntnToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + INTN Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -1042,6 +1102,8 @@ TestSafeIntnToChar8( // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeIntnToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1067,18 +1129,20 @@ TestSafeIntnToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUint8( +TestSafeIntnToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + INTN Operand; + UINT8 Result; // // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast // + Operand = 0xab; + Result = 0; Status = SafeIntnToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -1099,18 +1163,20 @@ TestSafeIntnToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToInt16( +TestSafeIntnToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bab; - INT16 Result = 0; + EFI_STATUS Status; + INTN Operand; + INT16 Result; // // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast // + Operand = 0x5bab; + Result = 0; Status = SafeIntnToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bab, Result); @@ -1136,18 +1202,20 @@ TestSafeIntnToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUint16( +TestSafeIntnToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + INTN Operand; + UINT16 Result; // // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeIntnToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -1168,18 +1236,20 @@ TestSafeIntnToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUintn( +TestSafeIntnToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bababab; - UINTN Result = 0; + EFI_STATUS Status; + INTN Operand; + UINTN Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeIntnToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -1196,18 +1266,20 @@ TestSafeIntnToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUint64( +TestSafeIntnToUint64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bababab; - UINT64 Result = 0; + EFI_STATUS Status; + INTN Operand; + UINT64 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeIntnToUint64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -1224,18 +1296,20 @@ TestSafeIntnToUint64( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToInt8( +TestSafeUintnToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + UINTN Operand; + INT8 Result; // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUintnToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1252,14 +1326,14 @@ TestSafeUintnToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToChar8( +TestSafeUintnToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + UINTN Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -1267,6 +1341,8 @@ TestSafeUintnToChar8( // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUintnToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1283,18 +1359,20 @@ TestSafeUintnToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToUint8( +TestSafeUintnToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + UINTN Operand; + UINT8 Result; // // If Operand is <= MAX_UINT8, then it's a cast // + Operand = 0xab; + Result = 0; Status = SafeUintnToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -1311,18 +1389,20 @@ TestSafeUintnToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToInt16( +TestSafeUintnToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5bab; - INT16 Result = 0; + EFI_STATUS Status; + UINTN Operand; + INT16 Result; // // If Operand is <= MAX_INT16, then it's a cast // + Operand = 0x5bab; + Result = 0; Status = SafeUintnToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bab, Result); @@ -1339,18 +1419,20 @@ TestSafeUintnToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToUint16( +TestSafeUintnToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + UINTN Operand; + UINT16 Result; // // If Operand is <= MAX_UINT16, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeUintnToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -1367,18 +1449,20 @@ TestSafeUintnToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToInt32( +TestSafeUintnToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + UINTN Operand; + INT32 Result; // // If Operand is <= MAX_INT32, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUintnToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -1395,18 +1479,20 @@ TestSafeUintnToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToInt8( +TestSafeInt64ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + INT64 Operand; + INT8 Result; // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt64ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1432,14 +1518,14 @@ TestSafeInt64ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToChar8( +TestSafeInt64ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + INT64 Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -1447,6 +1533,8 @@ TestSafeInt64ToChar8( // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeInt64ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1472,18 +1560,20 @@ TestSafeInt64ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUint8( +TestSafeInt64ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINT8 Result; // // If Operand is between 0 and MAX_UINT8 inclusive, then it's a cast // + Operand = 0xab; + Result = 0; Status = SafeInt64ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -1504,18 +1594,20 @@ TestSafeInt64ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToInt16( +TestSafeInt64ToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5bab; - INT16 Result = 0; + EFI_STATUS Status; + INT64 Operand; + INT16 Result; // // If Operand is between MIN_INT16 and MAX_INT16 inclusive, then it's a cast // + Operand = 0x5bab; + Result = 0; Status = SafeInt64ToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bab, Result); @@ -1541,18 +1633,20 @@ TestSafeInt64ToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUint16( +TestSafeInt64ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINT16 Result; // // If Operand is between 0 and MAX_UINT16 inclusive, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeInt64ToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -1573,18 +1667,20 @@ TestSafeInt64ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToInt32( +TestSafeInt64ToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + INT64 Operand; + INT32 Result; // // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt64ToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -1610,18 +1706,20 @@ TestSafeInt64ToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUint32( +TestSafeInt64ToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0xabababab; - UINT32 Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINT32 Result; // // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeInt64ToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -1642,18 +1740,20 @@ TestSafeInt64ToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUint64( +TestSafeInt64ToUint64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5babababefefefef; - UINT64 Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINT64 Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeInt64ToUint64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -1670,18 +1770,20 @@ TestSafeInt64ToUint64( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToInt8( +TestSafeUint64ToInt8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5b; - INT8 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INT8 Result; // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint64ToInt8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1698,14 +1800,14 @@ TestSafeUint64ToInt8( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToChar8( +TestSafeUint64ToChar8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5b; - CHAR8 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + CHAR8 Result; // CHAR8 is typedefed as char, which by default is signed, thus // CHAR8 is same as INT8, so same tests as above: @@ -1713,6 +1815,8 @@ TestSafeUint64ToChar8( // // If Operand is <= MAX_INT8, then it's a cast // + Operand = 0x5b; + Result = 0; Status = SafeUint64ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); @@ -1729,18 +1833,20 @@ TestSafeUint64ToChar8( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToUint8( +TestSafeUint64ToUint8 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0xab; - UINT8 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + UINT8 Result; // // If Operand is <= MAX_UINT8, then it's a cast // + Operand = 0xab; + Result = 0; Status = SafeUint64ToUint8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xab, Result); @@ -1757,18 +1863,20 @@ TestSafeUint64ToUint8( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToInt16( +TestSafeUint64ToInt16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5bab; - INT16 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INT16 Result; // // If Operand is <= MAX_INT16, then it's a cast // + Operand = 0x5bab; + Result = 0; Status = SafeUint64ToInt16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bab, Result); @@ -1785,18 +1893,20 @@ TestSafeUint64ToInt16( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToUint16( +TestSafeUint64ToUint16 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0xabab; - UINT16 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + UINT16 Result; // // If Operand is <= MAX_UINT16, then it's a cast // + Operand = 0xabab; + Result = 0; Status = SafeUint64ToUint16(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabab, Result); @@ -1813,18 +1923,20 @@ TestSafeUint64ToUint16( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToInt32( +TestSafeUint64ToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INT32 Result; // // If Operand is <= MAX_INT32, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeUint64ToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -1841,18 +1953,20 @@ TestSafeUint64ToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToUint32( +TestSafeUint64ToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0xabababab; - UINT32 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + UINT32 Result; // // If Operand is <= MAX_UINT32, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUint64ToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -1869,18 +1983,20 @@ TestSafeUint64ToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToInt64( +TestSafeUint64ToInt64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5babababefefefef; - INT64 Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INT64 Result; // // If Operand is <= MAX_INT64, then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeUint64ToInt64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -1900,19 +2016,22 @@ TestSafeUint64ToInt64( // UNIT_TEST_STATUS EFIAPI -TestSafeUint8Add( +TestSafeUint8Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT8 Augend = 0x3a; - UINT8 Addend = 0x3a; - UINT8 Result = 0; + EFI_STATUS Status; + UINT8 Augend; + UINT8 Addend; + UINT8 Result; // // If the result of addition doesn't overflow MAX_UINT8, then it's addition // + Augend = 0x3a; + Addend = 0x3a; + Result = 0; Status = SafeUint8Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74, Result); @@ -1930,12 +2049,12 @@ TestSafeUint8Add( UNIT_TEST_STATUS EFIAPI -TestSafeUint16Add( +TestSafeUint16Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; + EFI_STATUS Status; UINT16 Augend = 0x3a3a; UINT16 Addend = 0x3a3a; UINT16 Result = 0; @@ -1960,19 +2079,22 @@ TestSafeUint16Add( UNIT_TEST_STATUS EFIAPI -TestSafeUint32Add( +TestSafeUint32Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Augend = 0x3a3a3a3a; - UINT32 Addend = 0x3a3a3a3a; - UINT32 Result = 0; + EFI_STATUS Status; + UINT32 Augend; + UINT32 Addend; + UINT32 Result; // // If the result of addition doesn't overflow MAX_UINT32, then it's addition // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; Status = SafeUint32Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74747474, Result); @@ -1990,19 +2112,22 @@ TestSafeUint32Add( UNIT_TEST_STATUS EFIAPI -TestSafeUint64Add( +TestSafeUint64Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Augend = 0x3a3a3a3a12121212; - UINT64 Addend = 0x3a3a3a3a12121212; - UINT64 Result = 0; + EFI_STATUS Status; + UINT64 Augend; + UINT64 Addend; + UINT64 Result; // // If the result of addition doesn't overflow MAX_UINT64, then it's addition // + Augend = 0x3a3a3a3a12121212; + Addend = 0x3a3a3a3a12121212; + Result = 0; Status = SafeUint64Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7474747424242424, Result); @@ -2020,20 +2145,23 @@ TestSafeUint64Add( UNIT_TEST_STATUS EFIAPI -TestSafeInt8Add( +TestSafeInt8Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Augend = 0x3a; - INT8 Addend = 0x3a; - INT8 Result = 0; + EFI_STATUS Status; + INT8 Augend; + INT8 Addend; + INT8 Result; // // If the result of addition doesn't overflow MAX_INT8 // and doesn't underflow MIN_INT8, then it's addition // + Augend = 0x3a; + Addend = 0x3a; + Result = 0; Status = SafeInt8Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74, Result); @@ -2063,20 +2191,23 @@ TestSafeInt8Add( UNIT_TEST_STATUS EFIAPI -TestSafeInt16Add( +TestSafeInt16Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Augend = 0x3a3a; - INT16 Addend = 0x3a3a; - INT16 Result = 0; + EFI_STATUS Status; + INT16 Augend; + INT16 Addend; + INT16 Result; // // If the result of addition doesn't overflow MAX_INT16 // and doesn't underflow MIN_INT16, then it's addition // + Augend = 0x3a3a; + Addend = 0x3a3a; + Result = 0; Status = SafeInt16Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7474, Result); @@ -2105,20 +2236,23 @@ TestSafeInt16Add( UNIT_TEST_STATUS EFIAPI -TestSafeInt32Add( +TestSafeInt32Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Augend = 0x3a3a3a3a; - INT32 Addend = 0x3a3a3a3a; - INT32 Result = 0; + EFI_STATUS Status; + INT32 Augend; + INT32 Addend; + INT32 Result; // // If the result of addition doesn't overflow MAX_INT32 // and doesn't underflow MIN_INT32, then it's addition // + Augend = 0x3a3a3a3a; + Addend = 0x3a3a3a3a; + Result = 0; Status = SafeInt32Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x74747474, Result); @@ -2147,20 +2281,23 @@ TestSafeInt32Add( UNIT_TEST_STATUS EFIAPI -TestSafeInt64Add( +TestSafeInt64Add ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Augend = 0x3a3a3a3a3a3a3a3a; - INT64 Addend = 0x3a3a3a3a3a3a3a3a; - INT64 Result = 0; + EFI_STATUS Status; + INT64 Augend; + INT64 Addend; + INT64 Result; // // If the result of addition doesn't overflow MAX_INT64 // and doesn't underflow MIN_INT64, then it's addition // + Augend = 0x3a3a3a3a3a3a3a3a; + Addend = 0x3a3a3a3a3a3a3a3a; + Result = 0; Status = SafeInt64Add(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7474747474747474, Result); @@ -2192,19 +2329,22 @@ TestSafeInt64Add( // UNIT_TEST_STATUS EFIAPI -TestSafeUint8Sub( +TestSafeUint8Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT8 Minuend = 0x5a; - UINT8 Subtrahend = 0x3b; - UINT8 Result = 0; + EFI_STATUS Status; + UINT8 Minuend; + UINT8 Subtrahend; + UINT8 Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a; + Subtrahend = 0x3b; + Result = 0; Status = SafeUint8Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f, Result); @@ -2222,19 +2362,22 @@ TestSafeUint8Sub( UNIT_TEST_STATUS EFIAPI -TestSafeUint16Sub( +TestSafeUint16Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Minuend = 0x5a5a; - UINT16 Subtrahend = 0x3b3b; - UINT16 Result = 0; + EFI_STATUS Status; + UINT16 Minuend; + UINT16 Subtrahend; + UINT16 Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a5a; + Subtrahend = 0x3b3b; + Result = 0; Status = SafeUint16Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f1f, Result); @@ -2252,19 +2395,22 @@ TestSafeUint16Sub( UNIT_TEST_STATUS EFIAPI -TestSafeUint32Sub( +TestSafeUint32Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Minuend = 0x5a5a5a5a; - UINT32 Subtrahend = 0x3b3b3b3b; - UINT32 Result = 0; + EFI_STATUS Status; + UINT32 Minuend; + UINT32 Subtrahend; + UINT32 Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3b3b3b3b; + Result = 0; Status = SafeUint32Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f1f1f1f, Result); @@ -2282,19 +2428,22 @@ TestSafeUint32Sub( UNIT_TEST_STATUS EFIAPI -TestSafeUint64Sub( +TestSafeUint64Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Minuend = 0x5a5a5a5a5a5a5a5a; - UINT64 Subtrahend = 0x3b3b3b3b3b3b3b3b; - UINT64 Result = 0; + EFI_STATUS Status; + UINT64 Minuend; + UINT64 Subtrahend; + UINT64 Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3b3b3b3b3b3b3b3b; + Result = 0; Status = SafeUint64Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f1f1f1f1f1f1f1f, Result); @@ -2312,20 +2461,23 @@ TestSafeUint64Sub( UNIT_TEST_STATUS EFIAPI -TestSafeInt8Sub( +TestSafeInt8Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Minuend = 0x5a; - INT8 Subtrahend = 0x3a; - INT8 Result = 0; + EFI_STATUS Status; + INT8 Minuend; + INT8 Subtrahend; + INT8 Result; // // If the result of subtractions doesn't overflow MAX_INT8 or // underflow MIN_INT8, then it's subtraction // + Minuend = 0x5a; + Subtrahend = 0x3a; + Result = 0; Status = SafeInt8Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x20, Result); @@ -2354,20 +2506,23 @@ TestSafeInt8Sub( UNIT_TEST_STATUS EFIAPI -TestSafeInt16Sub( +TestSafeInt16Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Minuend = 0x5a5a; - INT16 Subtrahend = 0x3a3a; - INT16 Result = 0; + EFI_STATUS Status; + INT16 Minuend; + INT16 Subtrahend; + INT16 Result; // // If the result of subtractions doesn't overflow MAX_INT16 or // underflow MIN_INT16, then it's subtraction // + Minuend = 0x5a5a; + Subtrahend = 0x3a3a; + Result = 0; Status = SafeInt16Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x2020, Result); @@ -2396,20 +2551,23 @@ TestSafeInt16Sub( UNIT_TEST_STATUS EFIAPI -TestSafeInt32Sub( +TestSafeInt32Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Minuend = 0x5a5a5a5a; - INT32 Subtrahend = 0x3a3a3a3a; - INT32 Result = 0; + EFI_STATUS Status; + INT32 Minuend; + INT32 Subtrahend; + INT32 Result; // // If the result of subtractions doesn't overflow MAX_INT32 or // underflow MIN_INT32, then it's subtraction // + Minuend = 0x5a5a5a5a; + Subtrahend = 0x3a3a3a3a; + Result = 0; Status = SafeInt32Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x20202020, Result); @@ -2438,20 +2596,23 @@ TestSafeInt32Sub( UNIT_TEST_STATUS EFIAPI -TestSafeInt64Sub( +TestSafeInt64Sub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Minuend = 0x5a5a5a5a5a5a5a5a; - INT64 Subtrahend = 0x3a3a3a3a3a3a3a3a; - INT64 Result = 0; + EFI_STATUS Status; + INT64 Minuend; + INT64 Subtrahend; + INT64 Result; // // If the result of subtractions doesn't overflow MAX_INT64 or // underflow MIN_INT64, then it's subtraction // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3a3a3a3a3a3a3a3a; + Result = 0; Status = SafeInt64Sub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x2020202020202020, Result); @@ -2483,19 +2644,22 @@ TestSafeInt64Sub( // UNIT_TEST_STATUS EFIAPI -TestSafeUint8Mult( +TestSafeUint8Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT8 Multiplicand = 0x12; - UINT8 Multiplier = 0xa; - UINT8 Result = 0; + EFI_STATUS Status; + UINT8 Multiplicand; + UINT8 Multiplier; + UINT8 Result; // // If the result of multiplication doesn't overflow MAX_UINT8, it will succeed // + Multiplicand = 0x12; + Multiplier = 0xa; + Result = 0; Status = SafeUint8Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xb4, Result); @@ -2513,19 +2677,22 @@ TestSafeUint8Mult( UNIT_TEST_STATUS EFIAPI -TestSafeUint16Mult( +TestSafeUint16Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT16 Multiplicand = 0x212; - UINT16 Multiplier = 0x7a; - UINT16 Result = 0; + EFI_STATUS Status; + UINT16 Multiplicand; + UINT16 Multiplier; + UINT16 Result; // // If the result of multiplication doesn't overflow MAX_UINT16, it will succeed // + Multiplicand = 0x212; + Multiplier = 0x7a; + Result = 0; Status = SafeUint16Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xfc94, Result); @@ -2543,19 +2710,22 @@ TestSafeUint16Mult( UNIT_TEST_STATUS EFIAPI -TestSafeUint32Mult( +TestSafeUint32Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Multiplicand = 0xa122a; - UINT32 Multiplier = 0xd23; - UINT32 Result = 0; + EFI_STATUS Status; + UINT32 Multiplicand; + UINT32 Multiplier; + UINT32 Result; // // If the result of multiplication doesn't overflow MAX_UINT32, it will succeed // + Multiplicand = 0xa122a; + Multiplier = 0xd23; + Result = 0; Status = SafeUint32Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x844c9dbe, Result); @@ -2573,19 +2743,22 @@ TestSafeUint32Mult( UNIT_TEST_STATUS EFIAPI -TestSafeUint64Mult( +TestSafeUint64Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Multiplicand = 0x123456789a; - UINT64 Multiplier = 0x1234567; - UINT64 Result = 0; + EFI_STATUS Status; + UINT64 Multiplicand; + UINT64 Multiplier; + UINT64 Result; // // If the result of multiplication doesn't overflow MAX_UINT64, it will succeed // + Multiplicand = 0x123456789a; + Multiplier = 0x1234567; + Result = 0; Status = SafeUint64Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x14b66db9745a07f6, Result); @@ -2603,20 +2776,23 @@ TestSafeUint64Mult( UNIT_TEST_STATUS EFIAPI -TestSafeInt8Mult( +TestSafeInt8Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT8 Multiplicand = 0x12; - INT8 Multiplier = 0x7; - INT8 Result = 0; + EFI_STATUS Status; + INT8 Multiplicand; + INT8 Multiplier; + INT8 Result; // // If the result of multiplication doesn't overflow MAX_INT8 and doesn't // underflow MIN_UINT8, it will succeed // + Multiplicand = 0x12; + Multiplier = 0x7; + Result = 0; Status = SafeInt8Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7e, Result); @@ -2634,20 +2810,23 @@ TestSafeInt8Mult( UNIT_TEST_STATUS EFIAPI -TestSafeInt16Mult( +TestSafeInt16Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT16 Multiplicand = 0x123; - INT16 Multiplier = 0x67; - INT16 Result = 0; + EFI_STATUS Status; + INT16 Multiplicand; + INT16 Multiplier; + INT16 Result; // // If the result of multiplication doesn't overflow MAX_INT16 and doesn't // underflow MIN_UINT16, it will succeed // + Multiplicand = 0x123; + Multiplier = 0x67; + Result = 0; Status = SafeInt16Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7515, Result); @@ -2665,20 +2844,23 @@ TestSafeInt16Mult( UNIT_TEST_STATUS EFIAPI -TestSafeInt32Mult( +TestSafeInt32Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Multiplicand = 0x123456; - INT32 Multiplier = 0x678; - INT32 Result = 0; + EFI_STATUS Status; + INT32 Multiplicand; + INT32 Multiplier; + INT32 Result; // // If the result of multiplication doesn't overflow MAX_INT32 and doesn't // underflow MIN_UINT32, it will succeed // + Multiplicand = 0x123456; + Multiplier = 0x678; + Result = 0; Status = SafeInt32Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x75c28c50, Result); @@ -2696,20 +2878,23 @@ TestSafeInt32Mult( UNIT_TEST_STATUS EFIAPI -TestSafeInt64Mult( +TestSafeInt64Mult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Multiplicand = 0x123456789; - INT64 Multiplier = 0x6789abcd; - INT64 Result = 0; + EFI_STATUS Status; + INT64 Multiplicand; + INT64 Multiplier; + INT64 Result; // // If the result of multiplication doesn't overflow MAX_INT64 and doesn't // underflow MIN_UINT64, it will succeed // + Multiplicand = 0x123456789; + Multiplier = 0x6789abcd; + Result = 0; Status = SafeInt64Mult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x75cd9045220d6bb5, Result); @@ -2733,7 +2918,7 @@ TestSafeInt64Mult( EFI_STATUS EFIAPI UefiTestMain ( - VOID + VOID ) { EFI_STATUS Status; @@ -2902,8 +3087,11 @@ UefiTestMain ( return Status; } -int main (void) +int +main ( + int argc, + char *argv[] + ) { return UefiTestMain (); } - diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index 51c58b943fa..a7bb0edef9a 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -1,30 +1,28 @@ -/** -@file -UEFI OS based application for unit testing the SafeIntLib. - - -Copyright (c) 2017, Microsoft Corporation -Copyright (c) 2018, Intel Corporation. All rights reserved.
- -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** @file + UEFI OS based application for unit testing the SafeIntLib. + + Copyright (c) 2017, Microsoft Corporation + Copyright (c) 2018, Intel Corporation. All rights reserved.
+ + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c index 1c89ad596bd..d84f8eee171 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -1,31 +1,29 @@ -/** -@file -x64-specific functions for unit-testing INTN and UINTN functions in -SafeIntLib. - - -Copyright (c) 2017, Microsoft Corporation -Copyright (c) 2019, Intel Corporation. All rights reserved.
- -All rights reserved. -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are met: -1. Redistributions of source code must retain the above copyright notice, -this list of conditions and the following disclaimer. -2. Redistributions in binary form must reproduce the above copyright notice, -this list of conditions and the following disclaimer in the documentation -and/or other materials provided with the distribution. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +/** @file + x64-specific functions for unit-testing INTN and UINTN functions in + SafeIntLib. + + Copyright (c) 2017, Microsoft Corporation + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ + All rights reserved. + Redistribution and use in source and binary forms, with or without + modification, are permitted provided that the following conditions are met: + 1. Redistributions of source code must retain the above copyright notice, + this list of conditions and the following disclaimer. + 2. Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND + ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. + IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, + INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, + BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF + LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE + OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF + ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **/ @@ -33,18 +31,20 @@ ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. UNIT_TEST_STATUS EFIAPI -TestSafeInt32ToUintn( +TestSafeInt32ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT32 Operand = 0x5bababab; - UINTN Result = 0; + EFI_STATUS Status; + INT32 Operand; + UINTN Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeInt32ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -61,14 +61,14 @@ TestSafeInt32ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUint32ToIntn( +TestSafeUint32ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT32 Operand = 0xabababab; - INTN Result = 0; + EFI_STATUS Status; + UINT32 Operand; + INTN Result; // // For x64, INTN is same as INT64 which is a superset of INT32 @@ -78,6 +78,8 @@ TestSafeUint32ToIntn( // // If Operand is non-negative, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUint32ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -87,18 +89,20 @@ TestSafeUint32ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToInt32( +TestSafeIntnToInt32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0x5bababab; - INT32 Result = 0; + EFI_STATUS Status; + INTN Operand; + INT32 Result; // // If Operand is between MIN_INT32 and MAX_INT32 inclusive, then it's a cast // + Operand = 0x5bababab; + Result = 0; Status = SafeIntnToInt32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5bababab, Result); @@ -124,18 +128,20 @@ TestSafeIntnToInt32( UNIT_TEST_STATUS EFIAPI -TestSafeIntnToUint32( +TestSafeIntnToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Operand = 0xabababab; - UINT32 Result = 0; + EFI_STATUS Status; + INTN Operand; + UINT32 Result; // // If Operand is between 0 and MAX_UINT32 inclusive, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeIntnToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -156,18 +162,20 @@ TestSafeIntnToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToUint32( +TestSafeUintnToUint32 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0xabababab; - UINT32 Result = 0; + EFI_STATUS Status; + UINTN Operand; + UINT32 Result; // // If Operand is <= MAX_UINT32, then it's a cast // + Operand = 0xabababab; + Result = 0; Status = SafeUintnToUint32(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xabababab, Result); @@ -184,18 +192,20 @@ TestSafeUintnToUint32( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToIntn( +TestSafeUintnToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5babababefefefef; - INTN Result = 0; + EFI_STATUS Status; + UINTN Operand; + INTN Result; // // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeUintnToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -212,18 +222,20 @@ TestSafeUintnToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeUintnToInt64( +TestSafeUintnToInt64 ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Operand = 0x5babababefefefef; - INT64 Result = 0; + EFI_STATUS Status; + UINTN Operand; + INT64 Result; // // If Operand is <= MAX_INT64, then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeUintnToInt64(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -240,18 +252,20 @@ TestSafeUintnToInt64( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToIntn( +TestSafeInt64ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5babababefefefef; - INTN Result = 0; + EFI_STATUS Status; + INT64 Operand; + INTN Result; // // INTN is same as INT64 in x64, so this is just a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeInt64ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -261,18 +275,20 @@ TestSafeInt64ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeInt64ToUintn( +TestSafeInt64ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INT64 Operand = 0x5babababefefefef; - UINTN Result = 0; + EFI_STATUS Status; + INT64 Operand; + UINTN Result; // // If Operand is non-negative, then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeInt64ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -289,18 +305,20 @@ TestSafeInt64ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToIntn( +TestSafeUint64ToIntn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0x5babababefefefef; - INTN Result = 0; + EFI_STATUS Status; + UINT64 Operand; + INTN Result; // // If Operand is <= MAX_INTN (0x7fff_ffff_ffff_ffff), then it's a cast // + Operand = 0x5babababefefefef; + Result = 0; Status = SafeUint64ToIntn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5babababefefefef, Result); @@ -317,18 +335,20 @@ TestSafeUint64ToIntn( UNIT_TEST_STATUS EFIAPI -TestSafeUint64ToUintn( +TestSafeUint64ToUintn ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINT64 Operand = 0xababababefefefef; - UINTN Result = 0; + EFI_STATUS Status; + UINT64 Operand; + UINTN Result; // // UINTN is same as UINT64 in x64, so this is just a cast // + Operand = 0xababababefefefef; + Result = 0; Status = SafeUint64ToUintn(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0xababababefefefef, Result); @@ -338,19 +358,22 @@ TestSafeUint64ToUintn( UNIT_TEST_STATUS EFIAPI -TestSafeUintnAdd( +TestSafeUintnAdd ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Augend = 0x3a3a3a3a12121212; - UINTN Addend = 0x3a3a3a3a12121212; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Augend; + UINTN Addend; + UINTN Result; // // If the result of addition doesn't overflow MAX_UINTN, then it's addition // + Augend = 0x3a3a3a3a12121212; + Addend = 0x3a3a3a3a12121212; + Result = 0; Status = SafeUintnAdd(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7474747424242424, Result); @@ -368,20 +391,23 @@ TestSafeUintnAdd( UNIT_TEST_STATUS EFIAPI -TestSafeIntnAdd( +TestSafeIntnAdd ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Augend = 0x3a3a3a3a3a3a3a3a; - INTN Addend = 0x3a3a3a3a3a3a3a3a; - INTN Result = 0; + EFI_STATUS Status; + INTN Augend; + INTN Addend; + INTN Result; // // If the result of addition doesn't overflow MAX_INTN // and doesn't underflow MIN_INTN, then it's addition // + Augend = 0x3a3a3a3a3a3a3a3a; + Addend = 0x3a3a3a3a3a3a3a3a; + Result = 0; Status = SafeIntnAdd(Augend, Addend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x7474747474747474, Result); @@ -410,19 +436,22 @@ TestSafeIntnAdd( UNIT_TEST_STATUS EFIAPI -TestSafeUintnSub( +TestSafeUintnSub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Minuend = 0x5a5a5a5a5a5a5a5a; - UINTN Subtrahend = 0x3b3b3b3b3b3b3b3b; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Minuend; + UINTN Subtrahend; + UINTN Result; // // If Minuend >= Subtrahend, then it's subtraction // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3b3b3b3b3b3b3b3b; + Result = 0; Status = SafeUintnSub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x1f1f1f1f1f1f1f1f, Result); @@ -440,20 +469,23 @@ TestSafeUintnSub( UNIT_TEST_STATUS EFIAPI -TestSafeIntnSub( +TestSafeIntnSub ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Minuend = 0x5a5a5a5a5a5a5a5a; - INTN Subtrahend = 0x3a3a3a3a3a3a3a3a; - INTN Result = 0; + EFI_STATUS Status; + INTN Minuend; + INTN Subtrahend; + INTN Result; // // If the result of subtractions doesn't overflow MAX_INTN or // underflow MIN_INTN, then it's subtraction // + Minuend = 0x5a5a5a5a5a5a5a5a; + Subtrahend = 0x3a3a3a3a3a3a3a3a; + Result = 0; Status = SafeIntnSub(Minuend, Subtrahend, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x2020202020202020, Result); @@ -482,19 +514,22 @@ TestSafeIntnSub( UNIT_TEST_STATUS EFIAPI -TestSafeUintnMult( +TestSafeUintnMult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - UINTN Multiplicand = 0x123456789a; - UINTN Multiplier = 0x1234567; - UINTN Result = 0; + EFI_STATUS Status; + UINTN Multiplicand; + UINTN Multiplier; + UINTN Result; // // If the result of multiplication doesn't overflow MAX_UINTN, it will succeed // + Multiplicand = 0x123456789a; + Multiplier = 0x1234567; + Result = 0; Status = SafeUintnMult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x14b66db9745a07f6, Result); @@ -512,20 +547,23 @@ TestSafeUintnMult( UNIT_TEST_STATUS EFIAPI -TestSafeIntnMult( +TestSafeIntnMult ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { - EFI_STATUS Status; - INTN Multiplicand = 0x123456789; - INTN Multiplier = 0x6789abcd; - INTN Result = 0; + EFI_STATUS Status; + INTN Multiplicand; + INTN Multiplier; + INTN Result; // // If the result of multiplication doesn't overflow MAX_INTN and doesn't // underflow MIN_UINTN, it will succeed // + Multiplicand = 0x123456789; + Multiplier = 0x6789abcd; + Result = 0; Status = SafeIntnMult(Multiplicand, Multiplier, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x75cd9045220d6bb5, Result); From 8c885c665790ba74ebf29d183fcafdb7b2e6ac9e Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Fri, 3 Jan 2020 15:36:01 -0800 Subject: [PATCH 249/384] Bug - Incorrect case for submodule causing setup to fail --- .pytool/CISettings.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 0ab142f8660..6ee9fcc6c20 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -144,7 +144,7 @@ def GetRequiredSubmodules(self): rs.append(RequiredSubmodule( "CryptoPkg/Library/OpensslLib/openssl", False)) rs.append(RequiredSubmodule( - "UnitTestFrameworkPkg/Library/HostCMocka/CmockaLib/cmocka", False)) + "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka", False)) return rs def GetName(self): From 9dea9786cb64204829d99d5eaa7d6a6eb6a02ceb Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Fri, 3 Jan 2020 15:36:22 -0800 Subject: [PATCH 250/384] Unpin extensions dependency as it should use latest pip --- pip-requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pip-requirements.txt b/pip-requirements.txt index 352ae75473d..6a41a95ec59 100644 --- a/pip-requirements.txt +++ b/pip-requirements.txt @@ -13,4 +13,4 @@ ## edk2-pytool-library==0.10.* -edk2-pytool-extensions==0.12.0 +edk2-pytool-extensions==0.12.* From 5794bf7a247c7ff3a648c4b469e4b16d4f7b8b69 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Fri, 3 Jan 2020 16:01:05 -0800 Subject: [PATCH 251/384] Remove stuart_ci_setup as this solution doesn't require it --- .azurepipelines/templates/pr-gate-steps.yml | 7 ------- .pytool/CISettings.py | 5 ++--- .../HostBasedUnitTestRunner_plug_in.yaml | 6 +++--- 3 files changed, 5 insertions(+), 13 deletions(-) diff --git a/.azurepipelines/templates/pr-gate-steps.yml b/.azurepipelines/templates/pr-gate-steps.yml index e278cc3b183..a969661dea1 100644 --- a/.azurepipelines/templates/pr-gate-steps.yml +++ b/.azurepipelines/templates/pr-gate-steps.yml @@ -48,13 +48,6 @@ steps: - template: spell-check-prereq-steps.yml # Build repo -- task: CmdLine@1 - displayName: CI Setup ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} - inputs: - filename: stuart_ci_setup - arguments: -c .pytool/CISettings.py -p $(pkgs_to_build) -t ${{ parameters.build_targets}} -a ${{ parameters.build_archs}} TOOL_CHAIN_TAG=${{ parameters.tool_chain_tag}} - condition: and(gt(variables.pkg_count, 0), succeeded()) - - task: CmdLine@1 displayName: Setup ${{ parameters.build_pkgs }} ${{ parameters.build_archs}} inputs: diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index 6ee9fcc6c20..fd99c517c3b 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -6,7 +6,6 @@ import os import logging from edk2toolext.environment import shell_environment -from edk2toolext.invocables.edk2_ci_setup import CiSetupSettingsManager from edk2toolext.invocables.edk2_ci_build import CiBuildSettingsManager from edk2toolext.invocables.edk2_setup import SetupSettingsManager, RequiredSubmodule from edk2toolext.invocables.edk2_update import UpdateSettingsManager @@ -14,7 +13,7 @@ from edk2toollib.utility_functions import GetHostInfo -class Settings(CiSetupSettingsManager, CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): +class Settings(CiBuildSettingsManager, UpdateSettingsManager, SetupSettingsManager, PrEvalSettingsManager): def __init__(self): self.ActualPackages = [] @@ -119,7 +118,7 @@ def SetTargets(self, list_of_requested_target): def GetActiveScopes(self): ''' return tuple containing scopes that should be active for this process ''' - scopes = ("cibuild","edk2-build","host-based-test") + scopes = ("cibuild", "edk2-build", "host-based-test") self.ActualToolChainTag = shell_environment.GetBuildVars().GetValue("TOOL_CHAIN_TAG", "") diff --git a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml index 27fe4b028a1..c25fa4746c4 100644 --- a/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml +++ b/BaseTools/Plugin/HostBasedUnitTestRunner/HostBasedUnitTestRunner_plug_in.yaml @@ -1,6 +1,6 @@ ## -# CiBuildPlugin used to run any unittests that -# were built on this CI pass. +# IUefiBuildPlugin used to run any unittests that +# were built on this build. # # Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -9,4 +9,4 @@ "scope": "host-test-win", "name": "Windows Host-Based Unit Test Runner", "module": "HostBasedUnitTestRunner" -} \ No newline at end of file +} From 584632e069be21891ec95ebfcb902ff2899d6669 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 3 Jan 2020 17:25:47 -0800 Subject: [PATCH 252/384] UnitTestFrameworkPkg: Tem disable build of Posix libs Signed-off-by: Michael D Kinney --- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 69232ed0c38..d199c1d2373 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -170,8 +170,8 @@ UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf [Components] - UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf - UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf +# UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf +# UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf From 49accdedf956f175041040e677163b7cbb746283 Mon Sep 17 00:00:00 2001 From: "Albecki, Mateusz" Date: Sat, 21 Dec 2019 01:13:11 +0800 Subject: [PATCH 253/384] MdeModulePkg/SdMmcPciHcDxe: Hook SwitchClockFreq after SD clock start For eMMC modules we used to notify the platform about frequency change only after sending CMD13 which meant that platform might not get a chance to apply required post frequency change fixes to get the clock stable. To fix this notification has been moved to SdMmcHcClockSupply function just after we start the SD clock. During first time setup the notification won't be sent to avoid changing old behavior. Cc: Hao A Wu Cc: Marcin Wojtas Cc: Zhichao Gao Cc: Liming Gao Signed-off-by: Mateusz Albecki Tested-by: Marcin Wojtas Tested-by: Hao A Wu Reviewed-by: Hao A Wu --- .../Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c | 20 +--- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c | 28 ++--- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h | 24 ++++ .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 107 ++++++++---------- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h | 44 ------- 5 files changed, 81 insertions(+), 142 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c index 082904ccc5d..776c0e796c5 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/EmmcDevice.c @@ -727,7 +727,7 @@ EmmcSwitchBusTiming ( // // Convert the clock freq unit from MHz to KHz. // - Status = SdMmcHcClockSupply (PciIo, Slot, ClockFreq * 1000, Private->BaseClkFreq[Slot], Private->ControllerVersion[Slot]); + Status = SdMmcHcClockSupply (Private, Slot, BusTiming, FALSE, ClockFreq * 1000); if (EFI_ERROR (Status)) { return Status; } @@ -745,24 +745,6 @@ EmmcSwitchBusTiming ( return EFI_DEVICE_ERROR; } - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { - Status = mOverride->NotifyPhase ( - Private->ControllerHandle, - Slot, - EdkiiSdMmcSwitchClockFreqPost, - &BusTiming - ); - if (EFI_ERROR (Status)) { - DEBUG (( - DEBUG_ERROR, - "%a: SD/MMC switch clock freq post notifier callback failed - %r\n", - __FUNCTION__, - Status - )); - return Status; - } - } - return Status; } diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c index 336baade9e5..d63dc54e8c3 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c @@ -1145,29 +1145,11 @@ SdCardSetBusMode ( return Status; } - Status = SdMmcHcClockSupply (PciIo, Slot, BusMode.ClockFreq * 1000, Private->BaseClkFreq[Slot], Private->ControllerVersion[Slot]); + Status = SdMmcHcClockSupply (Private, Slot, BusMode.BusTiming, FALSE, BusMode.ClockFreq * 1000); if (EFI_ERROR (Status)) { return Status; } - if (mOverride != NULL && mOverride->NotifyPhase != NULL) { - Status = mOverride->NotifyPhase ( - Private->ControllerHandle, - Slot, - EdkiiSdMmcSwitchClockFreqPost, - &BusMode.BusTiming - ); - if (EFI_ERROR (Status)) { - DEBUG (( - DEBUG_ERROR, - "%a: SD/MMC switch clock freq post notifier callback failed - %r\n", - __FUNCTION__, - Status - )); - return Status; - } - } - if ((BusMode.BusTiming == SdMmcUhsSdr104) || ((BusMode.BusTiming == SdMmcUhsSdr50) && (Capability->TuningSDR50 != 0))) { Status = SdCardTuningClock (PciIo, PassThru, Slot); if (EFI_ERROR (Status)) { @@ -1345,7 +1327,13 @@ SdCardIdentification ( goto Error; } - SdMmcHcInitClockFreq (PciIo, Slot, Private->BaseClkFreq[Slot], Private->ControllerVersion[Slot]); + // + // Restart the clock with first time parameters. + // NOTE: it is not required to actually restart the clock + // and go through internal clock setup again. Some time + // could be saved if we simply started the SD clock. + // + SdMmcHcClockSupply (Private, Slot, 0, TRUE, 400); gBS->Stall (1000); diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h index c29e48767ec..03049601324 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHcDxe.h @@ -796,6 +796,30 @@ SdCardIdentification ( IN UINT8 Slot ); +/** + SD/MMC card clock supply. + + Refer to SD Host Controller Simplified spec 3.0 Section 3.2.1 for details. + + @param[in] Private A pointer to the SD_MMC_HC_PRIVATE_DATA instance. + @param[in] Slot The slot number of the SD card to send the command to. + @param[in] BusTiming BusTiming at which the frequency change is done. + @param[in] FirstTimeSetup Flag to indicate whether the clock is being setup for the first time. + @param[in] ClockFreq The max clock frequency to be set. The unit is KHz. + + @retval EFI_SUCCESS The clock is supplied successfully. + @retval Others The clock isn't supplied successfully. + +**/ +EFI_STATUS +SdMmcHcClockSupply ( + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot, + IN SD_MMC_BUS_MODE BusTiming, + IN BOOLEAN FirstTimeSetup, + IN UINT64 ClockFreq + ); + /** Software reset the specified SD/MMC host controller. diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index b9d04e0f17a..f667264c5e7 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -763,11 +763,11 @@ SdMmcHcStopClock ( Refer to SD Host Controller Simplified spec 3.0 Section 3.2.1 for details. - @param[in] PciIo The PCI IO protocol instance. - @param[in] Slot The slot number of the SD card to send the command to. - @param[in] ClockFreq The max clock frequency to be set. The unit is KHz. - @param[in] BaseClkFreq The base clock frequency of host controller in MHz. - @param[in] ControllerVer The version of host controller. + @param[in] Private A pointer to the SD_MMC_HC_PRIVATE_DATA instance. + @param[in] Slot The slot number of the SD card to send the command to. + @param[in] BusTiming BusTiming at which the frequency change is done. + @param[in] FirstTimeSetup Flag to indicate whether the clock is being setup for the first time. + @param[in] ClockFreq The max clock frequency to be set. The unit is KHz. @retval EFI_SUCCESS The clock is supplied successfully. @retval Others The clock isn't supplied successfully. @@ -775,11 +775,11 @@ SdMmcHcStopClock ( **/ EFI_STATUS SdMmcHcClockSupply ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT64 ClockFreq, - IN UINT32 BaseClkFreq, - IN UINT16 ControllerVer + IN SD_MMC_HC_PRIVATE_DATA *Private, + IN UINT8 Slot, + IN SD_MMC_BUS_MODE BusTiming, + IN BOOLEAN FirstTimeSetup, + IN UINT64 ClockFreq ) { EFI_STATUS Status; @@ -787,13 +787,15 @@ SdMmcHcClockSupply ( UINT32 Divisor; UINT32 Remainder; UINT16 ClockCtrl; + UINT32 BaseClkFreq; + UINT16 ControllerVer; + EFI_PCI_IO_PROTOCOL *PciIo; - // - // Calculate a divisor for SD clock frequency - // - ASSERT (BaseClkFreq != 0); + PciIo = Private->PciIo; + BaseClkFreq = Private->BaseClkFreq[Slot]; + ControllerVer = Private->ControllerVersion[Slot]; - if (ClockFreq == 0) { + if (BaseClkFreq == 0 || ClockFreq == 0) { return EFI_INVALID_PARAMETER; } @@ -883,6 +885,29 @@ SdMmcHcClockSupply ( ClockCtrl = BIT2; Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + // + // We don't notify the platform on first time setup to avoid changing + // legacy behavior. During first time setup we also don't know what type + // of the card slot it is and which enum value of BusTiming applies. + // + if (!FirstTimeSetup && mOverride != NULL && mOverride->NotifyPhase != NULL) { + Status = mOverride->NotifyPhase ( + Private->ControllerHandle, + Slot, + EdkiiSdMmcSwitchClockFreqPost, + &BusTiming + ); + if (EFI_ERROR (Status)) { + DEBUG (( + DEBUG_ERROR, + "%a: SD/MMC switch clock freq post notifier callback failed - %r\n", + __FUNCTION__, + Status + )); + return Status; + } + } + return Status; } @@ -1038,49 +1063,6 @@ SdMmcHcInitV4Enhancements ( return EFI_SUCCESS; } -/** - Supply SD/MMC card with lowest clock frequency at initialization. - - @param[in] PciIo The PCI IO protocol instance. - @param[in] Slot The slot number of the SD card to send the command to. - @param[in] BaseClkFreq The base clock frequency of host controller in MHz. - @param[in] ControllerVer The version of host controller. - - @retval EFI_SUCCESS The clock is supplied successfully. - @retval Others The clock isn't supplied successfully. - -**/ -EFI_STATUS -SdMmcHcInitClockFreq ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT32 BaseClkFreq, - IN UINT16 ControllerVer - ) -{ - EFI_STATUS Status; - UINT32 InitFreq; - - // - // According to SDHCI specification ver. 4.2, BaseClkFreq field value of - // the Capability Register 1 can be zero, which means a need for obtaining - // the clock frequency via another method. Fail in case it is not updated - // by SW at this point. - // - if (BaseClkFreq == 0) { - // - // Don't support get Base Clock Frequency information via another method - // - return EFI_UNSUPPORTED; - } - // - // Supply 400KHz clock frequency at initialization phase. - // - InitFreq = 400; - Status = SdMmcHcClockSupply (PciIo, Slot, InitFreq, BaseClkFreq, ControllerVer); - return Status; -} - /** Supply SD/MMC card with maximum voltage at initialization. @@ -1216,7 +1198,14 @@ SdMmcHcInitHost ( return Status; } - Status = SdMmcHcInitClockFreq (PciIo, Slot, Private->BaseClkFreq[Slot], Private->ControllerVersion[Slot]); + // + // Perform first time clock setup with 400 KHz frequency. + // We send the 0 as the BusTiming value because at this time + // we still do not know the slot type and which enum value will apply. + // Since it is a first time setup SdMmcHcClockSupply won't notify + // the platofrm driver anyway so it doesn't matter. + // + Status = SdMmcHcClockSupply (Private, Slot, 0, TRUE, 400); if (EFI_ERROR (Status)) { return Status; } diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h index 088c70451cd..826e851b045 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h @@ -478,30 +478,6 @@ SdMmcHcStopClock ( IN UINT8 Slot ); -/** - SD/MMC card clock supply. - - Refer to SD Host Controller Simplified spec 3.0 Section 3.2.1 for details. - - @param[in] PciIo The PCI IO protocol instance. - @param[in] Slot The slot number of the SD card to send the command to. - @param[in] ClockFreq The max clock frequency to be set. The unit is KHz. - @param[in] BaseClkFreq The base clock frequency of host controller in MHz. - @param[in] ControllerVer The version of host controller. - - @retval EFI_SUCCESS The clock is supplied successfully. - @retval Others The clock isn't supplied successfully. - -**/ -EFI_STATUS -SdMmcHcClockSupply ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT64 ClockFreq, - IN UINT32 BaseClkFreq, - IN UINT16 ControllerVer - ); - /** SD/MMC bus power control. @@ -542,26 +518,6 @@ SdMmcHcSetBusWidth ( IN UINT16 BusWidth ); -/** - Supply SD/MMC card with lowest clock frequency at initialization. - - @param[in] PciIo The PCI IO protocol instance. - @param[in] Slot The slot number of the SD card to send the command to. - @param[in] BaseClkFreq The base clock frequency of host controller in MHz. - @param[in] ControllerVer The version of host controller. - - @retval EFI_SUCCESS The clock is supplied successfully. - @retval Others The clock isn't supplied successfully. - -**/ -EFI_STATUS -SdMmcHcInitClockFreq ( - IN EFI_PCI_IO_PROTOCOL *PciIo, - IN UINT8 Slot, - IN UINT32 BaseClkFreq, - IN UINT16 ControllerVer - ); - /** Supply SD/MMC card with maximum voltage at initialization. From f68cb23c1469eee7ea6c28191dedcfef114d1495 Mon Sep 17 00:00:00 2001 From: "Albecki, Mateusz" Date: Sat, 21 Dec 2019 01:13:12 +0800 Subject: [PATCH 254/384] MdeModulePkg/SdMmcPciHcDxe: Add function to start SD clock In SD card voltage switch flow we used to redo the entire internal clock setup after voltage switch. Since internal clock has already been setup this is wasting time on polling the internal clock stable. This commit changes it to only start the SD clock. Cc: Hao A Wu Cc: Marcin Wojtas Cc: Zhichao Gao Cc: Liming Gao Signed-off-by: Mateusz Albecki Tested-by: Marcin Wojtas Tested-by: Hao A Wu Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c | 11 +++---- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 33 ++++++++++++++++--- .../Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h | 15 +++++++++ 3 files changed, 47 insertions(+), 12 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c index d63dc54e8c3..b630daab763 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdDevice.c @@ -1327,13 +1327,10 @@ SdCardIdentification ( goto Error; } - // - // Restart the clock with first time parameters. - // NOTE: it is not required to actually restart the clock - // and go through internal clock setup again. Some time - // could be saved if we simply started the SD clock. - // - SdMmcHcClockSupply (Private, Slot, 0, TRUE, 400); + Status = SdMmcHcStartSdClock (PciIo, Slot); + if (EFI_ERROR (Status)) { + goto Error; + } gBS->Stall (1000); diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index f667264c5e7..e7f2fac69b6 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -758,6 +758,30 @@ SdMmcHcStopClock ( return Status; } +/** + Start the SD clock. + + @param[in] PciIo The PCI IO protocol instance. + @param[in] Slot The slot number. + + @retval EFI_SUCCESS Succeeded to start the SD clock. + @rtval Others Failed to start the SD clock. +**/ +EFI_STATUS +SdMmcHcStartSdClock ( + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot + ) +{ + UINT16 ClockCtrl; + + // + // Set SD Clock Enable in the Clock Control register to 1 + // + ClockCtrl = BIT2; + return SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); +} + /** SD/MMC card clock supply. @@ -879,11 +903,10 @@ SdMmcHcClockSupply ( return Status; } - // - // Set SD Clock Enable in the Clock Control register to 1 - // - ClockCtrl = BIT2; - Status = SdMmcHcOrMmio (PciIo, Slot, SD_MMC_HC_CLOCK_CTRL, sizeof (ClockCtrl), &ClockCtrl); + Status = SdMmcHcStartSdClock (PciIo, Slot); + if (EFI_ERROR (Status)) { + return Status; + } // // We don't notify the platform on first time setup to avoid changing diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h index 826e851b045..4753bb68643 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h @@ -478,6 +478,21 @@ SdMmcHcStopClock ( IN UINT8 Slot ); +/** + Start the SD clock. + + @param[in] PciIo The PCI IO protocol instance. + @param[in] Slot The slot number. + + @retval EFI_SUCCESS Succeeded to start the SD clock. + @rtval Others Failed to start the SD clock. +**/ +EFI_STATUS +SdMmcHcStartSdClock ( + IN EFI_PCI_IO_PROTOCOL *PciIo, + IN UINT8 Slot + ); + /** SD/MMC bus power control. From df73a69faf34f17b4dcacfc373b0b2621db62bd3 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Mon, 30 Dec 2019 16:36:02 +0800 Subject: [PATCH 255/384] SecurityPkg/Guid: Add TCG 800-155 event GUID definition. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 The PEIM can produce the 800-155 event and the event will be recorded to TCG event log by the TCG2 DXE. Cc: Jian J Wang Cc: Chao Zhang Signed-off-by: Jiewen Yao Reviewed-by: Jian J Wang --- SecurityPkg/Include/Guid/TcgEventHob.h | 11 +++++++++++ SecurityPkg/SecurityPkg.dec | 4 ++++ 2 files changed, 15 insertions(+) diff --git a/SecurityPkg/Include/Guid/TcgEventHob.h b/SecurityPkg/Include/Guid/TcgEventHob.h index eef3f92abdb..97e40b47d0b 100644 --- a/SecurityPkg/Include/Guid/TcgEventHob.h +++ b/SecurityPkg/Include/Guid/TcgEventHob.h @@ -49,4 +49,15 @@ extern EFI_GUID gTpmErrorHobGuid; extern EFI_GUID gTpm2StartupLocalityHobGuid; +/// +/// The Global ID of a GUIDed HOB used to record TCG 800-155 PlatformId Event. +/// HOB payload is the whole TCG_Sp800_155_PlatformId_Event2 according to TCG 800-155 PlatformId Event. +/// +#define EFI_TCG_800_155_PLATFORM_ID_EVENT_HOB_GUID \ + { \ + 0xe2c3bc69, 0x615c, 0x4b5b, { 0x8e, 0x5c, 0xa0, 0x33, 0xa9, 0xc2, 0x5e, 0xd6 } \ + } + +extern EFI_GUID gTcg800155PlatformIdEventHobGuid; + #endif diff --git a/SecurityPkg/SecurityPkg.dec b/SecurityPkg/SecurityPkg.dec index cac36caf0a0..5335cc53973 100644 --- a/SecurityPkg/SecurityPkg.dec +++ b/SecurityPkg/SecurityPkg.dec @@ -121,6 +121,10 @@ ## Include/Guid/TcgEventHob.h gTpm2StartupLocalityHobGuid = { 0x397b0c9, 0x22e8, 0x459e, { 0xa4, 0xff, 0x99, 0xbc, 0x65, 0x27, 0x9, 0x29 }} + ## HOB GUID used to record TCG 800-155 PlatformId Event + ## Include/Guid/TcgEventHob.h + gTcg800155PlatformIdEventHobGuid = { 0xe2c3bc69, 0x615c, 0x4b5b, { 0x8e, 0x5c, 0xa0, 0x33, 0xa9, 0xc2, 0x5e, 0xd6 }} + ## HOB GUID used to pass all PEI measured FV info to DXE Driver. # Include/Guid/MeasuredFvHob.h gMeasuredFvHobGuid = { 0xb2360b42, 0x7173, 0x420a, { 0x86, 0x96, 0x46, 0xca, 0x6b, 0xab, 0x10, 0x60 }} From 4fa25853cdccc1e6bcb613180d730d010f6d6a6b Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Mon, 30 Dec 2019 16:38:38 +0800 Subject: [PATCH 256/384] SecurityPkg/Tcg2Dxe: Add Tcg2Dxe to support 800-155 event. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 The TCG2 DXE supports to parse the 800-155 event GUID from PEI and puts to the beginning of the TCG2 event. The TCG2 DXE also supports a DXE driver produces 800-155 event and let TCG2 DXE driver record. The 800-155 is a NO-ACTION event which does not need extend anything to TPM2. The TCG2 DXE also supports that. Multiple 800-155 events are supported. All of them will be put to the beginning of the TCG2 event, just after the SpecId event. Cc: Jian J Wang Cc: Chao Zhang Signed-off-by: Jiewen Yao Reviewed-by: Jian J Wang --- SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.c | 159 +++++++++++++++++++++++----- SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf | 1 + 2 files changed, 131 insertions(+), 29 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.c b/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.c index 3cd16c2fa33..1fe1955cab8 100644 --- a/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.c +++ b/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.c @@ -75,6 +75,7 @@ typedef struct { UINT8 *LastEvent; BOOLEAN EventLogStarted; BOOLEAN EventLogTruncated; + UINTN Next800155EventOffset; } TCG_EVENT_LOG_AREA_STRUCT; typedef struct _TCG_DXE_DATA { @@ -771,16 +772,43 @@ Tcg2GetEventLog ( return EFI_SUCCESS; } +/* + Return if this is a Tcg800155PlatformIdEvent. + + @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure. + @param[in] NewEventHdrSize New event header size. + @param[in] NewEventData Pointer to the new event data. + @param[in] NewEventSize New event data size. + + @retval TRUE This is a Tcg800155PlatformIdEvent. + @retval FALSE This is NOT a Tcg800155PlatformIdEvent. + +*/ +BOOLEAN +Is800155Event ( + IN VOID *NewEventHdr, + IN UINT32 NewEventHdrSize, + IN UINT8 *NewEventData, + IN UINT32 NewEventSize + ) +{ + if ((((TCG_PCR_EVENT2_HDR *)NewEventHdr)->EventType == EV_NO_ACTION) && + (NewEventSize >= sizeof(TCG_Sp800_155_PlatformId_Event2)) && + (CompareMem (NewEventData, TCG_Sp800_155_PlatformId_Event2_SIGNATURE, + sizeof(TCG_Sp800_155_PlatformId_Event2_SIGNATURE) - 1) == 0)) { + return TRUE; + } + return FALSE; +} + /** Add a new entry to the Event Log. - @param[in, out] EventLogPtr Pointer to the Event Log data. - @param[in, out] LogSize Size of the Event Log. - @param[in] MaxSize Maximum size of the Event Log. - @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure. - @param[in] NewEventHdrSize New event header size. - @param[in] NewEventData Pointer to the new event data. - @param[in] NewEventSize New event data size. + @param[in, out] EventLogAreaStruct The event log area data structure + @param[in] NewEventHdr Pointer to a TCG_PCR_EVENT_HDR/TCG_PCR_EVENT_EX data structure. + @param[in] NewEventHdrSize New event header size. + @param[in] NewEventData Pointer to the new event data. + @param[in] NewEventSize New event data size. @retval EFI_SUCCESS The new event log entry was added. @retval EFI_OUT_OF_RESOURCES No enough memory to log the new event. @@ -788,9 +816,7 @@ Tcg2GetEventLog ( **/ EFI_STATUS TcgCommLogEvent ( - IN OUT UINT8 **EventLogPtr, - IN OUT UINTN *LogSize, - IN UINTN MaxSize, + IN OUT TCG_EVENT_LOG_AREA_STRUCT *EventLogAreaStruct, IN VOID *NewEventHdr, IN UINT32 NewEventHdrSize, IN UINT8 *NewEventData, @@ -798,6 +824,7 @@ TcgCommLogEvent ( ) { UINTN NewLogSize; + BOOLEAN Record800155Event; if (NewEventSize > MAX_ADDRESS - NewEventHdrSize) { return EFI_OUT_OF_RESOURCES; @@ -805,23 +832,55 @@ TcgCommLogEvent ( NewLogSize = NewEventHdrSize + NewEventSize; - if (NewLogSize > MAX_ADDRESS - *LogSize) { + if (NewLogSize > MAX_ADDRESS - EventLogAreaStruct->EventLogSize) { return EFI_OUT_OF_RESOURCES; } - if (NewLogSize + *LogSize > MaxSize) { - DEBUG ((EFI_D_INFO, " MaxSize - 0x%x\n", MaxSize)); - DEBUG ((EFI_D_INFO, " NewLogSize - 0x%x\n", NewLogSize)); - DEBUG ((EFI_D_INFO, " LogSize - 0x%x\n", *LogSize)); - DEBUG ((EFI_D_INFO, "TcgCommLogEvent - %r\n", EFI_OUT_OF_RESOURCES)); + if (NewLogSize + EventLogAreaStruct->EventLogSize > EventLogAreaStruct->Laml) { + DEBUG ((DEBUG_INFO, " Laml - 0x%x\n", EventLogAreaStruct->Laml)); + DEBUG ((DEBUG_INFO, " NewLogSize - 0x%x\n", NewLogSize)); + DEBUG ((DEBUG_INFO, " LogSize - 0x%x\n", EventLogAreaStruct->EventLogSize)); + DEBUG ((DEBUG_INFO, "TcgCommLogEvent - %r\n", EFI_OUT_OF_RESOURCES)); return EFI_OUT_OF_RESOURCES; } - *EventLogPtr += *LogSize; - *LogSize += NewLogSize; - CopyMem (*EventLogPtr, NewEventHdr, NewEventHdrSize); + // + // Check 800-155 event + // Record to 800-155 event offset only. + // If the offset is 0, no need to record. + // + Record800155Event = Is800155Event (NewEventHdr, NewEventHdrSize, NewEventData, NewEventSize); + if (Record800155Event) { + if (EventLogAreaStruct->Next800155EventOffset != 0) { + CopyMem ( + (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset + NewLogSize, + (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset, + EventLogAreaStruct->EventLogSize - EventLogAreaStruct->Next800155EventOffset + ); + + CopyMem ( + (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset, + NewEventHdr, + NewEventHdrSize + ); + CopyMem ( + (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->Next800155EventOffset + NewEventHdrSize, + NewEventData, + NewEventSize + ); + + EventLogAreaStruct->Next800155EventOffset += NewLogSize; + EventLogAreaStruct->LastEvent += NewLogSize; + EventLogAreaStruct->EventLogSize += NewLogSize; + } + return EFI_SUCCESS; + } + + EventLogAreaStruct->LastEvent = (UINT8 *)(UINTN)EventLogAreaStruct->Lasa + EventLogAreaStruct->EventLogSize; + EventLogAreaStruct->EventLogSize += NewLogSize; + CopyMem (EventLogAreaStruct->LastEvent, NewEventHdr, NewEventHdrSize); CopyMem ( - *EventLogPtr + NewEventHdrSize, + EventLogAreaStruct->LastEvent + NewEventHdrSize, NewEventData, NewEventSize ); @@ -873,11 +932,8 @@ TcgDxeLogEvent ( return EFI_VOLUME_FULL; } - EventLogAreaStruct->LastEvent = (UINT8*)(UINTN)EventLogAreaStruct->Lasa; Status = TcgCommLogEvent ( - &EventLogAreaStruct->LastEvent, - &EventLogAreaStruct->EventLogSize, - (UINTN)EventLogAreaStruct->Laml, + EventLogAreaStruct, NewEventHdr, NewEventHdrSize, NewEventData, @@ -907,11 +963,8 @@ TcgDxeLogEvent ( return EFI_VOLUME_FULL; } - EventLogAreaStruct->LastEvent = (UINT8*)(UINTN)EventLogAreaStruct->Lasa; Status = TcgCommLogEvent ( - &EventLogAreaStruct->LastEvent, - &EventLogAreaStruct->EventLogSize, - (UINTN)EventLogAreaStruct->Laml, + EventLogAreaStruct, NewEventHdr, NewEventHdrSize, NewEventData, @@ -1138,11 +1191,25 @@ TcgDxeHashLogExtendEvent ( { EFI_STATUS Status; TPML_DIGEST_VALUES DigestList; + TCG_PCR_EVENT2_HDR NoActionEvent; if (!mTcgDxeData.BsCap.TPMPresentFlag) { return EFI_DEVICE_ERROR; } + if (NewEventHdr->EventType == EV_NO_ACTION) { + // + // Do not do TPM extend for EV_NO_ACTION + // + Status = EFI_SUCCESS; + InitNoActionEvent (&NoActionEvent, NewEventHdr->EventSize); + if ((Flags & EFI_TCG2_EXTEND_ONLY) == 0) { + Status = TcgDxeLogHashEvent (&(NoActionEvent.Digests), NewEventHdr, NewEventData); + } + + return Status; + } + Status = HashAndExtend ( NewEventHdr->PCRIndex, HashData, @@ -1202,7 +1269,13 @@ Tcg2HashLogExtendEvent ( DEBUG ((DEBUG_VERBOSE, "Tcg2HashLogExtendEvent ...\n")); - if ((This == NULL) || (DataToHash == 0) || (Event == NULL)) { + if ((This == NULL) || (Event == NULL)) { + return EFI_INVALID_PARAMETER; + } + // + // Do not check hash data size for EV_NO_ACTION event. + // + if ((Event->Header.EventType != EV_NO_ACTION) && (DataToHash == 0)) { return EFI_INVALID_PARAMETER; } @@ -1487,6 +1560,7 @@ SetupEventLog ( } mTcgDxeData.EventLogAreaStruct[Index].Lasa = Lasa; mTcgDxeData.EventLogAreaStruct[Index].Laml = PcdGet32 (PcdTcgLogAreaMinLen); + mTcgDxeData.EventLogAreaStruct[Index].Next800155EventOffset = 0; if ((PcdGet8(PcdTpm2AcpiTableRev) >= 4) || (mTcg2EventInfo[Index].LogFormat == EFI_TCG2_EVENT_LOG_FORMAT_TCG_2)) { @@ -1577,6 +1651,31 @@ SetupEventLog ( (UINT8 *)TcgEfiSpecIdEventStruct, SpecIdEvent.EventSize ); + // + // record the offset at the end of 800-155 event. + // the future 800-155 event can be inserted here. + // + mTcgDxeData.EventLogAreaStruct[Index].Next800155EventOffset = \ + mTcgDxeData.EventLogAreaStruct[Index].EventLogSize; + + // + // Tcg800155PlatformIdEvent. Event format is TCG_PCR_EVENT2 + // + GuidHob.Guid = GetFirstGuidHob (&gTcg800155PlatformIdEventHobGuid); + while (GuidHob.Guid != NULL) { + InitNoActionEvent(&NoActionEvent, GET_GUID_HOB_DATA_SIZE (GuidHob.Guid)); + + Status = TcgDxeLogEvent ( + mTcg2EventInfo[Index].LogFormat, + &NoActionEvent, + sizeof(NoActionEvent.PCRIndex) + sizeof(NoActionEvent.EventType) + GetDigestListBinSize (&NoActionEvent.Digests) + sizeof(NoActionEvent.EventSize), + GET_GUID_HOB_DATA (GuidHob.Guid), + GET_GUID_HOB_DATA_SIZE (GuidHob.Guid) + ); + + GuidHob.Guid = GET_NEXT_HOB (GuidHob); + GuidHob.Guid = GetNextGuidHob (&gTcg800155PlatformIdEventHobGuid, GuidHob.Guid); + } // // EfiStartupLocalityEvent. Event format is TCG_PCR_EVENT2 @@ -1643,6 +1742,7 @@ SetupEventLog ( mTcgDxeData.FinalEventLogAreaStruct[Index].LastEvent = (VOID *)(UINTN)mTcgDxeData.FinalEventLogAreaStruct[Index].Lasa; mTcgDxeData.FinalEventLogAreaStruct[Index].EventLogStarted = FALSE; mTcgDxeData.FinalEventLogAreaStruct[Index].EventLogTruncated = FALSE; + mTcgDxeData.FinalEventLogAreaStruct[Index].Next800155EventOffset = 0; // // Install to configuration table for EFI_TCG2_EVENT_LOG_FORMAT_TCG_2 @@ -1663,6 +1763,7 @@ SetupEventLog ( mTcgDxeData.FinalEventLogAreaStruct[Index].LastEvent = 0; mTcgDxeData.FinalEventLogAreaStruct[Index].EventLogStarted = FALSE; mTcgDxeData.FinalEventLogAreaStruct[Index].EventLogTruncated = FALSE; + mTcgDxeData.FinalEventLogAreaStruct[Index].Next800155EventOffset = 0; } } } diff --git a/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf b/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf index 0127a31e970..576cf80d06d 100644 --- a/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf +++ b/SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf @@ -85,6 +85,7 @@ gTcgEvent2EntryHobGuid ## SOMETIMES_CONSUMES ## HOB gTpm2StartupLocalityHobGuid ## SOMETIMES_CONSUMES ## HOB + gTcg800155PlatformIdEventHobGuid ## SOMETIMES_CONSUMES ## HOB [Protocols] gEfiTcg2ProtocolGuid ## PRODUCES From f27390516198b7a39bf1d306327a6b4334788390 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Tue, 31 Dec 2019 09:02:52 +0800 Subject: [PATCH 257/384] MdeModulePkg/Smbios: Done measure Smbios multiple times. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 In current implementation, the SMBIOS table is measured multiple time in every readytoboot event. This causes Smbios Table record appears multiple time in the TCG event log and confuses people. This issue makes it hard to implement 800-155 reference measurement. This patch closes the event to make sure Smbios is measured only once. Cc: Jian J Wang Cc: Hao A Wu Cc: Dandan Bi Cc: Star Zeng Signed-off-by: Jiewen Yao Reviewed-by: Star Zeng --- .../Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c index 7b5d4731466..5ec2aca0953 100644 --- a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c +++ b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c @@ -577,8 +577,8 @@ MeasureSmbiosTable ( TableAddress, // HashData TableLength // HashDataLen ); - if (EFI_ERROR (Status)) { - return ; + if (!EFI_ERROR (Status)) { + gBS->CloseEvent (Event) ; } } From 166830d8f7cad21886f7bf4c65a3dcc66b530be5 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Tue, 31 Dec 2019 09:45:27 +0800 Subject: [PATCH 258/384] MdeModulePkg/dec: add PcdTcgPfpMeasurementRevision PCD REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 This PCD is to control the TCG PFP spec revision. The PFP 105 added new event type to support NIST SP800-155, and deprecated old event type. Cc: Jian J Wang Cc: Hao A Wu Cc: Chao Zhang Signed-off-by: Jiewen Yao Reviewed-by: Jian J Wang --- MdeModulePkg/MdeModulePkg.dec | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index 41b9e70a1ac..f75a74af256 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -2003,6 +2003,14 @@ # @Prompt Capsule On Disk relocation device path. gEfiMdeModulePkgTokenSpaceGuid.PcdCodRelocationDevPath|{0xFF}|VOID*|0x0000002f + ## Indicates which TCG Platform Firmware Profile revision the EDKII firmware follows. + # The revision number is defined in MdePkg/Include/IndustryStandard/UefiTcgPlatform.h + # 0: This is for compatiblity support. + # 105: This is the first revision to support 800-155 is related event, such as + # EV_EFI_PLATFORM_FIRMWARE_BLOB2 and EV_EFI_HANDOFF_TABLES2. + # @Prompt TCG Platform Firmware Profile revision. + gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision|0|UINT32|0x00010077 + [PcdsPatchableInModule] ## Specify memory size with page number for PEI code when # Loading Module at Fixed Address feature is enabled. From 40801ac995c2153331eb3ea1ad658556849d3bae Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Tue, 31 Dec 2019 09:47:11 +0800 Subject: [PATCH 259/384] MdeModulePkg/Smbios: Add TCG PFP rev 105 support. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 Report EV_EFI_HANDOFF_TABLES2 if the platform chooses PFP >= 105. Cc: Jian J Wang Cc: Hao A Wu Cc: Dandan Bi Cc: Star Zeng Signed-off-by: Jiewen Yao Reviewed-by: Star Zeng --- .../SmbiosMeasurementDxe.c | 38 +++++++++++++++++-- .../SmbiosMeasurementDxe.inf | 6 ++- 2 files changed, 39 insertions(+), 5 deletions(-) diff --git a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c index 5ec2aca0953..1050c9b17b8 100644 --- a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c +++ b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.c @@ -1,7 +1,7 @@ /** @file This driver measures SMBIOS table to TPM. -Copyright (c) 2015 - 2017, Intel Corporation. All rights reserved.
+Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -20,6 +20,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #define FIELD_SIZE_OF(TYPE, Field) ((UINTN)sizeof(((TYPE *)0)->Field)) @@ -108,6 +109,18 @@ SMBIOS_FILTER_STRUCT mSmbiosFilterStandardTableBlackList[] = { EFI_SMBIOS_PROTOCOL *mSmbios; UINTN mMaxLen; +#pragma pack (1) + +#define SMBIOS_HANDOFF_TABLE_DESC "SmbiosTable" +typedef struct { + UINT8 TableDescriptionSize; + UINT8 TableDescription[sizeof(SMBIOS_HANDOFF_TABLE_DESC)]; + UINT64 NumberOfTables; + EFI_CONFIGURATION_TABLE TableEntry[1]; +} SMBIOS_HANDOFF_TABLE_POINTERS2; + +#pragma pack () + /** This function dump raw data. @@ -460,6 +473,10 @@ MeasureSmbiosTable ( { EFI_STATUS Status; EFI_HANDOFF_TABLE_POINTERS HandoffTables; + SMBIOS_HANDOFF_TABLE_POINTERS2 SmbiosHandoffTables2; + UINT32 EventType; + VOID *EventLog; + UINT32 EventLogSize; SMBIOS_TABLE_ENTRY_POINT *SmbiosTable; SMBIOS_TABLE_3_0_ENTRY_POINT *Smbios3Table; VOID *SmbiosTableAddress; @@ -569,11 +586,24 @@ MeasureSmbiosTable ( CopyGuid (&(HandoffTables.TableEntry[0].VendorGuid), &gEfiSmbiosTableGuid); HandoffTables.TableEntry[0].VendorTable = SmbiosTable; } + EventType = EV_EFI_HANDOFF_TABLES; + EventLog = &HandoffTables; + EventLogSize = sizeof (HandoffTables); + + if (PcdGet32(PcdTcgPfpMeasurementRevision) >= TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2_REV_105) { + SmbiosHandoffTables2.TableDescriptionSize = sizeof(SmbiosHandoffTables2.TableDescription); + CopyMem (SmbiosHandoffTables2.TableDescription, SMBIOS_HANDOFF_TABLE_DESC, sizeof(SmbiosHandoffTables2.TableDescription)); + SmbiosHandoffTables2.NumberOfTables = HandoffTables.NumberOfTables; + CopyMem (&(SmbiosHandoffTables2.TableEntry[0]), &(HandoffTables.TableEntry[0]), sizeof(SmbiosHandoffTables2.TableEntry[0])); + EventType = EV_EFI_HANDOFF_TABLES2; + EventLog = &SmbiosHandoffTables2; + EventLogSize = sizeof (SmbiosHandoffTables2); + } Status = TpmMeasureAndLogData ( 1, // PCRIndex - EV_EFI_HANDOFF_TABLES, // EventType - &HandoffTables, // EventLog - sizeof (HandoffTables), // LogLen + EventType, // EventType + EventLog, // EventLog + EventLogSize, // LogLen TableAddress, // HashData TableLength // HashDataLen ); diff --git a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.inf b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.inf index a074044c848..7537bfb519a 100644 --- a/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.inf +++ b/MdeModulePkg/Universal/SmbiosMeasurementDxe/SmbiosMeasurementDxe.inf @@ -11,7 +11,7 @@ # # A platform may use its own policy to filter some fields in SMBIOS table. # -# Copyright (c) 2015 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -48,6 +48,7 @@ UefiLib UefiDriverEntryPoint DebugLib + PcdLib TpmMeasurementLib [Protocols] @@ -57,6 +58,9 @@ gEfiSmbiosTableGuid ## SOMETIMES_CONSUMES ## SystemTable gEfiSmbios3TableGuid ## SOMETIMES_CONSUMES ## SystemTable +[Pcd] + gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision ## CONSUMES + [Depex] gEfiSmbiosProtocolGuid From 0286fe8176375feaf4af5ac24f8dc46284451ad5 Mon Sep 17 00:00:00 2001 From: Jiewen Yao Date: Tue, 31 Dec 2019 10:37:30 +0800 Subject: [PATCH 260/384] SecurityPkg/Tcg2Pei: Add TCG PFP 105 support. REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2439 Use EV_EFI_PLATFORM_FIRMWARE_BLOB2 if the TCG PFP revision is >= 105. Use FvName as the description for the FV. Cc: Jian J Wang Cc: Chao Zhang Signed-off-by: Jiewen Yao Reviewed-by: Jian J Wang --- SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c | 101 ++++++++++++++++++++++++---- SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf | 2 + 2 files changed, 89 insertions(+), 14 deletions(-) diff --git a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c index 1565d4e4021..3788063cc9e 100644 --- a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c +++ b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.c @@ -37,6 +37,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #define PERF_ID_TCG2_PEI 0x3080 @@ -78,6 +79,18 @@ EFI_PLATFORM_FIRMWARE_BLOB *mMeasuredChildFvInfo; UINT32 mMeasuredMaxChildFvIndex = 0; UINT32 mMeasuredChildFvIndex = 0; +#pragma pack (1) + +#define FV_HANDOFF_TABLE_DESC "Fv(XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX)" +typedef struct { + UINT8 BlobDescriptionSize; + UINT8 BlobDescription[sizeof(FV_HANDOFF_TABLE_DESC)]; + EFI_PHYSICAL_ADDRESS BlobBase; + UINT64 BlobLength; +} FV_HANDOFF_TABLE_POINTERS2; + +#pragma pack () + /** Measure and record the Firmware Volume Information once FvInfoPPI install. @@ -447,6 +460,48 @@ MeasureCRTMVersion ( ); } +/* + Get the FvName from the FV header. + + Causion: The FV is untrusted input. + + @param[in] FvBase Base address of FV image. + @param[in] FvLength Length of FV image. + + @return FvName pointer + @retval NULL FvName is NOT found +*/ +VOID * +GetFvName ( + IN EFI_PHYSICAL_ADDRESS FvBase, + IN UINT64 FvLength + ) +{ + EFI_FIRMWARE_VOLUME_HEADER *FvHeader; + EFI_FIRMWARE_VOLUME_EXT_HEADER *FvExtHeader; + + if (FvBase >= MAX_ADDRESS) { + return NULL; + } + if (FvLength >= MAX_ADDRESS - FvBase) { + return NULL; + } + if (FvLength < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) { + return NULL; + } + + FvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvBase; + if (FvHeader->ExtHeaderOffset < sizeof(EFI_FIRMWARE_VOLUME_HEADER)) { + return NULL; + } + if (FvHeader->ExtHeaderOffset + sizeof(EFI_FIRMWARE_VOLUME_EXT_HEADER) > FvLength) { + return NULL; + } + FvExtHeader = (EFI_FIRMWARE_VOLUME_EXT_HEADER *)(UINTN)(FvBase + FvHeader->ExtHeaderOffset); + + return &FvExtHeader->FvName; +} + /** Measure FV image. Add it into the measured FV list after the FV is measured successfully. @@ -469,6 +524,9 @@ MeasureFvImage ( UINT32 Index; EFI_STATUS Status; EFI_PLATFORM_FIRMWARE_BLOB FvBlob; + FV_HANDOFF_TABLE_POINTERS2 FvBlob2; + VOID *EventData; + VOID *FvName; TCG_PCR_EVENT_HDR TcgEventHdr; UINT32 Instance; UINT32 Tpm2HashMask; @@ -566,11 +624,26 @@ MeasureFvImage ( // // Init the log event for FV measurement // - FvBlob.BlobBase = FvBase; - FvBlob.BlobLength = FvLength; - TcgEventHdr.PCRIndex = 0; - TcgEventHdr.EventType = EV_EFI_PLATFORM_FIRMWARE_BLOB; - TcgEventHdr.EventSize = sizeof (FvBlob); + if (PcdGet32(PcdTcgPfpMeasurementRevision) >= TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2_REV_105) { + FvBlob2.BlobDescriptionSize = sizeof(FvBlob2.BlobDescription); + CopyMem (FvBlob2.BlobDescription, FV_HANDOFF_TABLE_DESC, sizeof(FvBlob2.BlobDescription)); + FvName = GetFvName (FvBase, FvLength); + if (FvName != NULL) { + AsciiSPrint ((CHAR8 *)FvBlob2.BlobDescription, sizeof(FvBlob2.BlobDescription), "Fv(%g)", FvName); + } + FvBlob2.BlobBase = FvBase; + FvBlob2.BlobLength = FvLength; + TcgEventHdr.EventType = EV_EFI_PLATFORM_FIRMWARE_BLOB2; + TcgEventHdr.EventSize = sizeof (FvBlob2); + EventData = &FvBlob2; + } else { + FvBlob.BlobBase = FvBase; + FvBlob.BlobLength = FvLength; + TcgEventHdr.PCRIndex = 0; + TcgEventHdr.EventType = EV_EFI_PLATFORM_FIRMWARE_BLOB; + TcgEventHdr.EventSize = sizeof (FvBlob); + EventData = &FvBlob; + } if (Tpm2HashMask == 0) { // @@ -583,9 +656,9 @@ MeasureFvImage ( ); if (!EFI_ERROR(Status)) { - Status = LogHashEvent (&DigestList, &TcgEventHdr, (UINT8*) &FvBlob); - DEBUG ((DEBUG_INFO, "The pre-hashed FV which is extended & logged by Tcg2Pei starts at: 0x%x\n", FvBlob.BlobBase)); - DEBUG ((DEBUG_INFO, "The pre-hashed FV which is extended & logged by Tcg2Pei has the size: 0x%x\n", FvBlob.BlobLength)); + Status = LogHashEvent (&DigestList, &TcgEventHdr, EventData); + DEBUG ((DEBUG_INFO, "The pre-hashed FV which is extended & logged by Tcg2Pei starts at: 0x%x\n", FvBase)); + DEBUG ((DEBUG_INFO, "The pre-hashed FV which is extended & logged by Tcg2Pei has the size: 0x%x\n", FvLength)); } else if (Status == EFI_DEVICE_ERROR) { BuildGuidHob (&gTpmErrorHobGuid,0); REPORT_STATUS_CODE ( @@ -599,13 +672,13 @@ MeasureFvImage ( // Status = HashLogExtendEvent ( 0, - (UINT8*) (UINTN) FvBlob.BlobBase, - (UINTN) FvBlob.BlobLength, - &TcgEventHdr, - (UINT8*) &FvBlob + (UINT8*) (UINTN) FvBase, // HashData + (UINTN) FvLength, // HashDataLen + &TcgEventHdr, // EventHdr + EventData // EventData ); - DEBUG ((DEBUG_INFO, "The FV which is measured by Tcg2Pei starts at: 0x%x\n", FvBlob.BlobBase)); - DEBUG ((DEBUG_INFO, "The FV which is measured by Tcg2Pei has the size: 0x%x\n", FvBlob.BlobLength)); + DEBUG ((DEBUG_INFO, "The FV which is measured by Tcg2Pei starts at: 0x%x\n", FvBase)); + DEBUG ((DEBUG_INFO, "The FV which is measured by Tcg2Pei has the size: 0x%x\n", FvLength)); } if (EFI_ERROR(Status)) { diff --git a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf index 30f985b6eac..3d361e8859e 100644 --- a/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf +++ b/SecurityPkg/Tcg/Tcg2Pei/Tcg2Pei.inf @@ -54,6 +54,7 @@ MemoryAllocationLib ReportStatusCodeLib ResetSystemLib + PrintLib [Guids] gTcgEventEntryHobGuid ## PRODUCES ## HOB @@ -74,6 +75,7 @@ [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdFirmwareVersionString ## SOMETIMES_CONSUMES + gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTpm2InitializationPolicy ## CONSUMES gEfiSecurityPkgTokenSpaceGuid.PcdTpm2SelfTestPolicy ## SOMETIMES_CONSUMES From f9c2c71ed69ca1d92687a55d3ef947cfb4413b3e Mon Sep 17 00:00:00 2001 From: MrChromebox Date: Mon, 6 Jan 2020 12:12:05 +0800 Subject: [PATCH 261/384] MdeModulePkg/Usb/EfiKey: Fix endpoint selection The endpoint selected by the driver needs to not only be an interrupt type, but have direction IN as required to set up an asynchronous interrupt transfer. Currently, the driver assumes that the first INT endpoint will be of type IN, but that is not true of all devices, and will silently fail on devices which have the OUT endpoint before the IN. Adjust the endpoint selection loop to explictly check for direction IN. Test: detachable keyboard on Google Pixel Slate now works. Signed-off-by: Matt DeVillier Reviewed-by: GuoMinJ Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c index 27685995c23..ccb389067a6 100644 --- a/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c +++ b/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c @@ -215,7 +215,7 @@ USBKeyboardDriverBindingStart ( EndpointNumber = UsbKeyboardDevice->InterfaceDescriptor.NumEndpoints; // - // Traverse endpoints to find interrupt endpoint + // Traverse endpoints to find interrupt endpoint IN // Found = FALSE; for (Index = 0; Index < EndpointNumber; Index++) { @@ -226,7 +226,8 @@ USBKeyboardDriverBindingStart ( &EndpointDescriptor ); - if ((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) { + if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { // // We only care interrupt endpoint here // From d0d38ce20ec9d4ef267433bbe8364c43ac1a2278 Mon Sep 17 00:00:00 2001 From: MrChromebox Date: Mon, 6 Jan 2020 12:12:06 +0800 Subject: [PATCH 262/384] MdeModulePkg/Usb/UsbMouse: Fix endpoint selection The endpoint selected by the driver needs to not only be an interrupt type, but have direction IN as required to set up an asynchronous interrupt transfer. Currently, the driver assumes that the first INT endpoint will be of type IN, but that is not true of all devices, and will silently fail on devices which have the OUT endpoint before the IN. Adjust the endpoint selection loop to explictly check for direction IN. Signed-off-by: Matt DeVillier Reviewed-by: GuoMinJ Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c index 677815a8ade..143ff15eb03 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseDxe/UsbMouse.c @@ -203,7 +203,7 @@ USBMouseDriverBindingStart ( EndpointNumber = UsbMouseDevice->InterfaceDescriptor.NumEndpoints; // - // Traverse endpoints to find interrupt endpoint + // Traverse endpoints to find interrupt endpoint IN // Found = FALSE; for (Index = 0; Index < EndpointNumber; Index++) { @@ -213,7 +213,8 @@ USBMouseDriverBindingStart ( &EndpointDescriptor ); - if ((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) { + if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { // // We only care interrupt endpoint here // From 6cfb6da9518d3c48107c26832e2709cfd92bf9fa Mon Sep 17 00:00:00 2001 From: MrChromebox Date: Mon, 6 Jan 2020 12:12:07 +0800 Subject: [PATCH 263/384] MdeModulePkg/UsbMouseAbsolutePointer: Fix endpoint selection The endpoint selected by the driver needs to not only be an interrupt type, but have direction IN as required to set up an asynchronous interrupt transfer. Currently, the driver assumes that the first INT endpoint will be of type IN, but that is not true of all devices, and will silently fail on devices which have the OUT endpoint before the IN. Adjust the endpoint selection loop to explictly check for direction IN. Signed-off-by: Matt DeVillier Reviewed-by: Hao A Wu --- .../Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c index 8953e7031cf..9cd0e4cd535 100644 --- a/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c +++ b/MdeModulePkg/Bus/Usb/UsbMouseAbsolutePointerDxe/UsbMouseAbsolutePointer.c @@ -203,7 +203,7 @@ USBMouseAbsolutePointerDriverBindingStart ( EndpointNumber = UsbMouseAbsolutePointerDevice->InterfaceDescriptor.NumEndpoints; // - // Traverse endpoints to find interrupt endpoint + // Traverse endpoints to find interrupt endpoint IN // Found = FALSE; for (Index = 0; Index < EndpointNumber; Index++) { @@ -213,7 +213,8 @@ USBMouseAbsolutePointerDriverBindingStart ( &EndpointDescriptor ); - if ((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) { + if (((EndpointDescriptor.Attributes & (BIT0 | BIT1)) == USB_ENDPOINT_INTERRUPT) && + ((EndpointDescriptor.EndpointAddress & USB_ENDPOINT_DIR_IN) != 0)) { // // We only care interrupt endpoint here // From 4a1aeca3bd02d04e01c2d4102057b8cb4357ec17 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:44 +0100 Subject: [PATCH 264/384] .mailmap: Add a stub with documentation The .mailmap git feature helps fixing commit mistakes (in name/email). The easiest way to use it is with the --use-mailmap flag: $ git log --use-mailmap See: * https://git-scm.com/docs/git-shortlog#_mapping_authors * https://git-scm.com/docs/git-check-mailmap#_mapping_authors Reviewed-by: Laszlo Ersek Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-2-philmd@redhat.com> --- .mailmap | 11 +++++++++++ 1 file changed, 11 insertions(+) create mode 100644 .mailmap diff --git a/.mailmap b/.mailmap new file mode 100644 index 00000000000..6d88189a58d --- /dev/null +++ b/.mailmap @@ -0,0 +1,11 @@ +# +# This list is used by git-shortlog to fix a few botched name translations +# in the git archive, either because the author's full name was messed up +# and/or not always written the same way, making contributions from the +# same person appearing not to be so or badly displayed. +# +# Please keep this file sorted alphabetically, and email in lowercase. +# The format used is: +# +# Firstname Lastname +# From ba5410320babf5fe712ec825a18191cfc77b35ad Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:45 +0100 Subject: [PATCH 265/384] .mailmap: Add an entry for Aaron Li We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Aaron Li to have his/her name and email address displayed properly in the git history. Cc: Aaron Li Cc: Songpeng Li Reviewed-by: Aaron Li Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-3-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 6d88189a58d..595ce337714 100644 --- a/.mailmap +++ b/.mailmap @@ -9,3 +9,5 @@ # # Firstname Lastname # + +Aaron Li From 0ce7f25fe3aae1a19a01456b8bb35f10f468e147 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:46 +0100 Subject: [PATCH 266/384] .mailmap: Add an entry for Antoine Coeur MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Antoine Cœur to have his/her name and email address displayed properly in the git history. Cc: Antoine Cœur Reviewed-by: Antoine Cœur Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-4-philmd@redhat.com> [lersek@redhat.com: fix up valid PatchCheck.py error in Reviewed-by] [lersek@redhat.com: translit subject to ASCII to suppress PatchCheck.py] --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 595ce337714..03ed977984b 100644 --- a/.mailmap +++ b/.mailmap @@ -11,3 +11,5 @@ # Aaron Li +Antoine Cœur +Antoine Cœur From 83e78feb8092ce274dcbbf391a1f79f490e31690 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:47 +0100 Subject: [PATCH 267/384] .mailmap: Add an entry for Ard Biesheuvel We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Ard Biesheuvel to have his/her name and email address displayed properly in the git history. Cc: Ard Biesheuvel Reviewed-by: Ard Biesheuvel Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-5-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 03ed977984b..491fcffeb95 100644 --- a/.mailmap +++ b/.mailmap @@ -13,3 +13,4 @@ Aaron Li Antoine Cœur Antoine Cœur +Ard Biesheuvel From caa6584f36bc7a71748e78cd0b615175a5648524 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:48 +0100 Subject: [PATCH 268/384] .mailmap: Add an entry for Ashley DeSimone We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Ashley DeSimone to have his/her name and email address displayed properly in the git history. Cc: Ashley DeSimone Reviewed-by: Ashley DeSimone Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-6-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 491fcffeb95..d054b07effa 100644 --- a/.mailmap +++ b/.mailmap @@ -14,3 +14,4 @@ Aaron Li Antoine Cœur Antoine Cœur Ard Biesheuvel +Ashley DeSimone From d42046e1da9424111b7777be5f8ea9809cc4680c Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:49 +0100 Subject: [PATCH 269/384] .mailmap: Add an entry for Baraneedharan Anbazhagan We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Baraneedharan Anbazhagan to have his/her name and email address displayed properly in the git history. Cc: Baraneedharan Anbazhagan Reviewed-by: Baraneedharan Anbazhagan Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-7-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index d054b07effa..35fbb78c6b4 100644 --- a/.mailmap +++ b/.mailmap @@ -15,3 +15,4 @@ Antoine Cœur Antoine Cœur Ard Biesheuvel Ashley DeSimone +Baraneedharan Anbazhagan From 31d60b9ba44230669d0e7adeff1119f41fe8b363 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:50 +0100 Subject: [PATCH 270/384] .mailmap: Add an entry for Chasel Chiu We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Chasel Chiu to have his/her name and email address displayed properly in the git history. Cc: Chasel Chiu Reviewed-by: Chasel Chiu Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-8-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 35fbb78c6b4..8f351b59ea7 100644 --- a/.mailmap +++ b/.mailmap @@ -16,3 +16,4 @@ Antoine Cœur Ard Biesheuvel Ashley DeSimone Baraneedharan Anbazhagan +Chasel Chiu From 0d141df465c91410ffdede2619b6d924b4660f0b Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:51 +0100 Subject: [PATCH 271/384] .mailmap: Add an entry for Christopher J Zurcher We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Christopher J Zurcher to have his/her name and email address displayed properly in the git history. Cc: Christopher J Zurcher Reviewed-by: Christopher J Zurcher Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-9-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 8f351b59ea7..b05d1501e18 100644 --- a/.mailmap +++ b/.mailmap @@ -17,3 +17,4 @@ Ard Biesheuvel Ashley DeSimone Baraneedharan Anbazhagan Chasel Chiu +Christopher J Zurcher From 52b6a7c88940c71e5fd1194ad6c05b3e8e59a734 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:52 +0100 Subject: [PATCH 272/384] .mailmap: Add an entry for Eric Dong We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Eric Dong to have his/her name and email address displayed properly in the git history. Cc: Eric Dong Reviewed-by: Eric Dong Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-10-philmd@redhat.com> --- .mailmap | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.mailmap b/.mailmap index b05d1501e18..28c01bdfcd7 100644 --- a/.mailmap +++ b/.mailmap @@ -18,3 +18,7 @@ Ashley DeSimone Chasel Chiu Christopher J Zurcher +Eric Dong +Eric Dong Eric Dong +Eric Dong +Eric Dong From e2a8eaec0fbc30ef435c70ace72a9ce9c7bec88b Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:53 +0100 Subject: [PATCH 273/384] .mailmap: Add an entry for Erik Bjorge We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Erik Bjorge to have his/her name and email address displayed properly in the git history. Cc: Erik Bjorge Reviewed-by: Erik Bjorge Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-11-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 28c01bdfcd7..732d7a99f84 100644 --- a/.mailmap +++ b/.mailmap @@ -22,3 +22,4 @@ Eric Dong Eric Dong Eric Dong Eric Dong Eric Dong +Erik Bjorge From 082208a8495eb18ba91c5376de51f0ce7a91aacd Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:54 +0100 Subject: [PATCH 274/384] .mailmap: Add an entry for Hao Wu We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Hao Wu to have his/her name and email address displayed properly in the git history. Cc: Hao Wu Reviewed-by: Hao A Wu Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-12-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 732d7a99f84..cc94d92461c 100644 --- a/.mailmap +++ b/.mailmap @@ -23,3 +23,5 @@ Eric Dong Eric Dong Eric Dong Eric Dong Erik Bjorge +Hao A Wu +Hao A Wu From 59bbab3a9a34213f4e279719e69e83ebb8bfd3f6 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:55 +0100 Subject: [PATCH 275/384] .mailmap: Add an entry for Hot Tian We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Hot Tian to have his/her name and email address displayed properly in the git history. Cc: Hot Tian Reviewed-by: Hot Tian Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-13-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index cc94d92461c..82d202841d9 100644 --- a/.mailmap +++ b/.mailmap @@ -25,3 +25,5 @@ Eric Dong Erik Bjorge Hao A Wu Hao A Wu +Hot Tian +Hot Tian From 1bbbd6a79d29bb4fb7e43dfb4e513a04c0f6993a Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:56 +0100 Subject: [PATCH 276/384] .mailmap: Add an entry for Jiewen Yao We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Jiewen Yao to have his/her name and email address displayed properly in the git history. Cc: Jiewen Yao Reviewed-by: Jiewen Yao Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-14-philmd@redhat.com> --- .mailmap | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/.mailmap b/.mailmap index 82d202841d9..566bd0e8135 100644 --- a/.mailmap +++ b/.mailmap @@ -27,3 +27,9 @@ Hao A Wu Hao A Wu Hot Tian Hot Tian +Jiewen Yao +Jiewen Yao +Jiewen Yao +Jiewen Yao +Jiewen Yao +Jiewen Yao From 5556529b949336638976776e11b3da8825a7fa59 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:57 +0100 Subject: [PATCH 277/384] .mailmap: Add an entry for Jim Dailey We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Jim Dailey to have his/her name and email address displayed properly in the git history. Cc: Jim Dailey Reviewed-by: Jim Dailey Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-15-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 566bd0e8135..1b936f892e7 100644 --- a/.mailmap +++ b/.mailmap @@ -33,3 +33,5 @@ Jiewen Yao Jiewen Yao Jiewen Yao Jiewen Yao +Jim Dailey +Jim Dailey From f235838f58b9885da4174fc44294fc37301bdabc Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:58 +0100 Subject: [PATCH 278/384] .mailmap: Add an entry for Laszlo Ersek We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Laszlo Ersek to have his/her name and email address displayed properly in the git history. Cc: Laszlo Ersek Reviewed-by: Laszlo Ersek Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-16-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 1b936f892e7..48e4ca43b5f 100644 --- a/.mailmap +++ b/.mailmap @@ -35,3 +35,5 @@ Jiewen Yao Jiewen Yao Jim Dailey Jim Dailey +Laszlo Ersek +Laszlo Ersek From 44c9a93948de8b2c8ebd95fceb243e5b0f80fae1 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:53:59 +0100 Subject: [PATCH 279/384] .mailmap: Add an entry for Liming Gao We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Liming Gao to have his/her name and email address displayed properly in the git history. Cc: Liming Gao Reviewed-by: Liming Gao Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-17-philmd@redhat.com> --- .mailmap | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/.mailmap b/.mailmap index 48e4ca43b5f..e38aa883d74 100644 --- a/.mailmap +++ b/.mailmap @@ -37,3 +37,7 @@ Jim Dailey Jim Dailey Laszlo Ersek Laszlo Ersek +Liming Gao +Liming Gao +Liming Gao +Liming Gao From a85cdb9f2b4dd7ce1b17298bbedaba5212d172c5 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:00 +0100 Subject: [PATCH 280/384] .mailmap: Add an entry for Maciej Rabeda We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Maciej Rabeda to have his/her name and email address displayed properly in the git history. Cc: Maciej Rabeda Reviewed-by: Maciej Rabeda Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-18-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index e38aa883d74..b66d4ef9437 100644 --- a/.mailmap +++ b/.mailmap @@ -41,3 +41,4 @@ Liming Gao Liming Gao Liming Gao Liming Gao +Maciej Rabeda From 9b2e99e50a72a5541a0a1fc4e0150290a96fef24 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:01 +0100 Subject: [PATCH 281/384] .mailmap: Add an entry for Marc-Andre Lureau MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Marc-André Lureau to have his/her name and email address displayed properly in the git history. Cc: Marc-André Lureau Reviewed-by: Marc-André Lureau Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-19-philmd@redhat.com> [lersek@redhat.com: translit subject to ASCII to suppress PatchCheck.py] --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index b66d4ef9437..d28b28f6f68 100644 --- a/.mailmap +++ b/.mailmap @@ -42,3 +42,4 @@ Liming Gao Liming Gao Liming Gao Maciej Rabeda +Marc-André Lureau From 76fc03874674acc4ce3bd942d0799f1c32df6aca Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:02 +0100 Subject: [PATCH 282/384] .mailmap: Add an entry for Marvin Haeuser MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Marvin Häuser to have his/her name and email address displayed properly in the git history (in particular, commit 62ec4a5e). Cc: Marvin Häuser Cc: Marvin Häuser Reviewed-by: Marvin Häuser Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-20-philmd@redhat.com> [lersek@redhat.com: translit subject to ASCII to suppress PatchCheck.py] --- .mailmap | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.mailmap b/.mailmap index d28b28f6f68..43edb3c8e92 100644 --- a/.mailmap +++ b/.mailmap @@ -43,3 +43,6 @@ Liming Gao Liming Gao Maciej Rabeda Marc-André Lureau +Marvin Häuser +Marvin Häuser edk2-devel +Marvin Häuser From 8ef8175a330c27fbb17aaaa8253158b017f20420 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:03 +0100 Subject: [PATCH 283/384] .mailmap: Add an entry for Maurice Ma We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Maurice Ma to have his/her name and email address displayed properly in the git history. Cc: Maurice Ma Reviewed-by: Maurice Ma Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-21-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 43edb3c8e92..0d30d5b0314 100644 --- a/.mailmap +++ b/.mailmap @@ -46,3 +46,4 @@ Marc-André Lureau Marvin Häuser Marvin Häuser edk2-devel Marvin Häuser +Maurice Ma From 43f2c9f8eb94489a69d61a61887d5fc03d249c61 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:04 +0100 Subject: [PATCH 284/384] .mailmap: Add an entry for Michael Kubacki We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Michael Kubacki to have his/her name and email address displayed properly in the git history. Cc: Michael Kubacki Reviewed-by: Michael Kubacki Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-22-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 0d30d5b0314..c87c23560a5 100644 --- a/.mailmap +++ b/.mailmap @@ -47,3 +47,5 @@ Marvin Häuser Marvin Häuser edk2-devel Marvin Häuser Maurice Ma +Michael Kubacki +Michael Kubacki From 266efa6b296c1ca60070484fa0136083a2732e25 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:05 +0100 Subject: [PATCH 285/384] .mailmap: Add an entry for Ming Tan We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Ming Tan to have his/her name and email address displayed properly in the git history. Cc: Ming Tan Reviewed-by: Ming Tan Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-23-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index c87c23560a5..99128ec1b49 100644 --- a/.mailmap +++ b/.mailmap @@ -49,3 +49,4 @@ Marvin Häuser Maurice Ma Michael Kubacki Michael Kubacki +Ming Tan From 21429c1566fbe50c4a6ab3539c701ef67cd02d90 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:06 +0100 Subject: [PATCH 286/384] .mailmap: Add an entry for Nikolai Saoukh We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Nikolai Saoukh to have his/her name and email address displayed properly in the git history. Cc: Nikolai Saoukh Reviewed-by: Nikolai Saoukh Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-24-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 99128ec1b49..2960aabaa1c 100644 --- a/.mailmap +++ b/.mailmap @@ -50,3 +50,4 @@ Maurice Ma Michael Kubacki Michael Kubacki Ming Tan +Nikolai Saoukh From a292d6c8ef3147ded7681cf6cf924c8c6314bffe Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:07 +0100 Subject: [PATCH 287/384] .mailmap: Add an entry for Philippe Mathieu-Daude MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Philippe Mathieu-Daudé to have his/her name and email address displayed properly in the git history. Reviewed-by: Laszlo Ersek Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-25-philmd@redhat.com> [lersek@redhat.com: translit subject to ASCII to suppress PatchCheck.py] --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 2960aabaa1c..9082d9912ac 100644 --- a/.mailmap +++ b/.mailmap @@ -51,3 +51,4 @@ Michael Kubacki Michael Kubacki Ming Tan Nikolai Saoukh +Philippe Mathieu-Daudé From 80f7c1b4640876ada2f33a8141c055a079848cc6 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:08 +0100 Subject: [PATCH 288/384] .mailmap: Add an entry for Ray Ni We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Ray Ni to have his/her name and email address displayed properly in the git history. Cc: Ray Ni Reviewed-by: Ray Ni Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-26-philmd@redhat.com> --- .mailmap | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/.mailmap b/.mailmap index 9082d9912ac..7f68422028c 100644 --- a/.mailmap +++ b/.mailmap @@ -52,3 +52,10 @@ Michael Kubacki Nikolai Saoukh Philippe Mathieu-Daudé +Ray Ni +Ray Ni +Ray Ni +Ray Ni +Ray Ni +Ray Ni +Ray Ni From ad12178c3dc1fc248ede3d5004979de642cf5242 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:09 +0100 Subject: [PATCH 289/384] .mailmap: Add an entry for Samer El-Haj-Mahmoud We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Samer El-Haj-Mahmoud to have his/her name and email address displayed properly in the git history. Cc: Samer El-Haj-Mahmoud Cc: Samer El-Haj-Mahmoud Reviewed-by: Samer El-Haj-Mahmoud Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-27-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 7f68422028c..504a7ea91ba 100644 --- a/.mailmap +++ b/.mailmap @@ -59,3 +59,5 @@ Ray Ni Ray Ni Ray Ni Ray Ni +Samer El-Haj-Mahmoud +Samer El-Haj-Mahmoud From 088573c97381c2dbcbf3dae9a153c88da7bb3498 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:10 +0100 Subject: [PATCH 290/384] .mailmap: Add an entry for Shenglei Zhang We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Shenglei Zhang to have his/her name and email address displayed properly in the git history. Cc: Shenglei Zhang Reviewed-by: Shenglei Zhang Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-28-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 504a7ea91ba..f574194fefb 100644 --- a/.mailmap +++ b/.mailmap @@ -61,3 +61,4 @@ Ray Ni Ray Ni Samer El-Haj-Mahmoud Samer El-Haj-Mahmoud +Shenglei Zhang From 0e660ee7a17915616f5c8b8dccc87c9a176e1aa4 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:11 +0100 Subject: [PATCH 291/384] .mailmap: Add an entry for Star Zeng We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Star Zeng to have his/her name and email address displayed properly in the git history. Cc: Star Zeng Reviewed-by: Star Zeng Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-29-philmd@redhat.com> --- .mailmap | 3 +++ 1 file changed, 3 insertions(+) diff --git a/.mailmap b/.mailmap index f574194fefb..b15d4f3bbdd 100644 --- a/.mailmap +++ b/.mailmap @@ -62,3 +62,6 @@ Ray Ni Samer El-Haj-Mahmoud Samer El-Haj-Mahmoud Shenglei Zhang +Star Zeng +Star Zeng +Star Zeng From 76b51586f4dc00a6341fd312052a92e3537410cc Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:12 +0100 Subject: [PATCH 292/384] .mailmap: Add an entry for Vitaly Cheptsov We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Vitaly Cheptsov to have his/her name and email address displayed properly in the git history. Cc: Vitaly Cheptsov Reviewed-by: Vitaly Cheptsov Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-30-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index b15d4f3bbdd..8b3140e9031 100644 --- a/.mailmap +++ b/.mailmap @@ -65,3 +65,4 @@ Shenglei Zhang Star Zeng Star Zeng Star Zeng +Vitaly Cheptsov Vitaly Cheptsov via Groups.Io From c751368c371a1ba29513fb22341f3f703d0b16b5 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:13 +0100 Subject: [PATCH 293/384] .mailmap: Add an entry for Vladimir Olovyannikov We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Vladimir Olovyannikov to have his/her name and email address displayed properly in the git history. Cc: Vladimir Olovyannikov Reviewed-by: Vladimir Olovyannikov Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-31-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 8b3140e9031..6e61fec90be 100644 --- a/.mailmap +++ b/.mailmap @@ -66,3 +66,4 @@ Star Zeng Star Zeng Star Zeng Vitaly Cheptsov Vitaly Cheptsov via Groups.Io +Vladimir Olovyannikov Vladimir Olovyannikov via edk2-devel From d96c7befc08d9d2b8b17cfd4e7abf00805a72018 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:14 +0100 Subject: [PATCH 294/384] .mailmap: Add an entry for Yonghong Zhu We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Yonghong Zhu to have his/her name and email address displayed properly in the git history. Cc: Yonghong Zhu Reviewed-by: Yonghong Zhu Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-32-philmd@redhat.com> --- .mailmap | 2 ++ 1 file changed, 2 insertions(+) diff --git a/.mailmap b/.mailmap index 6e61fec90be..88173455994 100644 --- a/.mailmap +++ b/.mailmap @@ -67,3 +67,5 @@ Star Zeng Star Zeng Vitaly Cheptsov Vitaly Cheptsov via Groups.Io Vladimir Olovyannikov Vladimir Olovyannikov via edk2-devel +Yonghong Zhu +Yonghong Zhu From 0ef6fbbd114e89b8d838eade39bc3a6d7ec54c3c Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Mon, 6 Jan 2020 12:54:15 +0100 Subject: [PATCH 295/384] .mailmap: Add an entry for Yu-Chen Lin We use .mailmap to display contributors email addresses in an uniform format. Add an entry for Yu-Chen Lin to have his/her name and email address displayed properly in the git history. Cc: Yu-Chen Lin Reviewed-by: Yu-Chen Lin Signed-off-by: Philippe Mathieu-Daude Message-Id: <20200106115415.11624-33-philmd@redhat.com> --- .mailmap | 1 + 1 file changed, 1 insertion(+) diff --git a/.mailmap b/.mailmap index 88173455994..ae179b0886c 100644 --- a/.mailmap +++ b/.mailmap @@ -69,3 +69,4 @@ Vitaly Cheptsov Vitaly Cheptsov via Groups.Io Vladimir Olovyannikov via edk2-devel Yonghong Zhu Yonghong Zhu +Yu-Chen Lin From cc617b6e1430242f8d042c71c2d923dbc6436a36 Mon Sep 17 00:00:00 2001 From: "Liu, Zhiguang" Date: Fri, 20 Dec 2019 16:32:26 +0800 Subject: [PATCH 296/384] edksetup.bat: Simplify the step to use CLANGPDB REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2404 Set the below two environment variables in edksetup.bat: set CLANG_HOST_BIN=n set CLANG_BIN=C:\Program Files\LLVM\bin\ In Windows, set CLANG_HOST_BIN=n to use nmake command The CLANG_BIN is only be set if it is not defined. Cc: Liming Gao Cc: Ray Ni Cc: Laszlo Ersek Signed-off-by: Zhiguang Liu --- edksetup.bat | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/edksetup.bat b/edksetup.bat index 024f57a4b73..7b9377aaa5c 100755 --- a/edksetup.bat +++ b/edksetup.bat @@ -113,6 +113,18 @@ if not defined NASM_PREFIX ( @if not exist "C:\nasm\nasm.exe" echo Attempting to build modules that require NASM will fail. ) +:check_CLANGPDB +@REM In Windows, set CLANG_HOST_BIN=n to use nmake command +@set CLANG_HOST_BIN=n +if not defined CLANG_BIN ( + @echo. + @echo !!! WARNING !!! CLANG_BIN environment variable is not set + @if exist "C:\Program Files\LLVM\bin\clang.exe" ( + @set CLANG_BIN=C:\Program Files\LLVM\bin\ + @echo Found LLVM, setting CLANG_BIN environment variable to C:\Program Files\LLVM\bin\ + ) +) + :check_cygwin if defined CYGWIN_HOME ( if not exist "%CYGWIN_HOME%" ( From 4bb34b6df1c8dbbb0bab65dc1838b8196568aec6 Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Tue, 7 Jan 2020 08:38:22 +0800 Subject: [PATCH 297/384] Revert "UefiCpuPkg/PiSmmCpuDxeSmm: Fix buffer overflow issue." This reverts commit 123b720eeb371e0a31eb727bcf59255b584e355f. The commit message for commit 123b720eeb37 is not correct. Cc: Ray Ni Reviewed-by: Laszlo Ersek Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 870250b0c55..f445d7b0300 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -137,7 +137,7 @@ ReleaseAllAPs ( { UINTN Index; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (IsPresentAp (Index)) { ReleaseSemaphore (mSmmMpSyncData->CpuData[Index].Run); } @@ -170,7 +170,7 @@ AllCpusInSmmWithExceptions ( CpuData = mSmmMpSyncData->CpuData; ProcessorInfo = gSmmCpuPrivate->ProcessorInfo; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (!(*(CpuData[Index].Present)) && ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { if (((Exceptions & ARRIVAL_EXCEPTION_DELAYED) != 0) && SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed) != 0) { continue; @@ -305,7 +305,7 @@ SmmWaitForApArrival ( // // Send SMI IPIs to bring outside processors in // - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (!(*(mSmmMpSyncData->CpuData[Index].Present)) && gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId); } @@ -361,7 +361,7 @@ WaitForAllAPsNotBusy ( { UINTN Index; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { // // Ignore BSP and APs which not call in SMM. // @@ -608,7 +608,7 @@ BSPHandler ( // while (TRUE) { PresentCount = 0; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (*(mSmmMpSyncData->CpuData[Index].Present)) { PresentCount ++; } @@ -1343,7 +1343,7 @@ InternalSmmStartupAllAPs ( } CpuCount = 0; - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (IsPresentAp (Index)) { CpuCount ++; @@ -1375,13 +1375,13 @@ InternalSmmStartupAllAPs ( // Here code always use AcquireSpinLock instead of AcquireSpinLockOrFail for not // block mode. // - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (IsPresentAp (Index)) { AcquireSpinLock (mSmmMpSyncData->CpuData[Index].Busy); } } - for (Index = 0; Index < mMaxNumberOfCpus; Index++) { + for (Index = mMaxNumberOfCpus; Index-- > 0;) { if (IsPresentAp (Index)) { mSmmMpSyncData->CpuData[Index].Procedure = (EFI_AP_PROCEDURE2) Procedure; mSmmMpSyncData->CpuData[Index].Parameter = ProcedureArguments; From 70911f1f4aee0366b6122f2b90d367ec0f066beb Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Tue, 7 Jan 2020 08:48:17 +0800 Subject: [PATCH 298/384] UefiCpuPkg/PiSmmCpuDxeSmm: improve the coding style REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2434 Current code use below loops to enumerate the CPUs: for (Index = mMaxNumberOfCpus; Index-- > 0;) { it has no issue but not easy for the developers to read the code. Update above code to below style, for (Index = 0; Index < mMaxNumberOfCpus; Index++) { It make the developers easy to read and consistent with other similar cases in this driver. Reviewed-by: Laszlo Ersek Cc: Ray Ni Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index f445d7b0300..35a6996ba34 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -1,7 +1,7 @@ /** @file SMM MP service implementation -Copyright (c) 2009 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
Copyright (c) 2017, AMD Incorporated. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -137,7 +137,7 @@ ReleaseAllAPs ( { UINTN Index; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { ReleaseSemaphore (mSmmMpSyncData->CpuData[Index].Run); } @@ -170,7 +170,7 @@ AllCpusInSmmWithExceptions ( CpuData = mSmmMpSyncData->CpuData; ProcessorInfo = gSmmCpuPrivate->ProcessorInfo; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (!(*(CpuData[Index].Present)) && ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { if (((Exceptions & ARRIVAL_EXCEPTION_DELAYED) != 0) && SmmCpuFeaturesGetSmmRegister (Index, SmmRegSmmDelayed) != 0) { continue; @@ -305,7 +305,7 @@ SmmWaitForApArrival ( // // Send SMI IPIs to bring outside processors in // - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (!(*(mSmmMpSyncData->CpuData[Index].Present)) && gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId != INVALID_APIC_ID) { SendSmiIpi ((UINT32)gSmmCpuPrivate->ProcessorInfo[Index].ProcessorId); } @@ -361,7 +361,7 @@ WaitForAllAPsNotBusy ( { UINTN Index; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { // // Ignore BSP and APs which not call in SMM. // @@ -608,7 +608,7 @@ BSPHandler ( // while (TRUE) { PresentCount = 0; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (*(mSmmMpSyncData->CpuData[Index].Present)) { PresentCount ++; } @@ -1343,7 +1343,7 @@ InternalSmmStartupAllAPs ( } CpuCount = 0; - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { CpuCount ++; @@ -1375,13 +1375,13 @@ InternalSmmStartupAllAPs ( // Here code always use AcquireSpinLock instead of AcquireSpinLockOrFail for not // block mode. // - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { AcquireSpinLock (mSmmMpSyncData->CpuData[Index].Busy); } } - for (Index = mMaxNumberOfCpus; Index-- > 0;) { + for (Index = 0; Index < mMaxNumberOfCpus; Index++) { if (IsPresentAp (Index)) { mSmmMpSyncData->CpuData[Index].Procedure = (EFI_AP_PROCEDURE2) Procedure; mSmmMpSyncData->CpuData[Index].Parameter = ProcedureArguments; From 08a475df10b75f84cdeb9b11e38f8eee9b5c048d Mon Sep 17 00:00:00 2001 From: Siyuan Fu Date: Fri, 3 Jan 2020 15:11:51 +0800 Subject: [PATCH 299/384] UefiCpuPkg: Remove alignment check when calculate microcode size. This patch removes the unnecessary alignment check on microcode patch TotalSize introduced by commit d786a172. The TotalSize has already been checked with 1K alignment and MAX_ADDRESS in previous code as below: if ( (UINTN)MicrocodeEntryPoint > (MAX_ADDRESS - TotalSize) || ((UINTN)MicrocodeEntryPoint + TotalSize) > MicrocodeEnd || (DataSize & 0x3) != 0 || (TotalSize & (SIZE_1KB - 1)) != 0 || TotalSize < DataSize ) { Cc: Eric Dong Cc: Ray Ni Cc: Hao A Wu Signed-off-by: Siyuan Fu Reviewed-by: Ray Ni Reviewed-by: Eric Dong --- UefiCpuPkg/Library/MpInitLib/Microcode.c | 24 +++++------------------- UefiCpuPkg/Library/MpInitLib/MpLib.h | 3 +-- 2 files changed, 6 insertions(+), 21 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index 3da5bfb9cf2..a9d06dd4099 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -1,7 +1,7 @@ /** @file Implementation of loading microcode on processors. - Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -397,16 +397,7 @@ LoadMicrocodePatchWorker ( Patches[Index].Size ); - // - // Zero-fill the padding area - // Please note that AlignedSize will be no less than Size - // - ZeroMem ( - Walker + Patches[Index].Size, - Patches[Index].AlignedSize - Patches[Index].Size - ); - - Walker += Patches[Index].AlignedSize; + Walker += Patches[Index].Size; } // @@ -578,14 +569,9 @@ LoadMicrocodePatch ( // // Store the information of this microcode patch // - if (TotalSize > ALIGN_VALUE (TotalSize, SIZE_1KB) || - ALIGN_VALUE (TotalSize, SIZE_1KB) > MAX_UINTN - TotalLoadSize) { - goto OnExit; - } - PatchInfoBuffer[PatchCount - 1].Address = (UINTN) MicrocodeEntryPoint; - PatchInfoBuffer[PatchCount - 1].Size = TotalSize; - PatchInfoBuffer[PatchCount - 1].AlignedSize = ALIGN_VALUE (TotalSize, SIZE_1KB); - TotalLoadSize += PatchInfoBuffer[PatchCount - 1].AlignedSize; + PatchInfoBuffer[PatchCount - 1].Address = (UINTN) MicrocodeEntryPoint; + PatchInfoBuffer[PatchCount - 1].Size = TotalSize; + TotalLoadSize += TotalSize; } // diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index 6609c958ce8..b6e5a1afab0 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -1,7 +1,7 @@ /** @file Common header file for MP Initialize Library. - Copyright (c) 2016 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -54,7 +54,6 @@ typedef struct { UINTN Address; UINTN Size; - UINTN AlignedSize; } MICROCODE_PATCH_INFO; // From 396e791059f37062cbee85696e2b4186ec72a9e3 Mon Sep 17 00:00:00 2001 From: "Siyuan, Fu" Date: Fri, 3 Jan 2020 14:59:27 +0800 Subject: [PATCH 300/384] UefiCpuPkg: Always load microcode patch on AP processor. This patch updates the microcode loader to always perform a microcode detect and load on both BSP and AP processor. This is to fix a potential microcode revision mismatch issue in below situation: 1. Assume there are two microcode co-exists in flash: one production version and one debug version microcode. 2. FIT loads production microcode to BSP and all AP. 3. UefiCpuPkg loader loads debug microcode to BSP, and skip the loading on AP. As a result, different microcode patches are loaded to BSP and AP, and trigger microcode mismatch error during OS boot. BZ link: https://bugzilla.tianocore.org/show_bug.cgi?id=2431 Cc: Eric Dong Cc: Ray Ni Signed-off-by: Siyuan Fu Reviewed-by: Eric Dong --- UefiCpuPkg/Library/MpInitLib/Microcode.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index a9d06dd4099..8f4d4da40c7 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -105,12 +105,6 @@ MicrocodeDetect ( CurrentRevision = GetCurrentMicrocodeSignature (); IsBspCallIn = (ProcessorNumber == (UINTN)CpuMpData->BspNumber) ? TRUE : FALSE; - if (CurrentRevision != 0 && !IsBspCallIn) { - // - // Skip loading microcode if it has been loaded successfully - // - return; - } GetProcessorLocationByApicId (GetInitialApicId (), NULL, NULL, &ThreadId); if (ThreadId != 0) { From c9d72628432126cbce58a48b440e4944baa4beab Mon Sep 17 00:00:00 2001 From: "Pavana.K" Date: Thu, 2 Jan 2020 20:30:27 +0000 Subject: [PATCH 301/384] CryptoPkg: Support for SHA384 & SHA512 RSA signing schemes BZ: https://bugzilla.tianocore.org/show_bug.cgi?id=2389 Currently RSA signing scheme support is available for MD5, SHA-1 or SHA-256 algorithms.The fix is to extend this support for SHA384 and SHA512. Cc: Liming Gao Cc: Jian J Wang Cc: Bob Feng Signed-off-by: Pavana.K Reviewed-by: Jian J Wang --- CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaBasic.c | 14 +++++++++++--- CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaExt.c | 14 +++++++++++--- 2 files changed, 22 insertions(+), 6 deletions(-) diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaBasic.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaBasic.c index 454dbbd476d..d24e1fdf680 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaBasic.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaBasic.c @@ -7,7 +7,7 @@ 3) RsaSetKey 4) RsaPkcs1Verify -Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -250,7 +250,7 @@ RsaSetKey ( If RsaContext is NULL, then return FALSE. If MessageHash is NULL, then return FALSE. If Signature is NULL, then return FALSE. - If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE. + If HashSize is not equal to the size of MD5, SHA-1, SHA-256, SHA-384 or SHA-512 digest, then return FALSE. @param[in] RsaContext Pointer to RSA context for signature verification. @param[in] MessageHash Pointer to octet message hash to be checked. @@ -288,7 +288,7 @@ RsaPkcs1Verify ( // // Determine the message digest algorithm according to digest size. - // Only MD5, SHA-1 or SHA-256 algorithm is supported. + // Only MD5, SHA-1, SHA-256, SHA-384 or SHA-512 algorithm is supported. // switch (HashSize) { case MD5_DIGEST_SIZE: @@ -303,6 +303,14 @@ RsaPkcs1Verify ( DigestType = NID_sha256; break; + case SHA384_DIGEST_SIZE: + DigestType = NID_sha384; + break; + + case SHA512_DIGEST_SIZE: + DigestType = NID_sha512; + break; + default: return FALSE; } diff --git a/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaExt.c b/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaExt.c index e3dd4844c44..7cd5fecf04c 100644 --- a/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaExt.c +++ b/CryptoPkg/Library/BaseCryptLib/Pk/CryptRsaExt.c @@ -7,7 +7,7 @@ 3) RsaCheckKey 4) RsaPkcs1Sign -Copyright (c) 2009 - 2018, Intel Corporation. All rights reserved.
+Copyright (c) 2009 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -276,7 +276,7 @@ RsaCheckKey ( If RsaContext is NULL, then return FALSE. If MessageHash is NULL, then return FALSE. - If HashSize is not equal to the size of MD5, SHA-1 or SHA-256 digest, then return FALSE. + If HashSize is not equal to the size of MD5, SHA-1, SHA-256, SHA-384 or SHA-512 digest, then return FALSE. If SigSize is large enough but Signature is NULL, then return FALSE. @param[in] RsaContext Pointer to RSA context for signature generation. @@ -326,7 +326,7 @@ RsaPkcs1Sign ( // // Determine the message digest algorithm according to digest size. - // Only MD5, SHA-1 or SHA-256 algorithm is supported. + // Only MD5, SHA-1, SHA-256, SHA-384 or SHA-512 algorithm is supported. // switch (HashSize) { case MD5_DIGEST_SIZE: @@ -341,6 +341,14 @@ RsaPkcs1Sign ( DigestType = NID_sha256; break; + case SHA384_DIGEST_SIZE: + DigestType = NID_sha384; + break; + + case SHA512_DIGEST_SIZE: + DigestType = NID_sha512; + break; + default: return FALSE; } From 972d88726410e21b1fff1a528854202c67e97ef1 Mon Sep 17 00:00:00 2001 From: Ashish Singhal Date: Tue, 24 Dec 2019 10:57:47 +0800 Subject: [PATCH 302/384] MdeModulePkg: Add EDK2 Platform Boot Manager Protocol Add edk2 platform boot manager protocol which would have platform specific refreshes to the auto enumerated as well as NV boot options for the platform. Signed-off-by: Ashish Singhal Reviewed-by: Ray Ni --- .../Include/Protocol/PlatformBootManager.h | 82 +++++++++++++++++++ .../Library/UefiBootManagerLib/BmBoot.c | 41 ++++++++-- .../Library/UefiBootManagerLib/InternalBm.h | 2 + .../UefiBootManagerLib/UefiBootManagerLib.inf | 2 + MdeModulePkg/MdeModulePkg.dec | 4 + 5 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 MdeModulePkg/Include/Protocol/PlatformBootManager.h diff --git a/MdeModulePkg/Include/Protocol/PlatformBootManager.h b/MdeModulePkg/Include/Protocol/PlatformBootManager.h new file mode 100644 index 00000000000..26b9ce48ad6 --- /dev/null +++ b/MdeModulePkg/Include/Protocol/PlatformBootManager.h @@ -0,0 +1,82 @@ +/** @file + + Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. + + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __PLATFORM_BOOT_MANAGER_PROTOCOL_H__ +#define __PLATFORM_BOOT_MANAGER_PROTOCOL_H__ + +#include + +// +// Platform Boot Manager Protocol GUID value +// +#define EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL_GUID \ + { \ + 0xaa17add4, 0x756c, 0x460d, { 0x94, 0xb8, 0x43, 0x88, 0xd7, 0xfb, 0x3e, 0x59 } \ + } + +// +// Protocol interface structure +// +typedef struct _EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL; + +// +// Revision The revision to which the protocol interface adheres. +// All future revisions must be backwards compatible. +// If a future version is not back wards compatible it is not the same GUID. +// +#define EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL_REVISION 0x00000001 + +// +// Function Prototypes +// + +/* + This function allows platform to refresh all boot options specific to the platform. Within + this function, platform can make modifications to the auto enumerated platform boot options + as well as NV boot options. + + @param[in const] BootOptions An array of auto enumerated platform boot options. + This array will be freed by caller upon successful + exit of this function and output array would be used. + + @param[in const] BootOptionsCount The number of elements in BootOptions. + + @param[out] UpdatedBootOptions An array of boot options that have been customized + for the platform on top of input boot options. This + array would be allocated by REFRESH_ALL_BOOT_OPTIONS + and would be freed by caller after consuming it. + + @param[out] UpdatedBootOptionsCount The number of elements in UpdatedBootOptions. + + + @retval EFI_SUCCESS Platform refresh to input BootOptions and + BootCount have been done. + + @retval EFI_OUT_OF_RESOURCES Memory allocation failed. + + @retval EFI_INVALID_PARAMETER Input is not correct. + + @retval EFI_UNSUPPORTED Platform specific overrides are not supported. +*/ +typedef +EFI_STATUS +(EFIAPI *PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS) ( + IN CONST EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions, + IN CONST UINTN BootOptionsCount, + OUT EFI_BOOT_MANAGER_LOAD_OPTION **UpdatedBootOptions, + OUT UINTN *UpdatedBootOptionsCount + ); + +struct _EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL { + UINT64 Revision; + PLATFORM_BOOT_MANAGER_REFRESH_ALL_BOOT_OPTIONS RefreshAllBootOptions; +}; + +extern EFI_GUID gEdkiiPlatformBootManagerProtocolGuid; + +#endif /* __PLATFORM_BOOT_MANAGER_PROTOCOL_H__ */ diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c index 760d7647b8b..62c5b2dc94a 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c @@ -1,6 +1,7 @@ /** @file Library functions which relates with booting. +Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. Copyright (c) 2011 - 2019, Intel Corporation. All rights reserved.
(C) Copyright 2015-2016 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -2258,12 +2259,15 @@ EfiBootManagerRefreshAllBootOption ( VOID ) { - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions; - UINTN NvBootOptionCount; - EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; - UINTN BootOptionCount; - UINTN Index; + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION *NvBootOptions; + UINTN NvBootOptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION *BootOptions; + UINTN BootOptionCount; + EFI_BOOT_MANAGER_LOAD_OPTION *UpdatedBootOptions; + UINTN UpdatedBootOptionCount; + UINTN Index; + EDKII_PLATFORM_BOOT_MANAGER_PROTOCOL *PlatformBootManager; // // Optionally refresh the legacy boot option @@ -2273,7 +2277,6 @@ EfiBootManagerRefreshAllBootOption ( } BootOptions = BmEnumerateBootOptions (&BootOptionCount); - NvBootOptions = EfiBootManagerGetLoadOptions (&NvBootOptionCount, LoadOptionTypeBoot); // // Mark the boot option as added by BDS by setting OptionalData to a special GUID @@ -2283,6 +2286,30 @@ EfiBootManagerRefreshAllBootOption ( BootOptions[Index].OptionalDataSize = sizeof (EFI_GUID); } + // + // Locate Platform Boot Options Protocol + // + Status = gBS->LocateProtocol (&gEdkiiPlatformBootManagerProtocolGuid, + NULL, + (VOID **)&PlatformBootManager); + if (!EFI_ERROR (Status)) { + // + // If found, call platform specific refresh to all auto enumerated and NV + // boot options. + // + Status = PlatformBootManager->RefreshAllBootOptions ((CONST EFI_BOOT_MANAGER_LOAD_OPTION *)BootOptions, + (CONST UINTN)BootOptionCount, + &UpdatedBootOptions, + &UpdatedBootOptionCount); + if (!EFI_ERROR (Status)) { + EfiBootManagerFreeLoadOptions (BootOptions, BootOptionCount); + BootOptions = UpdatedBootOptions; + BootOptionCount = UpdatedBootOptionCount; + } + } + + NvBootOptions = EfiBootManagerGetLoadOptions (&NvBootOptionCount, LoadOptionTypeBoot); + // // Remove invalid EFI boot options from NV // diff --git a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h index 027eb25ecf2..ac866ac25fd 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h +++ b/MdeModulePkg/Library/UefiBootManagerLib/InternalBm.h @@ -1,6 +1,7 @@ /** @file BDS library definition, include the file and data structure +Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. Copyright (c) 2004 - 2018, Intel Corporation. All rights reserved.
(C) Copyright 2015 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -41,6 +42,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent #include #include #include +#include #include #include diff --git a/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf b/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf index ed6b4679eb7..cf5908692fa 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf +++ b/MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf @@ -5,6 +5,7 @@ # manipulation, hotkey registration, UEFI boot, connect/disconnect, console # manipulation, driver health checking and etc. # +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# (C) Copyright 2016 Hewlett Packard Enterprise Development LP
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -107,6 +108,7 @@ gEfiFormBrowser2ProtocolGuid ## SOMETIMES_CONSUMES gEfiRamDiskProtocolGuid ## SOMETIMES_CONSUMES gEfiDeferredImageLoadProtocolGuid ## SOMETIMES_CONSUMES + gEdkiiPlatformBootManagerProtocolGuid ## SOMETIMES_CONSUMES [Pcd] gEfiMdeModulePkgTokenSpaceGuid.PcdResetOnMemoryTypeInformationChange ## SOMETIMES_CONSUMES diff --git a/MdeModulePkg/MdeModulePkg.dec b/MdeModulePkg/MdeModulePkg.dec index f75a74af256..e840cebe2ea 100644 --- a/MdeModulePkg/MdeModulePkg.dec +++ b/MdeModulePkg/MdeModulePkg.dec @@ -3,6 +3,7 @@ # It also provides the definitions(including PPIs/PROTOCOLs/GUIDs and library classes) # and libraries instances, which are used for those modules. # +# Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved. # Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
# Copyright (c) 2016, Linaro Ltd. All rights reserved.
# (C) Copyright 2016 - 2019 Hewlett Packard Enterprise Development LP
@@ -609,6 +610,9 @@ ## Include/Protocol/PeCoffImageEmulator.h gEdkiiPeCoffImageEmulatorProtocolGuid = { 0x96f46153, 0x97a7, 0x4793, { 0xac, 0xc1, 0xfa, 0x19, 0xbf, 0x78, 0xea, 0x97 } } + ## Include/Protocol/PlatformBootManager.h + gEdkiiPlatformBootManagerProtocolGuid = { 0xaa17add4, 0x756c, 0x460d, { 0x94, 0xb8, 0x43, 0x88, 0xd7, 0xfb, 0x3e, 0x59 } } + # # [Error.gEfiMdeModulePkgTokenSpaceGuid] # 0x80000001 | Invalid value provided. From fb8e74b68f7050146030a542e8fdcd1458a19f22 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Mon, 6 Jan 2020 11:17:35 -0800 Subject: [PATCH 303/384] UnitTestFrameworkPkg/Library/HostCmocha: Simplify build options Signed-off-by: Michael D Kinney --- .../Library/HostCmocka/CmockaLib/CmockaLib.inf | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf index 3ef9bd9aa79..bbf3e4616ad 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf @@ -26,7 +26,10 @@ UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [BuildOptions] - MSFT:*_*_*_CC_FLAGS == /c /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES=1 /D _CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES_COUNT=1 /D _CRT_NONSTDC_NO_WARNINGS=1 /D _CRT_SECURE_NO_WARNINGS=1 -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + MSFT:*_*_*_CC_FLAGS == /c -DHAVE_VSNPRINTF -DHAVE_SNPRINTF + MSFT:NOOPT_*_*_CC_FLAGS = /Od - GCC:*_*_IA32_CC_FLAGS == -m32 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H - GCC:*_*_X64_CC_FLAGS == -m64 -O0 -g -fprofile-arcs -ftest-coverage -std=gnu99 -Wpedantic -Wall -Wshadow -Wmissing-prototypes -Wcast-align -Werror=address -Wstrict-prototypes -Werror=strict-prototypes -Wwrite-strings -Werror=write-strings -Werror-implicit-function-declaration -Wpointer-arith -Werror=pointer-arith -Wdeclaration-after-statement -Werror=declaration-after-statement -Wreturn-type -Werror=return-type -Wuninitialized -Werror=uninitialized -Werror=strict-overflow -Wstrict-overflow=2 -Wno-format-zero-length -Wmissing-field-initializers -Wformat-security -Werror=format-security -fno-common -Wformat -fno-common -fstack-protector-strong -DHAVE_SIGNAL_H + GCC:*_*_*_CC_FLAGS == -g -DHAVE_SIGNAL_H + GCC:NOOPT_*_*_CC_FLAGS = -O0 + GCC:*_*_IA32_CC_FLAGS = -m32 + GCC:*_*_X64_CC_FLAGS = -m64 From b6cd657ff8028a0bac08b7eb834eb9b1d6be8398 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 7 Jan 2020 19:15:49 -0800 Subject: [PATCH 304/384] UnitTestFrameworkPkg: Clean ups Signed-off-by: Michael D Kinney --- .gitmodules | 4 +- .pytool/CISettings.py | 2 +- MdePkg/Include/Library/UnitTestLib.h | 667 +++++++------- MdePkg/Test/MdePkgHostTest.dsc | 27 + MdePkg/Test/MdePkgTargetTest.dsc | 30 + .../BaseSafeIntLib/TestBaseSafeIntLib.c | 22 +- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 1 + .../BaseSafeIntLib/TestBaseSafeIntLib.uni | 13 + .../BaseSafeIntLib/TestBaseSafeIntLibDxe.inf | 65 ++ ...eIntLib.inf => TestBaseSafeIntLibHost.inf} | 14 +- .../BaseSafeIntLib/TestBaseSafeIntLibPei.inf | 65 ++ .../BaseSafeIntLib/TestBaseSafeIntLibSmm.inf | 65 ++ .../TestBaseSafeIntLibUefiShell.inf | 62 ++ .../{HostCmocka => }/CmockaLib/CmockaLib.inf | 14 +- .../{HostCmocka => }/CmockaLib/CmockaLib.uni | 2 - .../Library/{HostCmocka => }/CmockaLib/cmocka | 0 .../UnitTestAssertLib.c | 191 ---- .../UnitTestAssertLibCmocka.inf | 25 - .../UnitTestLibCmocka/UnitTestLib.c | 497 ---------- .../Posix/DebugLibPosix/DebugLibPosix.c | 341 ++++--- .../Posix/DebugLibPosix/DebugLibPosix.inf | 33 +- .../Posix/DebugLibPosix/DebugLibPosix.uni | 14 + .../MemoryAllocationLibPosix.c | 405 ++++++++- .../MemoryAllocationLibPosix.inf | 21 +- .../MemoryAllocationLibPosix.uni | 14 + .../UnitTestAssertLib/UnitTestAssertLib.c | 235 ----- .../UnitTestAssertLib/UnitTestAssertLib.inf | 38 - .../UnitTestBootLibNull/UnitTestBootLibNull.c | 18 - .../UnitTestBootLibNull.inf | 28 - .../Library/Uefi/UnitTestLib/UnitTestLib.c | 858 ------------------ .../Uefi/UnitTestLib/UnitTestLibDxe.inf | 43 - .../Uefi/UnitTestLib/UnitTestLibPei.inf | 41 - .../Uefi/UnitTestLib/UnitTestLibSmm.inf | 42 - .../Uefi/UnitTestLogLib/UnitTestLogLib.c | 216 ----- .../Uefi/UnitTestLogLib/UnitTestLogLib.inf | 42 - .../UnitTestPersistenceLibNull.c | 94 -- .../UnitTestResultReportLibDebug.c | 210 ----- .../UnitTestResultReportLibDebug.inf | 34 - .../UnitTestBootLibUsbClass.c | 112 --- .../UnitTestPersistenceLibFileSystem.c | 416 --------- .../UnitTestResultReportLibPlainTextOutput.c | 227 ----- ...UnitTestResultReportLibPlainTextOutput.inf | 37 - .../UnitTestBootLibNull/UnitTestBootLibNull.c | 25 + .../UnitTestBootLibNull.inf | 22 + .../UnitTestBootLibNull.uni | 11 + .../UnitTestBootLibUsbClass.c | 126 +++ .../UnitTestBootLibUsbClass.inf | 36 +- .../UnitTestBootLibUsbClass.uni | 12 + .../Library/UnitTestLib/Assert.c | 215 +++++ .../Library/UnitTestLib/AssertCmocka.c | 183 ++++ .../Library/UnitTestLib/Log.c | 195 ++++ .../Library/UnitTestLib/RunTests.c | 144 +++ .../Library/UnitTestLib/RunTestsCmocka.c | 121 +++ .../Library/UnitTestLib/UnitTestLib.c | 736 +++++++++++++++ .../Library/UnitTestLib/UnitTestLib.inf | 37 + .../Library/UnitTestLib/UnitTestLib.uni | 11 + .../UnitTestLibCmocka.inf | 29 +- .../Library/UnitTestLib/UnitTestLibCmocka.uni | 11 + .../UnitTestPersistenceLibNull.c | 88 ++ .../UnitTestPersistenceLibNull.inf | 19 +- .../UnitTestPersistenceLibNull.uni | 11 + .../UnitTestPersistenceLibSimpleFileSystem.c | 428 +++++++++ ...nitTestPersistenceLibSimpleFileSystem.inf} | 33 +- ...UnitTestPersistenceLibSimpleFileSystem.uni | 15 + .../UnitTestResultReportLib.c | 217 +++++ .../UnitTestResultReportLibConOut.c | 49 + .../UnitTestResultReportLibConOut.inf | 29 + .../UnitTestResultReportLibConOut.uni | 11 + .../UnitTestResultReportLibDebugLib.c | 48 + .../UnitTestResultReportLibDebugLib.inf | 28 + .../UnitTestResultReportLibDebugLib.uni | 11 + .../PrivateInclude/Library/UnitTestBootLib.h | 22 +- .../Library/UnitTestPersistenceLib.h | 15 +- .../Library/UnitTestResultReportLib.h | 16 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 27 +- .../SampleUnitTestApp/SampleUnitTestApp.inf | 7 - .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 6 - .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 6 - .../UnitTestFrameworkPkg.ci.yaml | 4 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 12 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 67 +- .../UnitTestFrameworkPkgHost.dsc.inc | 44 +- .../UnitTestFrameworkPkgTarget.dsc.inc | 57 ++ 83 files changed, 4326 insertions(+), 4143 deletions(-) create mode 100644 MdePkg/Test/MdePkgHostTest.dsc create mode 100644 MdePkg/Test/MdePkgTargetTest.dsc create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.uni create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf rename MdePkg/Test/UnitTest/Library/BaseSafeIntLib/{TestBaseSafeIntLib.inf => TestBaseSafeIntLibHost.inf} (82%) create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf create mode 100644 MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf rename UnitTestFrameworkPkg/Library/{HostCmocka => }/CmockaLib/CmockaLib.inf (62%) rename UnitTestFrameworkPkg/Library/{HostCmocka => }/CmockaLib/CmockaLib.uni (96%) rename UnitTestFrameworkPkg/Library/{HostCmocka => }/CmockaLib/cmocka (100%) delete mode 100644 UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c delete mode 100644 UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf delete mode 100644 UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c create mode 100644 UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.uni create mode 100644 UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.uni delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c delete mode 100644 UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf delete mode 100644 UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c delete mode 100644 UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c delete mode 100644 UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c delete mode 100644 UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c rename UnitTestFrameworkPkg/Library/{UefiShell => }/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf (64%) create mode 100644 UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/Log.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.uni rename UnitTestFrameworkPkg/Library/{HostCmocka/UnitTestLibCmocka => UnitTestLib}/UnitTestLibCmocka.inf (51%) create mode 100644 UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c rename UnitTestFrameworkPkg/Library/{Uefi => }/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf (77%) create mode 100644 UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c rename UnitTestFrameworkPkg/Library/{UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf => UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf} (64%) create mode 100644 UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.uni create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf create mode 100644 UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.uni rename MdePkg/Test/MdePkgTest.dsc => UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc (52%) create mode 100644 UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc diff --git a/.gitmodules b/.gitmodules index bb34fb2b76c..b30f5bf136b 100644 --- a/.gitmodules +++ b/.gitmodules @@ -4,6 +4,6 @@ [submodule "SoftFloat"] path = ArmPkg/Library/ArmSoftFloatLib/berkeley-softfloat-3 url = https://github.com/ucb-bar/berkeley-softfloat-3.git -[submodule "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka"] - path = UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka +[submodule "UnitTestFrameworkPkg/Library/CmockaLib/cmocka"] + path = UnitTestFrameworkPkg/Library/CmockaLib/cmocka url = https://git.cryptomilk.org/projects/cmocka.git diff --git a/.pytool/CISettings.py b/.pytool/CISettings.py index fd99c517c3b..79593d9dc51 100644 --- a/.pytool/CISettings.py +++ b/.pytool/CISettings.py @@ -143,7 +143,7 @@ def GetRequiredSubmodules(self): rs.append(RequiredSubmodule( "CryptoPkg/Library/OpensslLib/openssl", False)) rs.append(RequiredSubmodule( - "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka", False)) + "UnitTestFrameworkPkg/Library/CmockaLib/cmocka", False)) return rs def GetName(self): diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 04ce936ea7f..1d0cd644222 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -1,334 +1,335 @@ -/** @file - Provides a unit test framework. This allows tests to focus on testing logic - and the framework to focus on runnings, reporting, statistics, etc. - - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#ifndef __UNIT_TEST_LIB_H__ -#define __UNIT_TEST_LIB_H__ - -typedef UINT32 UNIT_TEST_STATUS; -#define UNIT_TEST_PASSED (0) -#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) -#define UNIT_TEST_ERROR_TEST_FAILED (2) -#define UNIT_TEST_SKIPPED (0xFFFFFFFD) -#define UNIT_TEST_RUNNING (0xFFFFFFFE) -#define UNIT_TEST_PENDING (0xFFFFFFFF) - -typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK*, but with fewer build errors. -typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE*, but with fewer build errors. -typedef VOID* UNIT_TEST_HANDLE; // Same as a UNIT_TEST*, but with fewer build errors. -typedef VOID* UNIT_TEST_CONTEXT; - - -///================================================================================================ -///================================================================================================ -/// -/// UNIT TEST FUNCTION TYPE DEFINITIONS -/// -///================================================================================================ -///================================================================================================ - -// -// Unit-Test Function pointer type. -// -typedef -UNIT_TEST_STATUS -(EFIAPI *UNIT_TEST_FUNCTION) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Prerequisite Function pointer type. -// NOTE: Should be the same as UnitTest. -// -typedef -UNIT_TEST_STATUS -(EFIAPI *UNIT_TEST_PREREQ) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Test Cleanup (after) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_CLEANUP) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework, - UNIT_TEST_CONTEXT Context - ); - -// -// Unit-Test Test Suite Setup (before) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_SUITE_SETUP) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework - ); - -// -// Unit-Test Test Suite Teardown (after) function pointer type. -// -typedef -VOID -(EFIAPI *UNIT_TEST_SUITE_TEARDOWN) ( - UNIT_TEST_FRAMEWORK_HANDLE Framework - ); - - -///================================================================================================ -///================================================================================================ -/// -/// UNIT TEST FUNCTION DEFINITIONS -/// -///================================================================================================ -///================================================================================================ - - -/* -Method to Initialize the Unit Test framework - -@param Framework - Unit test framework to be created. -@param Title - String name of the framework. String is copied. -@param ShortTitle - Short string name of the framework. String is copied. -@param VersionString - Version string for the framework. String is copied. - -@retval Success - Unit Test init. -@retval EFI_ERROR - Unit Tests init failed. -*/ -EFI_STATUS -EFIAPI -InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString - ); - -/* -Creates Unit Test Suite in the Unit Test Framework - -@param Suite - Suite to create -@param Framework - Framework to add suite to -@param Title - String name of the suite. String is copied. -@param Package - String name of the package. String is copied. -@param Sup - Setup function, runs before suite. -@param Tdn - Teardown function, runs after suite. - -@retval Success - Unit Test Suite was created. -@retval EFI_OUT_OF_RESOURCES - Unit Test Suite failed to be created. -*/ -EFI_STATUS -EFIAPI -CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL - ); - -/* -Adds test case to Suite - -@param Suite - Suite to add test to. -@param Description - String describing test. String is copied. -@param ClassName - String name of the test. String is copied. -@param Func - Test function. -@param PreReq - Prep function, runs before test. -@param CleanUp - Clean up function, runs after test. -@param Context - Pointer to context. - -@retval Success - Unit test was added. -@retval EFI_OUT_OF_RESOURCES - Unit test failed to be added. -*/ -EFI_STATUS -EFIAPI -AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL - ); - -EFI_STATUS -EFIAPI -RunAllTestSuites( - IN UNIT_TEST_SUITE_HANDLE Framework - ); - -EFI_STATUS -EFIAPI -FreeUnitTestFramework ( - IN UNIT_TEST_SUITE_HANDLE Framework - ); - -EFI_STATUS -EFIAPI -SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ); - - -///================================================================================================ -///================================================================================================ -/// -/// LOGGING AND ASSERTION DEFINITIONS/DECLARATIONS -/// -///================================================================================================ -///================================================================================================ - - -#define UT_ASSERT_TRUE(Expression) \ - if(!UnitTestAssertTrue( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_FALSE(Expression) \ - if(!UnitTestAssertFalse( Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ - if(!UnitTestAssertMemEqual( Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual( Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError( Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual( Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status )) { return UNIT_TEST_ERROR_TEST_FAILED;} - -#define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull(Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { return UNIT_TEST_ERROR_TEST_FAILED; } - - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ); - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ); - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ); - -#define UT_LOG_ERROR(Format, ...) \ - UnitTestLog( Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); -#define UT_LOG_WARNING(Format, ...) \ - UnitTestLog( Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); -#define UT_LOG_INFO(Format, ...) \ - UnitTestLog( Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); -#define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog( Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); - -VOID -EFIAPI -UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - ... - ); - +/** @file + Provides a unit test framework. This allows tests to focus on testing logic + and the framework to focus on runnings, reporting, statistics, etc. + + Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __UNIT_TEST_LIB_H__ +#define __UNIT_TEST_LIB_H__ + +typedef UINT32 UNIT_TEST_STATUS; +#define UNIT_TEST_PASSED (0) +#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) +#define UNIT_TEST_ERROR_TEST_FAILED (2) +#define UNIT_TEST_SKIPPED (0xFFFFFFFD) +#define UNIT_TEST_RUNNING (0xFFFFFFFE) +#define UNIT_TEST_PENDING (0xFFFFFFFF) + +typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK* +typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE* +typedef VOID* UNIT_TEST_HANDLE; // Same as a UNIT_TEST* +typedef VOID* UNIT_TEST_CONTEXT; + +// +// Unit-Test Function pointer type. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_FUNCTION)( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Prerequisite Function pointer type. +// NOTE: Should be the same as UnitTest. +// +typedef +UNIT_TEST_STATUS +(EFIAPI *UNIT_TEST_PREREQ)( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Cleanup (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_CLEANUP)( + UNIT_TEST_FRAMEWORK_HANDLE Framework, + UNIT_TEST_CONTEXT Context + ); + +// +// Unit-Test Test Suite Setup (before) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_SETUP)( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + +// +// Unit-Test Test Suite Teardown (after) function pointer type. +// +typedef +VOID +(EFIAPI *UNIT_TEST_SUITE_TEARDOWN)( + UNIT_TEST_FRAMEWORK_HANDLE Framework + ); + +/// +/// Unit-Test Library Functions +/// + +/* + Method to Initialize the Unit Test framework + + @param Framework - Unit test framework to be created. + @param Title - String name of the framework. String is copied. + @param ShortTitle - Short string name of the framework. String is copied. + @param VersionString - Version string for the framework. String is copied. + + @retval Success - Unit Test init. + @retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString + ); + +/* + Creates Unit Test Suite in the Unit Test Framework + + @param Suite - Suite to create + @param Framework - Framework to add suite to + @param Title - String name of the suite. String is copied. + @param Package - String name of the package. String is copied. + @param Sup - Setup function, runs before suite. + @param Tdn - Teardown function, runs after suite. + + @retval Success - Unit Test Suite was created. + @retval EFI_OUT_OF_RESOURCES - Unit Test Suite failed to be created. +*/ +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN CHAR8 *Title, + IN CHAR8 *Package, + IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ); + +/* + Adds test case to Suite + + @param Suite - Suite to add test to. + @param Description - String describing test. String is copied. + @param ClassName - String name of the test. String is copied. + @param Func - Test function. + @param PreReq - Prep function, runs before test. + @param CleanUp - Clean up function, runs after test. + @param Context - Pointer to context. + + @retval Success - Unit test was added. + @retval EFI_OUT_OF_RESOURCES - Unit test failed to be added. +*/ +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE_HANDLE Suite, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL + ); + +EFI_STATUS +EFIAPI +RunAllTestSuites( + IN UNIT_TEST_SUITE_HANDLE Framework + ); + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_SUITE_HANDLE Framework + ); + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, + IN UINTN ContextToSaveSize + ); + +/// +/// Unit-Test Assertion Macros and Functions +/// + +#define UT_ASSERT_TRUE(Expression) \ + if(!UnitTestAssertTrue (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_FALSE(Expression) \ + if(!UnitTestAssertFalse (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ + if(!UnitTestAssertMemEqual (Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ + if(!UnitTestAssertNotEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_NOT_EFI_ERROR(Status) \ + if(!UnitTestAssertNotEfiError (Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ + if(!UnitTestAssertStatusEqual (Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +#define UT_ASSERT_NOT_NULL(Pointer) \ + if(!UnitTestAssertNotNull (Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ + } + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ); + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ); + +BOOLEAN +EFIAPI +UnitTestAssertNotNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ); + +/// +/// Unit-Test Logging Macros and Functions +/// + +#define UT_LOG_ERROR(Format, ...) \ + UnitTestLog (Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); + +#define UT_LOG_WARNING(Format, ...) \ + UnitTestLog (Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); + +#define UT_LOG_INFO(Format, ...) \ + UnitTestLog (Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); + +#define UT_LOG_VERBOSE(Format, ...) \ + UnitTestLog (Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ); + #endif \ No newline at end of file diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc new file mode 100644 index 00000000000..cdacebd5c9a --- /dev/null +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -0,0 +1,27 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdePkgHostTest + PLATFORM_GUID = 50652B4C-88CB-4481-96E8-37F2D0034440 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdePkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[LibraryClasses] + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + +[Components] + # + # Build HOST_APPLICATION that tests the SafeIntLib + # + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf diff --git a/MdePkg/Test/MdePkgTargetTest.dsc b/MdePkg/Test/MdePkgTargetTest.dsc new file mode 100644 index 00000000000..ddabe8c602e --- /dev/null +++ b/MdePkg/Test/MdePkgTargetTest.dsc @@ -0,0 +1,30 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdePkgTargetTest + PLATFORM_GUID = F79ED988-CA41-4D1D-A71B-C4E257695E15 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdePkg/TargetTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc + +[LibraryClasses] + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + +[Components] + # + # Build PEIM, DXE_DRIVER, SMM_DRIVER, UEFI Shell components that test SafeIntLib + # + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index ad0ffd3ede4..082fb0518f0 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -2918,7 +2918,7 @@ TestSafeInt64Mult ( EFI_STATUS EFIAPI UefiTestMain ( - VOID + VOID ) { EFI_STATUS Status; @@ -3087,6 +3087,26 @@ UefiTestMain ( return Status; } +EFI_STATUS +EFIAPI +PeiEntryPoint ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + return UefiTestMain (); +} + +EFI_STATUS +EFIAPI +DxeEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return UefiTestMain (); +} + int main ( int argc, diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index a7bb0edef9a..d4e946743ff 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -29,6 +29,7 @@ #ifndef _TEST_BASE_SAFE_INT_LIB_H_ #define _TEST_BASE_SAFE_INT_LIB_H_ +#include #include #include #include diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.uni b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.uni new file mode 100644 index 00000000000..956835c30d5 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.uni @@ -0,0 +1,13 @@ +// /** @file +// Application that Unit Tests the SafeIntLib +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Application that Unit Tests the SafeIntLib" + +#string STR_MODULE_DESCRIPTION #language en-US "Application that Unit Tests the SafeIntLib." + diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf new file mode 100644 index 00000000000..b693ac7777f --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf @@ -0,0 +1,65 @@ +## @file +# DXE Driver that Unit Tests the SafeIntLib +# +# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibDxe + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 9729DB60-FB9D-4625-9EE1-93B21EC246B8 + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + TestBaseSafeIntLib.h + +[Sources.Ia32] + IA32/SafeIntLibUintnIntnUnitTests.c + +[Sources.X64] + X64/SafeIntLibUintnIntnUnitTests.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + BaseLib + DebugLib + SafeIntLib + UnitTestLib + +[Depex] + TRUE \ No newline at end of file diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf similarity index 82% rename from MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf rename to MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf index 27a7200fe11..b72f329bc68 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf @@ -1,5 +1,5 @@ ## @file -# Uefi OS based Application that Unit Tests the SafeIntLib +# Host OS based Application that Unit Tests the SafeIntLib # # Copyright (c) 2017, Microsoft Corporation # Copyright (c) 2019, Intel Corporation. All rights reserved.
@@ -26,11 +26,12 @@ ## [Defines] - INF_VERSION = 0x00010005 - BASE_NAME = TestBaseSafeIntLib - FILE_GUID = 95487689-9E30-41AD-B773-3650C94BCBE2 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibHost + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 95487689-9E30-41AD-B773-3650C94BCBE2 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 # # The following information is for reference only and not required by the build tools. @@ -57,4 +58,3 @@ DebugLib SafeIntLib UnitTestLib - UnitTestAssertLib diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf new file mode 100644 index 00000000000..aac2e41cb17 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf @@ -0,0 +1,65 @@ +## @file +# PEIM that Unit Tests the SafeIntLib +# +# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibPei + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 7D910602-ED53-45E6-826E-8266705B9734 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = PeiEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + TestBaseSafeIntLib.h + +[Sources.Ia32] + IA32/SafeIntLibUintnIntnUnitTests.c + +[Sources.X64] + X64/SafeIntLibUintnIntnUnitTests.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + PeimEntryPoint + BaseLib + DebugLib + SafeIntLib + UnitTestLib + +[Depex] + TRUE \ No newline at end of file diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf new file mode 100644 index 00000000000..e21b2e5a452 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf @@ -0,0 +1,65 @@ +## @file +# SMM Driver that Unit Tests the SafeIntLib +# +# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibSmm + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 2F2A1907-B1B4-4E33-8B83-62A60AB4F0D4 + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + TestBaseSafeIntLib.h + +[Sources.Ia32] + IA32/SafeIntLibUintnIntnUnitTests.c + +[Sources.X64] + X64/SafeIntLibUintnIntnUnitTests.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + BaseLib + DebugLib + SafeIntLib + UnitTestLib + +[Depex] + TRUE \ No newline at end of file diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf new file mode 100644 index 00000000000..12571ee13fc --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf @@ -0,0 +1,62 @@ +## @file +# UEFI Shell based Application that Unit Tests the SafeIntLib +# +# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# +# All rights reserved. +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# 1. Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimer. +# 2. Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE +# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF +# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = TestBaseSafeIntLibUefiShell + MODULE_UNI_FILE = TestBaseSafeIntLib.uni + FILE_GUID = 1F91B73E-5B6A-4317-80E8-E7C36A3C7AF4 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + TestBaseSafeIntLib.c + TestBaseSafeIntLib.h + +[Sources.Ia32] + IA32/SafeIntLibUintnIntnUnitTests.c + +[Sources.X64] + X64/SafeIntLibUintnIntnUnitTests.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + UefiApplicationEntryPoint + BaseLib + DebugLib + SafeIntLib + UnitTestLib diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf similarity index 62% rename from UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf rename to UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf index bbf3e4616ad..9b88d646a04 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf @@ -7,13 +7,13 @@ ## [Defines] - INF_VERSION = 0x00010005 - BASE_NAME = CmockaLib - MODULE_UNI_FILE = CmockaLib.uni - FILE_GUID = F1662152-3399-49AC-BE44-CAA97575FACE - MODULE_TYPE = BASE - VERSION_STRING = 0.1 - LIBRARY_CLASS = CmockaLib + INF_VERSION = 0x00010005 + BASE_NAME = CmockaLib + MODULE_UNI_FILE = CmockaLib.uni + FILE_GUID = F1662152-3399-49AC-BE44-CAA97575FACE + MODULE_TYPE = BASE + VERSION_STRING = 0.1 + LIBRARY_CLASS = CmockaLib|HOST_APPLICATION # # VALID_ARCHITECTURES = IA32 X64 ARM AARCH64 diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni similarity index 96% rename from UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni rename to UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni index 5a114b93455..67f03288ca3 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.uni +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni @@ -9,8 +9,6 @@ // // **/ - #string STR_MODULE_ABSTRACT #language en-US "Cmocka Library implementation" #string STR_MODULE_DESCRIPTION #language en-US "This module provides Cmocka Library implementation." - diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka b/UnitTestFrameworkPkg/Library/CmockaLib/cmocka similarity index 100% rename from UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/cmocka rename to UnitTestFrameworkPkg/Library/CmockaLib/cmocka diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c deleted file mode 100644 index 43190ff6aff..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLib.c +++ /dev/null @@ -1,191 +0,0 @@ -/** @file - - Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include - -#include -#include - -#define MAX_STRING_SIZE 1025 - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); - _assert_true (Expression, Description, FileName, (INT32)LineNumber); - - return Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); - _assert_true (!Expression, Description, FileName, (INT32)LineNumber); - - return !Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); - _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); - - return !EFI_ERROR (Status); -} - - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); - - return (ValueA == ValueB); -} - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - BOOLEAN Result; - - Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); - _assert_true (Result, TempStr, FileName, (INT32)LineNumber); - - return Result; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); - - return (ValueA != ValueB); -} - - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); - _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); - - return (Status == Expected); -} - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ) -{ - CHAR8 TempStr[MAX_STRING_SIZE]; - - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); - _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); - - return (Pointer != NULL); -} diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf deleted file mode 100644 index 853c703b209..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf +++ /dev/null @@ -1,25 +0,0 @@ -## @file -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestAssertLibCmocka - FILE_GUID = 8841561C-ABF2-4989-9039-4C6485D61C23 - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestAssertLib - -[LibraryClasses] - BaseMemoryLib - CmockaLib - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[Sources] - UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c b/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c deleted file mode 100644 index 29b0d06f47a..00000000000 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLib.c +++ /dev/null @@ -1,497 +0,0 @@ -/** @file - - Copyright (c) 2019, Intel Corporation. All rights reserved.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#define MAX_STRING_SIZE 1025 - -int GroupSetupTemplate (void **state); -int GroupTeardownTemplate (void **state); -void TestFuncTemplate (void **state); -int SetupFuncTemplate (void **state); -int TeardownFuncTemplate (void **state); - -extern UINTN mGroupSetupTemplateSize; -extern UINTN mGroupTeardownTemplateSize; -extern UINTN mTestFuncTemplateSize; -extern UINTN mSetupFuncTemplateSize; -extern UINTN mTeardownFuncTemplateSize; - -// NOTE: Changing structure below requires NASM file update -typedef struct { - CHAR8 *TestName; - CMUnitTestFunction TestFunc; - CMFixtureFunction SetupFunc; - CMFixtureFunction TeardownFunc; - CHAR8 *Description; - CHAR8 *ClassName; //can't have spaces and should be short - UNIT_TEST_FUNCTION RunTest; - UNIT_TEST_PREREQ PreReq; - UNIT_TEST_CLEANUP CleanUp; - UNIT_TEST_CONTEXT Context; - UNIT_TEST_SUITE_HANDLE ParentSuite; - UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; -} MY_UNIT_TEST; - -typedef struct { - LIST_ENTRY Entry; - MY_UNIT_TEST UT; -} MY_UNIT_TEST_LIST_ENTRY; - -// NOTE: Changing structure below requires NASM file update -typedef struct { - UINTN NumTests; - CMFixtureFunction GroupSetup; - CMFixtureFunction GroupTeardown; - CHAR8 *Title; - CHAR8 *Package; - UNIT_TEST_SUITE_SETUP Setup; - UNIT_TEST_SUITE_TEARDOWN Teardown; - LIST_ENTRY TestCaseList; // MY_UNIT_TEST_LIST_ENTRY - UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; -} MY_UNIT_TEST_SUITE; - -typedef struct { - LIST_ENTRY Entry; - MY_UNIT_TEST_SUITE UTS; -} MY_UNIT_TEST_SUITE_LIST_ENTRY; - -typedef struct { - CHAR8 *Title; - CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. - CHAR8 *VersionString; - LIST_ENTRY TestSuiteList; // MY_UNIT_TEST_SUITE_LIST_ENTRY -} MY_UNIT_TEST_FRAMEWORK; - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - -/** - This function will determine whether the short name violates any rules that would - prevent it from being used as a reporting name or as a serialization name. - - Example: If the name cannot be serialized to a filesystem file name. - - @param[in] ShortTitleString A pointer to the short title string to be evaluated. - - @retval TRUE The string is acceptable. - @retval FALSE The string should not be used. - -**/ -STATIC -BOOLEAN -IsFrameworkShortNameValid ( - IN CHAR8 *ShortTitleString - ) -{ - // TODO: Finish this function. - return TRUE; -} // IsFrameworkShortNameValid() - -STATIC -CHAR8* -AllocateAndCopyString ( - IN CHAR8 *StringToCopy - ) -{ - CHAR8 *NewString = NULL; - UINTN NewStringLength; - - NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; - NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); - if (NewString != NULL) - { - AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); - } - - return NewString; -} // AllocateAndCopyString () - - -EFI_STATUS -EFIAPI -FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestFramework() - - -STATIC -EFI_STATUS -FreeUnitTestSuiteEntry ( - IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestSuiteEntry() - - -STATIC -EFI_STATUS -FreeUnitTestTestEntry ( - IN UNIT_TEST_LIST_ENTRY *TestEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestTestEntry() - - - -//============================================================================= -// -// ---------------- TEST SETUP FUNCTIONS ------------------------------------- -// -//============================================================================= - - -/* -Method to Initialize the Unit Test framework - -@retval Success - Unit Test init. -@retval EFI_ERROR - Unit Tests init failed. -*/ -EFI_STATUS -EFIAPI -InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_FRAMEWORK *NewFramework; - - Status = EFI_SUCCESS; - NewFramework = NULL; - - // - // First, check all pointers and make sure nothing's broked. - if (Framework == NULL || Title == NULL || - ShortTitle == NULL || VersionString == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, determine whether all of the strings are good to use. - if (!IsFrameworkShortNameValid( ShortTitle )) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, set aside some space to start messing with the framework. - NewFramework = AllocateZeroPool( sizeof( MY_UNIT_TEST_FRAMEWORK ) ); - if (NewFramework == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Next, set up all the test data. - NewFramework->Title = AllocateAndCopyString( Title ); - NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); - NewFramework->VersionString = AllocateAndCopyString( VersionString ); - if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || - NewFramework->VersionString == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - InitializeListHead( &(NewFramework->TestSuiteList) ); - -Exit: - // - // If we're good, then let's copy the framework. - if (!EFI_ERROR( Status )) - { - *Framework = (UNIT_TEST_FRAMEWORK *)NewFramework; - } - // Otherwise, we need to undo this horrible thing that we've done. - else - { - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); - } - - return Status; -} - -EFI_STATUS -EFIAPI -CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; - MY_UNIT_TEST_FRAMEWORK *MyFramework; - - Status = EFI_SUCCESS; - MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; - - // - // First, let's check to make sure that our parameters look good. - if ((MyFramework == NULL) || (Title == NULL) || (Package == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewSuiteEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_SUITE_LIST_ENTRY ) ); - if (NewSuiteEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewSuiteEntry->UTS.NumTests = 0; - NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); - NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); - NewSuiteEntry->UTS.Setup = Sup; - NewSuiteEntry->UTS.Teardown = Tdn; - NewSuiteEntry->UTS.ParentFramework = MyFramework; - InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. - InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. - if (NewSuiteEntry->UTS.Title == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - if (NewSuiteEntry->UTS.Package == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - NewSuiteEntry->UTS.GroupSetup = (CMFixtureFunction)Sup; - NewSuiteEntry->UTS.GroupTeardown = (CMFixtureFunction)Tdn; - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(MyFramework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); - *Suite = (UNIT_TEST_SUITE *)&NewSuiteEntry->UTS; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestSuiteEntry( (UNIT_TEST_SUITE_LIST_ENTRY *)NewSuiteEntry ); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE Suite, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_SUITE *MySuite; - MY_UNIT_TEST_LIST_ENTRY *NewTestEntry; - UINTN TestNameSize; - - Status = EFI_SUCCESS; - MySuite = (MY_UNIT_TEST_SUITE *)Suite; - - // - // First, let's check to make sure that our parameters look good. - if ((MySuite == NULL) || (Description == NULL) || (ClassName == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewTestEntry = AllocateZeroPool( sizeof( MY_UNIT_TEST_LIST_ENTRY ) ); - if (NewTestEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewTestEntry->UT.Description = AllocateAndCopyString( Description ); - NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); - NewTestEntry->UT.PreReq = PreReq; - NewTestEntry->UT.CleanUp = CleanUp; - NewTestEntry->UT.RunTest = Func; - NewTestEntry->UT.Context = Context; - NewTestEntry->UT.ParentSuite = MySuite; - NewTestEntry->UT.ParentFramework = MySuite->ParentFramework; - InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. - if (NewTestEntry->UT.Description == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - NewTestEntry->UT.TestFunc = (CMUnitTestFunction)Func; - NewTestEntry->UT.SetupFunc = (CMFixtureFunction)PreReq; - NewTestEntry->UT.TeardownFunc = (CMFixtureFunction)CleanUp; - - TestNameSize = AsciiStrLen (Description) + 1; - NewTestEntry->UT.TestName = AllocatePool (TestNameSize); - ASSERT (NewTestEntry->UT.TestName != NULL); - - Status = AsciiStrCpyS (NewTestEntry->UT.TestName, TestNameSize, Description); - ASSERT_EFI_ERROR(Status); - - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(MySuite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); - MySuite->NumTests ++; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestTestEntry( (UNIT_TEST_LIST_ENTRY *)NewTestEntry ); - } - - return Status; -} - - -//============================================================================= -// -// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- -// -//============================================================================= - -EFI_STATUS -EFIAPI -RunAllTestSuites( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - EFI_STATUS Status; - MY_UNIT_TEST_FRAMEWORK *MyFramework; - LIST_ENTRY *TestSuiteList; - LIST_ENTRY *TestSuiteLink; - MY_UNIT_TEST_SUITE_LIST_ENTRY *TestSuiteListEntry; - MY_UNIT_TEST_SUITE *TestSuite; - CHAR8 GroupName[MAX_STRING_SIZE]; - struct CMUnitTest *Tests; - LIST_ENTRY *UnitTestList; - LIST_ENTRY *UnitTestLink; - MY_UNIT_TEST_LIST_ENTRY *UnitTestListEntry; - MY_UNIT_TEST *UnitTest; - UINTN Index; - - // MU_CHANGE - We control this from our build system. - // May need to revisit. - // if (PcdGet8 (HostUnitTestMode) == 1) { - // cmocka_set_message_output (CM_OUTPUT_XML); - // } - - MyFramework = (MY_UNIT_TEST_FRAMEWORK *)Framework; - - TestSuiteList = &MyFramework->TestSuiteList; - for (TestSuiteLink = TestSuiteList->ForwardLink; - TestSuiteLink != TestSuiteList; - TestSuiteLink = TestSuiteLink->ForwardLink) { - TestSuiteListEntry = BASE_CR ( - TestSuiteLink, - MY_UNIT_TEST_SUITE_LIST_ENTRY, - Entry - ); - TestSuite = &TestSuiteListEntry->UTS; - Status = AsciiStrCpyS (GroupName, sizeof(GroupName), TestSuite->Title); - ASSERT_EFI_ERROR(Status); - - Tests = AllocateZeroPool (TestSuite->NumTests * sizeof(struct CMUnitTest)); - ASSERT (Tests != NULL); - Index = 0; - - UnitTestList = &TestSuite->TestCaseList; - for (UnitTestLink = UnitTestList->ForwardLink; - UnitTestLink != UnitTestList; - UnitTestLink = UnitTestLink->ForwardLink) { - UnitTestListEntry = BASE_CR ( - UnitTestLink, - MY_UNIT_TEST_LIST_ENTRY, - Entry - ); - UnitTest = &UnitTestListEntry->UT; - - Tests[Index].name = UnitTest->TestName; - Tests[Index].test_func = UnitTest->TestFunc; - Tests[Index].setup_func = UnitTest->SetupFunc; - Tests[Index].teardown_func = UnitTest->TeardownFunc; - Tests[Index].initial_state = NULL; - Index++; - } - ASSERT (Index == TestSuite->NumTests); - - _cmocka_run_group_tests (GroupName, Tests, TestSuite->NumTests, TestSuite->GroupSetup, TestSuite->GroupTeardown); - FreePool (Tests); - } - - return EFI_SUCCESS; -} - -//============================================================================= -// -// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- -// -//============================================================================= - -EFI_STATUS -EFIAPI -SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - return EFI_UNSUPPORTED; -} // SaveFrameworkState() diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c index 1bc306ca262..12115731998 100644 --- a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c @@ -6,177 +6,272 @@ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include -#include -#include -#include -#include -#include +#include +#include #include #include +#include -#ifndef HOST_DEBUG_MESSAGE -#define HOST_DEBUG_MESSAGE 0 -#endif - -// -// Define the maximum debug and assert message length that this library supports -// +/// +/// Define the maximum debug and assert message length that this library supports +/// #define MAX_DEBUG_MESSAGE_LENGTH 0x100 +/** + Prints a debug message to the debug output device if the specified error level is enabled. + + If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function + GetDebugPrintErrorLevel (), then print the message specified by Format and the + associated variable argument list to the debug output device. + + If Format is NULL, then ASSERT(). + + @param ErrorLevel The error level of the debug message. + @param Format The format string for the debug message to print. + @param ... The variable argument list whose contents are accessed + based on the format string specified by Format. + +**/ VOID EFIAPI -DebugAssert ( - IN CONST CHAR8 *FileName, - IN UINTN LineNumber, - IN CONST CHAR8 *Description +DebugPrint ( + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... ) { -#ifndef TEST_WITH_KLEE - printf ("ASSERT: %s(%d): %s\n", FileName, (INT32)(UINT32)LineNumber, Description); - CpuBreakpoint (); -#endif + VA_LIST Marker; + + VA_START (Marker, Format); + DebugVPrint (ErrorLevel, Format, Marker); + VA_END (Marker); } -BOOLEAN +/** + Prints a debug message to the debug output device if the specified + error level is enabled. + + If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function + GetDebugPrintErrorLevel (), then print the message specified by Format and + the associated variable argument list to the debug output device. + + If Format is NULL, then ASSERT(). + + @param ErrorLevel The error level of the debug message. + @param Format Format string for the debug message to print. + @param VaListMarker VA_LIST marker for the variable argument list. + +**/ +VOID EFIAPI -DebugAssertEnabled ( - VOID +DebugVPrint ( + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN VA_LIST VaListMarker ) { - return TRUE; + CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; + + AsciiVSPrint (Buffer, sizeof (Buffer), Format, VaListMarker); + printf ("%s", Buffer); } +/** + Prints a debug message to the debug output device if the specified + error level is enabled. + This function use BASE_LIST which would provide a more compatible + service than VA_LIST. + + If any bit in ErrorLevel is also set in DebugPrintErrorLevelLib function + GetDebugPrintErrorLevel (), then print the message specified by Format and + the associated variable argument list to the debug output device. + + If Format is NULL, then ASSERT(). + + @param ErrorLevel The error level of the debug message. + @param Format Format string for the debug message to print. + @param BaseListMarker BASE_LIST marker for the variable argument list. + +**/ VOID -PatchFormat ( - IN CONST CHAR8 *Format, - IN CHAR8 *MyFormat +EFIAPI +DebugBPrint ( + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + IN BASE_LIST BaseListMarker ) { - UINTN Index; - UINTN MyIndex; - - Index = 0; - MyIndex = 0; - while (Format[Index] != 0) { - MyFormat[MyIndex] = Format[Index]; - if (Format[Index] == '%') { - Index++; - MyIndex++; - switch (Format[Index]) { - case 'a': - MyFormat[MyIndex] = 's'; - break; - case 's': - MyFormat[MyIndex] = 'w'; - MyIndex++; - MyFormat[MyIndex] = 's'; - break; - case 'g': - case 't': - MyFormat[MyIndex] = 'p'; - break; - case 'r': - MyFormat[MyIndex] = 'x'; - break; - case 'L': - case 'l': - MyFormat[MyIndex] = 'I'; - MyIndex++; - MyFormat[MyIndex] = '6'; - MyIndex++; - MyFormat[MyIndex] = '4'; - break; - case '0': - MyFormat[MyIndex] = Format[Index]; - if (Format[Index + 1] == '1') { - Index++; - MyIndex++; - MyFormat[MyIndex] = Format[Index]; - } - case '1': - MyFormat[MyIndex] = Format[Index]; - if (Format[Index + 1] == '6') { - Index++; - MyIndex++; - MyFormat[MyIndex] = Format[Index]; - } - if (Format[Index + 1] == 'l') { - Index++; - MyIndex++; - MyFormat[MyIndex] = 'I'; - MyIndex++; - MyFormat[MyIndex] = '6'; - MyIndex++; - MyFormat[MyIndex] = '4'; - } - if (Format[Index + 1] == 'l') { - Index++; - } - break; - default: - MyFormat[MyIndex] = Format[Index]; - break; - } - } - Index++; - MyIndex++; - } - MyFormat[MyIndex] = 0; + CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; + + AsciiBSPrint (Buffer, sizeof (Buffer), Format, BaseListMarker); + printf ("%s", Buffer); } +/** + Prints an assert message containing a filename, line number, and description. + This may be followed by a breakpoint or a dead loop. + + Print a message of the form "ASSERT (): \n" + to the debug output device. If DEBUG_PROPERTY_ASSERT_BREAKPOINT_ENABLED bit of + PcdDebugProperyMask is set then CpuBreakpoint() is called. Otherwise, if + DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED bit of PcdDebugProperyMask is set then + CpuDeadLoop() is called. If neither of these bits are set, then this function + returns immediately after the message is printed to the debug output device. + DebugAssert() must actively prevent recursion. If DebugAssert() is called while + processing another DebugAssert(), then DebugAssert() must return immediately. + + If FileName is NULL, then a string of "(NULL) Filename" is printed. + If Description is NULL, then a string of "(NULL) Description" is printed. + + @param FileName The pointer to the name of the source file that generated the assert condition. + @param LineNumber The line number in the source file that generated the assert condition + @param Description The pointer to the description of the assert condition. + +**/ VOID EFIAPI -DebugPrint ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - ... +DebugAssert ( + IN CONST CHAR8 *FileName, + IN UINTN LineNumber, + IN CONST CHAR8 *Description ) { -#ifndef TEST_WITH_KLEE -#if HOST_DEBUG_MESSAGE - CHAR8 Buffer[MAX_DEBUG_MESSAGE_LENGTH]; - CHAR8 MyFormat[MAX_DEBUG_MESSAGE_LENGTH]; - VA_LIST Marker; - - VA_START (Marker, Format); + printf ("ASSERT: %s(%d): %s\n", FileName, (INT32)(UINT32)LineNumber, Description); - if (0) { - PatchFormat (Format, MyFormat); - vsprintf (Buffer, MyFormat, Marker); - } else { - AsciiVSPrint (Buffer, sizeof (Buffer), Format, Marker); + // + // Generate a Breakpoint, DeadLoop, or NOP based on PCD settings + // + if ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_ASSERT_BREAKPOINT_ENABLED) != 0) { + CpuBreakpoint (); + } else if ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED) != 0) { + CpuDeadLoop (); } - VA_END (Marker); +} - printf ("%s", Buffer); -#endif -#endif +/** + Fills a target buffer with PcdDebugClearMemoryValue, and returns the target buffer. + + This function fills Length bytes of Buffer with the value specified by + PcdDebugClearMemoryValue, and returns Buffer. + + If Buffer is NULL, then ASSERT(). + If Length is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param Buffer The pointer to the target buffer to be filled with PcdDebugClearMemoryValue. + @param Length The number of bytes in Buffer to fill with zeros PcdDebugClearMemoryValue. + + @return Buffer The pointer to the target buffer filled with PcdDebugClearMemoryValue. + +**/ +VOID * +EFIAPI +DebugClearMemory ( + OUT VOID *Buffer, + IN UINTN Length + ) +{ + // + // If Buffer is NULL, then ASSERT(). + // + ASSERT (Buffer != NULL); + + // + // SetMem() checks for the the ASSERT() condition on Length and returns Buffer + // + return SetMem (Buffer, Length, PcdGet8(PcdDebugClearMemoryValue)); } +/** + Returns TRUE if ASSERT() macros are enabled. + + This function returns TRUE if the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of + PcdDebugProperyMask is set. Otherwise FALSE is returned. + + @retval TRUE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear. + +**/ BOOLEAN EFIAPI -DebugPrintEnabled ( +DebugAssertEnabled ( VOID ) { - return TRUE; + return (BOOLEAN) ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED) != 0); } +/** + Returns TRUE if DEBUG() macros are enabled. + + This function returns TRUE if the DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of + PcdDebugProperyMask is set. Otherwise FALSE is returned. + + @retval TRUE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is clear. + +**/ BOOLEAN EFIAPI -DebugPrintLevelEnabled ( - IN CONST UINTN ErrorLevel +DebugPrintEnabled ( + VOID ) { - return TRUE; + return (BOOLEAN) ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_PRINT_ENABLED) != 0); } +/** + Returns TRUE if DEBUG_CODE() macros are enabled. + + This function returns TRUE if the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of + PcdDebugProperyMask is set. Otherwise FALSE is returned. + + @retval TRUE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is clear. + +**/ BOOLEAN EFIAPI DebugCodeEnabled ( VOID ) { - return TRUE; + return (BOOLEAN) ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_DEBUG_CODE_ENABLED) != 0); +} + +/** + Returns TRUE if DEBUG_CLEAR_MEMORY() macro is enabled. + + This function returns TRUE if the DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of + PcdDebugProperyMask is set. Otherwise FALSE is returned. + + @retval TRUE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is set. + @retval FALSE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is clear. + +**/ +BOOLEAN +EFIAPI +DebugClearMemoryEnabled ( + VOID + ) +{ + return (BOOLEAN) ((PcdGet8(PcdDebugPropertyMask) & DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED) != 0); +} + +/** + Returns TRUE if any one of the bit is set both in ErrorLevel and PcdFixedDebugPrintErrorLevel. + + This function compares the bit mask of ErrorLevel and PcdFixedDebugPrintErrorLevel. + + @retval TRUE Current ErrorLevel is supported. + @retval FALSE Current ErrorLevel is not supported. + +**/ +BOOLEAN +EFIAPI +DebugPrintLevelEnabled ( + IN CONST UINTN ErrorLevel + ) +{ + return (BOOLEAN) ((ErrorLevel & PcdGet32(PcdFixedDebugPrintErrorLevel)) != 0); } diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf index c1ff5773c12..87617921e60 100644 --- a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf @@ -1,17 +1,21 @@ ## @file +# Instance of Debug Library based on POSIX APIs # -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent +# Uses Print Library to produce formatted output strings sent to printf(). +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## [Defines] - INF_VERSION = 0x00010005 - BASE_NAME = DebugLibPosix - FILE_GUID = 6A77CE89-C1B6-4A6B-9561-07D7127514A7 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = DebugLib | HOST_APPLICATION + INF_VERSION = 0x00010005 + BASE_NAME = DebugLibPosix + MODULE_UNI_FILE = DebugLibPosix.uni + FILE_GUID = 6A77CE89-C1B6-4A6B-9561-07D7127514A7 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = DebugLib|HOST_APPLICATION [Sources] DebugLibPosix.c @@ -20,11 +24,12 @@ MdePkg/MdePkg.dec [LibraryClasses] - BaseLib + BaseMemoryLib + PcdLib PrintLib + BaseLib -[BuildOptions] - MSFT:*_*_*_CC_FLAGS = /D _CRT_SECURE_NO_WARNINGS - GCC:*_KLEE_*_CC_FLAGS = "-DTEST_WITH_KLEE=TRUE" - - +[Pcd] + gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue ## SOMETIMES_CONSUMES + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask ## CONSUMES + gEfiMdePkgTokenSpaceGuid.PcdFixedDebugPrintErrorLevel ## CONSUMES diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.uni b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.uni new file mode 100644 index 00000000000..d34f1a05bee --- /dev/null +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.uni @@ -0,0 +1,14 @@ +// /** @file +// Instance of Debug Library based on POSIX APIs +// +// Uses Print Library to produce formatted output strings sent to printf(). +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Instance of Debug Library based on POSIX APIs" + +#string STR_MODULE_DESCRIPTION #language en-US "Uses Print Library to produce formatted output strings sent to printf()." diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c index 9bc8838a438..bb4700163c0 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c @@ -1,41 +1,52 @@ /** @file + Instance of Memory Allocation Library based on POSIX APIs -Copyright (c) 2018, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent + Uses POSIX APIs malloc() and free() to allocate and free memory. + + Copyright (c) 2018, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ -#include #include #include -#include #include +#include +#include +/// +/// Signature for PAGE_HEAD structure +/// Used to verify that buffer being freed was allocated by this library. +/// #define PAGE_HEAD_PRIVATE_SIGNATURE SIGNATURE_32 ('P', 'H', 'D', 'R') +/// +/// Structure placed immediately before an aligned allocation to store the +/// information required to free the entire buffer allocated to support then +/// aligned alocation. +/// typedef struct { - UINT32 Signature; - VOID *AllocatedBufffer; - UINTN TotalPages; - VOID *AlignedBuffer; - UINTN AlignedPages; + UINT32 Signature; + VOID *AllocatedBufffer; + UINTN TotalPages; + VOID *AlignedBuffer; + UINTN AlignedPages; } PAGE_HEAD; -VOID * -EFIAPI -AllocateAlignedPages ( - IN UINTN Pages, - IN UINTN Alignment - ); +/** + Allocates one or more 4KB pages of type EfiBootServicesData. -VOID -EFIAPI -FreeAlignedPages ( - IN VOID *Buffer, - IN UINTN Pages - ); + Allocates the number of 4KB pages of type EfiBootServicesData and returns a pointer to the + allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL + is returned. If there is not enough memory remaining to satisfy the request, then NULL is + returned. + + @param Pages The number of 4 KB pages to allocate. + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocatePages ( @@ -45,6 +56,19 @@ AllocatePages ( return AllocateAlignedPages (Pages, SIZE_4KB); } +/** + Allocates one or more 4KB pages of type EfiRuntimeServicesData. + + Allocates the number of 4KB pages of type EfiRuntimeServicesData and returns a pointer to the + allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL + is returned. If there is not enough memory remaining to satisfy the request, then NULL is + returned. + + @param Pages The number of 4 KB pages to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateRuntimePages ( @@ -54,6 +78,19 @@ AllocateRuntimePages ( return AllocatePages (Pages); } +/** + Allocates one or more 4KB pages of type EfiReservedMemoryType. + + Allocates the number of 4KB pages of type EfiReservedMemoryType and returns a pointer to the + allocated buffer. The buffer returned is aligned on a 4KB boundary. If Pages is 0, then NULL + is returned. If there is not enough memory remaining to satisfy the request, then NULL is + returned. + + @param Pages The number of 4 KB pages to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateReservedPages ( @@ -63,6 +100,23 @@ AllocateReservedPages ( return AllocatePages (Pages); } +/** + Frees one or more 4KB pages that were previously allocated with one of the page allocation + functions in the Memory Allocation Library. + + Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer + must have been allocated on a previous call to the page allocation services of the Memory + Allocation Library. If it is not possible to free allocated pages, then this function will + perform no actions. + + If Buffer was not allocated with a page allocation function in the Memory Allocation Library, + then ASSERT(). + If Pages is zero, then ASSERT(). + + @param Buffer The pointer to the buffer of pages to free. + @param Pages The number of 4 KB pages to free. + +**/ VOID EFIAPI FreePages ( @@ -73,18 +127,35 @@ FreePages ( FreeAlignedPages (Buffer, Pages); } -VOID * +/** + Allocates one or more 4KB pages of type EfiBootServicesData at a specified alignment. + + Allocates the number of 4KB pages specified by Pages of type EfiBootServicesData with an + alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is + returned. If there is not enough memory at the specified alignment remaining to satisfy the + request, then NULL is returned. + + If Alignment is not a power of two and Alignment is not zero, then ASSERT(). + If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). + + @param Pages The number of 4 KB pages to allocate. + @param Alignment The requested alignment of the allocation. Must be a power of two. + If Alignment is zero, then byte alignment is used. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/VOID * EFIAPI AllocateAlignedPages ( IN UINTN Pages, IN UINTN Alignment ) { - PAGE_HEAD PageHead; - PAGE_HEAD *PageHeadPtr; - UINTN AlignmentMask; + PAGE_HEAD PageHead; + PAGE_HEAD *PageHeadPtr; + UINTN AlignmentMask; - assert ((Alignment & (Alignment - 1)) == 0); + ASSERT ((Alignment & (Alignment - 1)) == 0); if (Alignment < SIZE_4KB) { Alignment = SIZE_4KB; @@ -94,11 +165,10 @@ AllocateAlignedPages ( // // We need reserve Alignment pages for PAGE_HEAD, as meta data. // - PageHead.Signature = PAGE_HEAD_PRIVATE_SIGNATURE; - PageHead.TotalPages = Pages + EFI_SIZE_TO_PAGES(Alignment) * 2; + PageHead.TotalPages = Pages + EFI_SIZE_TO_PAGES (Alignment) * 2; PageHead.AlignedPages = Pages; - PageHead.AllocatedBufffer = malloc (EFI_PAGES_TO_SIZE(PageHead.TotalPages)); + PageHead.AllocatedBufffer = malloc (EFI_PAGES_TO_SIZE (PageHead.TotalPages)); if (PageHead.AllocatedBufffer == NULL) { return NULL; } @@ -113,6 +183,24 @@ AllocateAlignedPages ( return PageHead.AlignedBuffer; } +/** + Allocates one or more 4KB pages of type EfiRuntimeServicesData at a specified alignment. + + Allocates the number of 4KB pages specified by Pages of type EfiRuntimeServicesData with an + alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is + returned. If there is not enough memory at the specified alignment remaining to satisfy the + request, then NULL is returned. + + If Alignment is not a power of two and Alignment is not zero, then ASSERT(). + If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). + + @param Pages The number of 4 KB pages to allocate. + @param Alignment The requested alignment of the allocation. Must be a power of two. + If Alignment is zero, then byte alignment is used. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateAlignedRuntimePages ( @@ -123,6 +211,24 @@ AllocateAlignedRuntimePages ( return AllocateAlignedPages (Pages, Alignment); } +/** + Allocates one or more 4KB pages of type EfiReservedMemoryType at a specified alignment. + + Allocates the number of 4KB pages specified by Pages of type EfiReservedMemoryType with an + alignment specified by Alignment. The allocated buffer is returned. If Pages is 0, then NULL is + returned. If there is not enough memory at the specified alignment remaining to satisfy the + request, then NULL is returned. + + If Alignment is not a power of two and Alignment is not zero, then ASSERT(). + If Pages plus EFI_SIZE_TO_PAGES (Alignment) overflows, then ASSERT(). + + @param Pages The number of 4 KB pages to allocate. + @param Alignment The requested alignment of the allocation. Must be a power of two. + If Alignment is zero, then byte alignment is used. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateAlignedReservedPages ( @@ -133,6 +239,23 @@ AllocateAlignedReservedPages ( return AllocateAlignedPages (Pages, Alignment); } +/** + Frees one or more 4KB pages that were previously allocated with one of the aligned page + allocation functions in the Memory Allocation Library. + + Frees the number of 4KB pages specified by Pages from the buffer specified by Buffer. Buffer + must have been allocated on a previous call to the aligned page allocation services of the Memory + Allocation Library. If it is not possible to free allocated pages, then this function will + perform no actions. + + If Buffer was not allocated with an aligned page allocation function in the Memory Allocation + Library, then ASSERT(). + If Pages is zero, then ASSERT(). + + @param Buffer The pointer to the buffer of pages to free. + @param Pages The number of 4 KB pages to free. + +**/ VOID EFIAPI FreeAlignedPages ( @@ -140,25 +263,35 @@ FreeAlignedPages ( IN UINTN Pages ) { - PAGE_HEAD *PageHeadPtr; + PAGE_HEAD *PageHeadPtr; // // NOTE: Partial free is not supported. Just keep it. // - PageHeadPtr = (VOID *)((UINTN)Buffer - sizeof(PAGE_HEAD)); if (PageHeadPtr->Signature != PAGE_HEAD_PRIVATE_SIGNATURE) { - return ; + return; } if (PageHeadPtr->AlignedPages != Pages) { - return ; + return; } PageHeadPtr->Signature = 0; free (PageHeadPtr->AllocatedBufffer); } -VOID * +/** + Allocates a buffer of type EfiBootServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiBootServicesData and returns a + pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is + returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/VOID * EFIAPI AllocatePool ( IN UINTN AllocationSize @@ -167,6 +300,18 @@ AllocatePool ( return malloc (AllocationSize); } +/** + Allocates a buffer of type EfiRuntimeServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData and returns + a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is + returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateRuntimePool ( @@ -176,6 +321,18 @@ AllocateRuntimePool ( return AllocatePool (AllocationSize); } +/** + Allocates a buffer of type EfiReservedMemoryType. + + Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType and returns + a pointer to the allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is + returned. If there is not enough memory remaining to satisfy the request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateReservedPool ( @@ -185,13 +342,27 @@ AllocateReservedPool ( return AllocatePool (AllocationSize); } +/** + Allocates and zeros a buffer of type EfiBootServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, clears the + buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a + valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the + request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate and zero. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateZeroPool ( IN UINTN AllocationSize ) { - VOID *Buffer; + VOID *Buffer; + Buffer = malloc (AllocationSize); if (Buffer == NULL) { return NULL; @@ -200,6 +371,19 @@ AllocateZeroPool ( return Buffer; } +/** + Allocates and zeros a buffer of type EfiRuntimeServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, clears the + buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a + valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the + request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate and zero. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateRuntimeZeroPool ( @@ -209,6 +393,19 @@ AllocateRuntimeZeroPool ( return AllocateZeroPool (AllocationSize); } +/** + Allocates and zeros a buffer of type EfiReservedMemoryType. + + Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, clears the + buffer with zeros, and returns a pointer to the allocated buffer. If AllocationSize is 0, then a + valid buffer of 0 size is returned. If there is not enough memory remaining to satisfy the + request, then NULL is returned. + + @param AllocationSize The number of bytes to allocate and zero. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateReservedZeroPool ( @@ -218,6 +415,23 @@ AllocateReservedZeroPool ( return AllocateZeroPool (AllocationSize); } +/** + Copies a buffer to an allocated buffer of type EfiBootServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiBootServicesData, copies + AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the + allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there + is not enough memory remaining to satisfy the request, then NULL is returned. + + If Buffer is NULL, then ASSERT(). + If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param AllocationSize The number of bytes to allocate and zero. + @param Buffer The buffer to copy to the allocated buffer. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateCopyPool ( @@ -226,6 +440,7 @@ AllocateCopyPool ( ) { VOID *Memory; + Memory = malloc (AllocationSize); if (Memory == NULL) { return NULL; @@ -234,6 +449,23 @@ AllocateCopyPool ( return Memory; } +/** + Copies a buffer to an allocated buffer of type EfiRuntimeServicesData. + + Allocates the number bytes specified by AllocationSize of type EfiRuntimeServicesData, copies + AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the + allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there + is not enough memory remaining to satisfy the request, then NULL is returned. + + If Buffer is NULL, then ASSERT(). + If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param AllocationSize The number of bytes to allocate and zero. + @param Buffer The buffer to copy to the allocated buffer. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateRuntimeCopyPool ( @@ -244,6 +476,23 @@ AllocateRuntimeCopyPool ( return AllocateCopyPool (AllocationSize, Buffer); } +/** + Copies a buffer to an allocated buffer of type EfiReservedMemoryType. + + Allocates the number bytes specified by AllocationSize of type EfiReservedMemoryType, copies + AllocationSize bytes from Buffer to the newly allocated buffer, and returns a pointer to the + allocated buffer. If AllocationSize is 0, then a valid buffer of 0 size is returned. If there + is not enough memory remaining to satisfy the request, then NULL is returned. + + If Buffer is NULL, then ASSERT(). + If AllocationSize is greater than (MAX_ADDRESS - Buffer + 1), then ASSERT(). + + @param AllocationSize The number of bytes to allocate and zero. + @param Buffer The buffer to copy to the allocated buffer. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI AllocateReservedCopyPool ( @@ -254,15 +503,37 @@ AllocateReservedCopyPool ( return AllocateCopyPool (AllocationSize, Buffer); } +/** + Reallocates a buffer of type EfiBootServicesData. + + Allocates and zeros the number bytes specified by NewSize from memory of type + EfiBootServicesData. If OldBuffer is not NULL, then the smaller of OldSize and + NewSize bytes are copied from OldBuffer to the newly allocated buffer, and + OldBuffer is freed. A pointer to the newly allocated buffer is returned. + If NewSize is 0, then a valid buffer of 0 size is returned. If there is not + enough memory remaining to satisfy the request, then NULL is returned. + + If the allocation of the new buffer is successful and the smaller of NewSize and OldSize + is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). + + @param OldSize The size, in bytes, of OldBuffer. + @param NewSize The size, in bytes, of the buffer to reallocate. + @param OldBuffer The buffer to copy to the allocated buffer. This is an optional + parameter that may be NULL. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI ReallocatePool ( IN UINTN OldSize, IN UINTN NewSize, - IN VOID *OldBuffer OPTIONAL + IN VOID *OldBuffer OPTIONAL ) { VOID *NewBuffer; + NewBuffer = malloc (NewSize); if (NewBuffer != NULL && OldBuffer != NULL) { memcpy (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); @@ -270,32 +541,88 @@ ReallocatePool ( return NewBuffer; } +/** + Reallocates a buffer of type EfiRuntimeServicesData. + + Allocates and zeros the number bytes specified by NewSize from memory of type + EfiRuntimeServicesData. If OldBuffer is not NULL, then the smaller of OldSize and + NewSize bytes are copied from OldBuffer to the newly allocated buffer, and + OldBuffer is freed. A pointer to the newly allocated buffer is returned. + If NewSize is 0, then a valid buffer of 0 size is returned. If there is not + enough memory remaining to satisfy the request, then NULL is returned. + + If the allocation of the new buffer is successful and the smaller of NewSize and OldSize + is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). + + @param OldSize The size, in bytes, of OldBuffer. + @param NewSize The size, in bytes, of the buffer to reallocate. + @param OldBuffer The buffer to copy to the allocated buffer. This is an optional + parameter that may be NULL. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI ReallocateRuntimePool ( IN UINTN OldSize, IN UINTN NewSize, - IN VOID *OldBuffer OPTIONAL + IN VOID *OldBuffer OPTIONAL ) { return ReallocatePool (OldSize, NewSize, OldBuffer); } +/** + Reallocates a buffer of type EfiReservedMemoryType. + + Allocates and zeros the number bytes specified by NewSize from memory of type + EfiReservedMemoryType. If OldBuffer is not NULL, then the smaller of OldSize and + NewSize bytes are copied from OldBuffer to the newly allocated buffer, and + OldBuffer is freed. A pointer to the newly allocated buffer is returned. + If NewSize is 0, then a valid buffer of 0 size is returned. If there is not + enough memory remaining to satisfy the request, then NULL is returned. + + If the allocation of the new buffer is successful and the smaller of NewSize and OldSize + is greater than (MAX_ADDRESS - OldBuffer + 1), then ASSERT(). + + @param OldSize The size, in bytes, of OldBuffer. + @param NewSize The size, in bytes, of the buffer to reallocate. + @param OldBuffer The buffer to copy to the allocated buffer. This is an optional + parameter that may be NULL. + + @return A pointer to the allocated buffer or NULL if allocation fails. + +**/ VOID * EFIAPI ReallocateReservedPool ( IN UINTN OldSize, IN UINTN NewSize, - IN VOID *OldBuffer OPTIONAL + IN VOID *OldBuffer OPTIONAL ) { return ReallocatePool (OldSize, NewSize, OldBuffer); } +/** + Frees a buffer that was previously allocated with one of the pool allocation functions in the + Memory Allocation Library. + + Frees the buffer specified by Buffer. Buffer must have been allocated on a previous call to the + pool allocation services of the Memory Allocation Library. If it is not possible to free pool + resources, then this function will perform no actions. + + If Buffer was not allocated with a pool allocation function in the Memory Allocation Library, + then ASSERT(). + + @param Buffer The pointer to the buffer to free. + +**/ VOID EFIAPI FreePool ( - IN VOID *Buffer + IN VOID *Buffer ) { free (Buffer); diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf index 8d1e08994e4..813f9806eac 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf @@ -1,17 +1,21 @@ ## @file +# Instance of Memory Allocation Library based on POSIX APIs # -# Copyright (c) 2018, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent +# Uses POSIX APIs malloc() and free() to allocate and free memory. +# +# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## [Defines] - INF_VERSION = 0x00010005 - BASE_NAME = MemoryAllocationLibPosix - FILE_GUID = A1672454-A3D3-4AAC-A86B-8D63132BBB91 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - LIBRARY_CLASS = MemoryAllocationLib | HOST_APPLICATION + INF_VERSION = 0x00010005 + BASE_NAME = MemoryAllocationLibPosix + MODULE_UNI_FILE = MemoryAllocationLibPosix.uni + FILE_GUID = A1672454-A3D3-4AAC-A86B-8D63132BBB91 + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = MemoryAllocationLib|HOST_APPLICATION [Sources] MemoryAllocationLibPosix.c @@ -21,4 +25,3 @@ [LibraryClasses] BaseLib - diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.uni b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.uni new file mode 100644 index 00000000000..854b4279764 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.uni @@ -0,0 +1,14 @@ +// /** @file +// Instance of Memory Allocation Library based on POSIX APIs +// +// Uses POSIX APIs malloc() and free() to allocate and free memory. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// +// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Instance of Memory Allocation Library based on POSIX APIs" + +#string STR_MODULE_DESCRIPTION #language en-US "Uses POSIX APIs malloc() and free() to allocate and free memory." diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c deleted file mode 100644 index 1491bb5b2d7..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.c +++ /dev/null @@ -1,235 +0,0 @@ -/** - -Implement UnitTestLib - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include - -#include -#include - - -STATIC -EFI_STATUS -AddUnitTestFailure( - IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR8 *FailureMessage, - IN FAILURE_TYPE FailureType - ) -{ - // - // Make sure that you're cooking with gas. - // - if (UnitTest == NULL || FailureMessage == NULL) - { - return EFI_INVALID_PARAMETER; - } - - UnitTest->FailureType = FailureType; - AsciiStrCpyS(&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); - - return EFI_SUCCESS; -} // AddUnitTestFailure() - - -STATIC -VOID -UnitTestLogFailure( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN FAILURE_TYPE FailureType, - IN CONST CHAR8 *Format, - ... - ) -{ - CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - VA_LIST Marker; - - - // - // Convert the message to an ASCII String - // - VA_START(Marker, Format); - AsciiVSPrint(LogString, sizeof(LogString), Format, Marker); - VA_END(Marker); - - // - // Finally, add the string to the log. - // - AddUnitTestFailure(((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString, FailureType); - - return; -} // UnitTestLogFailure() - - -BOOLEAN -EFIAPI -UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (!Expression) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); - } - return Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (Expression) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - } - return !Expression; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if (EFI_ERROR( Status )) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); - } - return !EFI_ERROR( Status ); -} - - -BOOLEAN -EFIAPI -UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if ((ValueA != ValueB)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); - } - return (ValueA == ValueB); -} - -BOOLEAN -EFIAPI -UnitTestAssertMemEqual( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - return FALSE; - } - return TRUE; -} - - -BOOLEAN -EFIAPI -UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB - ) -{ - if ((ValueA == ValueB)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); - } - return (ValueA != ValueB); -} - - -BOOLEAN -EFIAPI -UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description - ) -{ - if ((Status != Expected)) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); - UnitTestLog(Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); - } - return (Status == Expected); -} - -BOOLEAN -EFIAPI -UnitTestAssertNotNull( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName - ) -{ - if (Pointer == NULL) - { - UnitTestLogFailure(Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - UnitTestLog(Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - } - return (Pointer != NULL); - -} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf deleted file mode 100644 index a3a0df2fdf1..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf +++ /dev/null @@ -1,38 +0,0 @@ -## @file -# Library to support simple and readable Unit Test Assert -# -# -# @copyright -# Copyright (c) 2017 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestAssertLib -FILE_GUID = FDDB0735-04FE-447C-B987-305988BDC983 -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestAssertLib - - -[LibraryClasses] - DebugLib - BaseLib - BaseMemoryLib - UnitTestLogLib - PrintLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - -[Sources] - UnitTestAssertLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c deleted file mode 100644 index 762543ed9db..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.c +++ /dev/null @@ -1,18 +0,0 @@ -/** - -NULL implementation for UnitTestBootLib to allow simple compliation - - -Copyright (c) Microsoft -**/ - -#include - -EFI_STATUS -EFIAPI -SetBootNextDevice( - VOID -) -{ - return EFI_UNSUPPORTED; -} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf deleted file mode 100644 index b05a5fc7d48..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf +++ /dev/null @@ -1,28 +0,0 @@ -## @file -# NULL library for UnitTestBootUsb -# -# -# @copyright -# Copyright (c) 2018 Microsoft Corporation. All rights reserved -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestBootLibNull -FILE_GUID = f143e75d-76e1-4040-b134-8f4f0bd5e3bd -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestBootLib - - -[LibraryClasses] - -[Packages] - MdePkg/MdePkg.dec - -[Guids] - -[Sources] - UnitTestBootLibNull.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c deleted file mode 100644 index bd3d956c1bb..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLib.c +++ /dev/null @@ -1,858 +0,0 @@ -/** -Implement UnitTestLib - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include - -#include -#include -#include -#include - - -// Prototyped here so that it can be included near the functions that -// it logically goes with. -STATIC -VOID -UpdateTestFromSave ( - IN OUT UNIT_TEST *Test, - IN UNIT_TEST_SAVE_HEADER *SavedState - ); - - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - - -/** - This function will determine whether the short name violates any rules that would - prevent it from being used as a reporting name or as a serialization name. - - Example: If the name cannot be serialized to a filesystem file name. - - @param[in] ShortTitleString A pointer to the short title string to be evaluated. - - @retval TRUE The string is acceptable. - @retval FALSE The string should not be used. - -**/ -STATIC -BOOLEAN -IsFrameworkShortNameValid ( - IN CHAR8 *ShortTitleString - ) -{ - // TODO: Finish this function. - return TRUE; -} // IsFrameworkShortNameValid() - - -STATIC -CHAR8* -AllocateAndCopyString ( - IN CHAR8 *StringToCopy - ) -{ - CHAR8 *NewString = NULL; - UINTN NewStringLength; - - NewStringLength = AsciiStrnLenS( StringToCopy, UNIT_TEST_MAX_STRING_LENGTH ) + 1; - NewString = AllocatePool( NewStringLength * sizeof( CHAR8 ) ); - if (NewString != NULL) - { - AsciiStrCpyS( NewString, NewStringLength, StringToCopy ); - } - - return NewString; -} // AllocateAndCopyString () - - -STATIC -VOID -SetFrameworkFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - UINT32 NewFingerprint; - - // For this one we'll just use the title and version as the unique fingerprint. - NewFingerprint = CalculateCrc32( Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetFrameworkFingerprint() - - -STATIC -VOID -SetSuiteFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_FRAMEWORK *Framework, - IN UNIT_TEST_SUITE *Suite - ) -{ - UINT32 NewFingerprint; - - // For this one, we'll use the fingerprint from the framework, and the title of the suite. - NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetSuiteFingerprint() - - -STATIC -VOID -SetTestFingerprint ( - OUT UINT8 *Fingerprint, - IN UNIT_TEST_SUITE *Suite, - IN UNIT_TEST *Test - ) -{ - UINT32 NewFingerprint; - - // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. - NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); - - CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); - return; -} // SetTestFingerprint() - - -STATIC -BOOLEAN -CompareFingerprints ( - IN UINT8 *FingerprintA, - IN UINT8 *FingerprintB - ) -{ - return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); -} // SetTestFingerprint() - - -EFI_STATUS -EFIAPI -FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestFramework() - - -STATIC -EFI_STATUS -FreeUnitTestSuiteEntry ( - IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestSuiteEntry() - - -STATIC -EFI_STATUS -FreeUnitTestTestEntry ( - IN UNIT_TEST_LIST_ENTRY *TestEntry - ) -{ - // TODO: Finish this function. - return EFI_SUCCESS; -} // FreeUnitTestTestEntry() - - -//============================================================================= -// -// ---------------- TEST SETUP FUNCTIONS ------------------------------------- -// -//============================================================================= - - -/* -Method to Initialize the Unit Test framework - -@retval Success - Unit Test init. -@retval EFI_ERROR - Unit Tests init failed. -*/ -EFI_STATUS -EFIAPI -InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, - IN CHAR8 *Title, - IN CHAR8 *ShortTitle, - IN CHAR8 *VersionString - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_FRAMEWORK *NewFramework = NULL; - - // - // First, check all pointers and make sure nothing's broked. - if (Framework == NULL || Title == NULL || - ShortTitle == NULL || VersionString == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, determine whether all of the strings are good to use. - if (!IsFrameworkShortNameValid( ShortTitle )) - { - return EFI_INVALID_PARAMETER; - } - - // - // Next, set aside some space to start messing with the framework. - NewFramework = AllocateZeroPool( sizeof( UNIT_TEST_FRAMEWORK ) ); - if (NewFramework == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Next, set up all the test data. - NewFramework->Title = AllocateAndCopyString( Title ); - NewFramework->ShortTitle = AllocateAndCopyString( ShortTitle ); - NewFramework->VersionString = AllocateAndCopyString( VersionString ); - NewFramework->Log = NULL; - NewFramework->CurrentTest = NULL; - NewFramework->SavedState = NULL; - if (NewFramework->Title == NULL || NewFramework->ShortTitle == NULL || - NewFramework->VersionString == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - InitializeListHead( &(NewFramework->TestSuiteList) ); - - // - // Create the framework fingerprint. - SetFrameworkFingerprint( &NewFramework->Fingerprint[0], NewFramework ); - - // - // If there is a persisted context, load it now. - if (DoesCacheExist( NewFramework )) - { - UNIT_TEST_SAVE_HEADER *SavedState = (UNIT_TEST_SAVE_HEADER*)NewFramework->SavedState; - Status = LoadUnitTestCache( NewFramework, &SavedState ); - if (EFI_ERROR( Status )) - { - // Don't actually report it as an error, but emit a warning. - DEBUG(( DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__ )); - Status = EFI_SUCCESS; - } - } - -Exit: - // - // If we're good, then let's copy the framework. - if (!EFI_ERROR( Status )) - { - *Framework = NewFramework; - } - // Otherwise, we need to undo this horrible thing that we've done. - else - { - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; - UNIT_TEST_FRAMEWORK *Framework; - - Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - - // - // First, let's check to make sure that our parameters look good. - if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewSuiteEntry = AllocateZeroPool( sizeof( UNIT_TEST_SUITE_LIST_ENTRY ) ); - if (NewSuiteEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewSuiteEntry->UTS.Title = AllocateAndCopyString( Title ); - NewSuiteEntry->UTS.Package = AllocateAndCopyString(Package); - NewSuiteEntry->UTS.Setup = Sup; - NewSuiteEntry->UTS.Teardown = Tdn; - NewSuiteEntry->UTS.ParentFramework = Framework; - InitializeListHead( &(NewSuiteEntry->Entry) ); // List entry for sibling suites. - InitializeListHead( &(NewSuiteEntry->UTS.TestCaseList) ); // List entry for child tests. - if (NewSuiteEntry->UTS.Title == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - if (NewSuiteEntry->UTS.Package == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Create the suite fingerprint. - SetSuiteFingerprint( &NewSuiteEntry->UTS.Fingerprint[0], Framework, &NewSuiteEntry->UTS ); - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(Framework->TestSuiteList), (LIST_ENTRY*)NewSuiteEntry ); - *Suite = &NewSuiteEntry->UTS; - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestSuiteEntry( NewSuiteEntry ); - } - - return Status; -} - - -EFI_STATUS -EFIAPI -AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE SuiteHandle, - IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL - ) -{ - EFI_STATUS Status = EFI_SUCCESS; - UNIT_TEST_LIST_ENTRY *NewTestEntry; - UNIT_TEST_FRAMEWORK *ParentFramework; - UNIT_TEST_SUITE *Suite; - - Suite = (UNIT_TEST_SUITE*)SuiteHandle; - ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; - - // - // First, let's check to make sure that our parameters look good. - if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) - { - return EFI_INVALID_PARAMETER; - } - - // - // Create the new entry. - NewTestEntry = AllocateZeroPool( sizeof( UNIT_TEST_LIST_ENTRY ) ); - if (NewTestEntry == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // Copy the fields we think we need. - NewTestEntry->UT.Description = AllocateAndCopyString( Description ); - NewTestEntry->UT.ClassName = AllocateAndCopyString(ClassName); - NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; - NewTestEntry->UT.FailureMessage[0] = '\0'; - NewTestEntry->UT.Log = NULL; - NewTestEntry->UT.PreReq = PreReq; - NewTestEntry->UT.CleanUp = CleanUp; - NewTestEntry->UT.RunTest = Func; - NewTestEntry->UT.Context = Context; - NewTestEntry->UT.Result = UNIT_TEST_PENDING; - NewTestEntry->UT.ParentSuite = Suite; - InitializeListHead( &(NewTestEntry->Entry) ); // List entry for sibling tests. - if (NewTestEntry->UT.Description == NULL) - { - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Create the test fingerprint. - SetTestFingerprint( &NewTestEntry->UT.Fingerprint[0], Suite, &NewTestEntry->UT ); - - // TODO: Make sure that duplicate fingerprints cannot be created. - - // - // If there is saved test data, update this record. - if (ParentFramework->SavedState != NULL) - { - UpdateTestFromSave( &NewTestEntry->UT, ParentFramework->SavedState ); - } - -Exit: - // - // If everything is going well, add the new suite to the tail list for the framework. - if (!EFI_ERROR( Status )) - { - InsertTailList( &(Suite->TestCaseList), (LIST_ENTRY*)NewTestEntry ); - } - // Otherwise, make with the destruction. - else - { - FreeUnitTestTestEntry( NewTestEntry ); - } - - return Status; -} - - -//============================================================================= -// -// ---------------- TEST EXECUTION FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -EFI_STATUS -RunTestSuite ( - IN UNIT_TEST_SUITE *Suite - ) -{ - UNIT_TEST_LIST_ENTRY *TestEntry = NULL; - UNIT_TEST *Test; - UNIT_TEST_FRAMEWORK *ParentFramework = (UNIT_TEST_FRAMEWORK*)Suite->ParentFramework; - - if (Suite == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - DEBUG((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - - if (Suite->Setup != NULL) - { - Suite->Setup( Suite->ParentFramework ); - } - - // - // Iterate all tests within the suite - // - for (TestEntry = (UNIT_TEST_LIST_ENTRY*)GetFirstNode( &(Suite->TestCaseList) ); // Start at the beginning. - (LIST_ENTRY*)TestEntry != &(Suite->TestCaseList); // Go until you loop back to the head. - TestEntry = (UNIT_TEST_LIST_ENTRY*)GetNextNode( &(Suite->TestCaseList), (LIST_ENTRY*)TestEntry) ) // Always get the next test. - { - Test = &TestEntry->UT; - ParentFramework->CurrentTest = Test; - - DEBUG((DEBUG_VERBOSE, "*********************************************************\n")); - DEBUG((DEBUG_VERBOSE, " RUNNING TEST: %a:\n", Test->Description)); - DEBUG((DEBUG_VERBOSE, "**********************************************************\n")); - - // - // First, check to see whether the test has already been run. - // NOTE: This would generally only be the case if a saved state was detected and loaded. - if (Test->Result != UNIT_TEST_PENDING && Test->Result != UNIT_TEST_RUNNING) - { - DEBUG(( DEBUG_VERBOSE, "Test was run on a previous pass. Skipping.\n" )); - ParentFramework->CurrentTest = NULL; - continue; - } - - // - // Next, if we're still running, make sure that our test prerequisites are in place. - if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) - { - DEBUG(( DEBUG_VERBOSE, "PREREQ\n" )); - if (Test->PreReq( Suite->ParentFramework, Test->Context ) != UNIT_TEST_PASSED) - { - DEBUG(( DEBUG_ERROR, "PreReq Not Met\n" )); - Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; - ParentFramework->CurrentTest = NULL; - continue; - } - } - - // - // Now we should be ready to call the actual test. - // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot - // or quit. The UNIT_TEST_RUNNING state will allow the test to resume - // but will prevent the PreReq from being dispatched a second time. - Test->Result = UNIT_TEST_RUNNING; - Test->Result = Test->RunTest( Suite->ParentFramework, Test->Context ); - - // - // Finally, clean everything up, if need be. - if (Test->CleanUp != NULL) - { - DEBUG(( DEBUG_VERBOSE, "CLEANUP\n" )); - Test->CleanUp( Suite->ParentFramework, Test->Context ); - } - - // - // End the test. - ParentFramework->CurrentTest = NULL; - } // End Test iteration - - - if (Suite->Teardown != NULL) - { - Suite->Teardown( Suite->ParentFramework ); - } - - return EFI_SUCCESS; -} - -EFI_STATUS -EFIAPI -RunAllTestSuites ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - UNIT_TEST_FRAMEWORK *Framework; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - EFI_STATUS Status; - - Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); - DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - Status = RunTestSuite(&(Suite->UTS)); - if (EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); - } - } // End Suite iteration - - //Save current state so if test is started again it doesn't have to run. It will just report - SaveFrameworkState(Framework, NULL, 0); - OutputUnitTestFrameworkReport(Framework); - - return EFI_SUCCESS; -} - -//============================================================================= -// -// ---------------- TEST UTILITY FUNCTIONS ----------------------------------- -// -//============================================================================= - - -STATIC -VOID -UpdateTestFromSave ( - IN OUT UNIT_TEST *Test, - IN UNIT_TEST_SAVE_HEADER *SavedState - ) -{ - UNIT_TEST_SAVE_TEST *CurrentTest, *MatchingTest; - UINT8 *FloatingPointer; - UNIT_TEST_SAVE_CONTEXT *SavedContext; - UINTN Index; - - // - // First, evaluate the inputs. - if (Test == NULL || SavedState == NULL) - { - return; - } - if (SavedState->TestCount == 0) - { - return; - } - - // - // Next, determine whether a matching test can be found. - // Start at the beginning. - MatchingTest = NULL; - FloatingPointer = (UINT8*)SavedState + sizeof( *SavedState ); - for (Index = 0; Index < SavedState->TestCount; Index++) - { - CurrentTest = (UNIT_TEST_SAVE_TEST*)FloatingPointer; - if (CompareFingerprints( &Test->Fingerprint[0], &CurrentTest->Fingerprint[0] )) - { - MatchingTest = CurrentTest; - // If there's a saved context, it's important that we iterate through the entire list. - if (!SavedState->HasSavedContext) - { - break; - } - } - - // If we didn't find it, we have to increment to the next test. - FloatingPointer = (UINT8*)CurrentTest + CurrentTest->Size; - } - - // - // If a matching test was found, copy the status. - if (MatchingTest) - { - // Override the test status with the saved status. - Test->Result = MatchingTest->Result; - - Test->FailureType = MatchingTest->FailureType; - AsciiStrnCpyS(&Test->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &MatchingTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); - - // If there is a log string associated, grab that. - // We can tell that there's a log string because the "size" will be larger than - // the structure size. - // IMPORTANT NOTE: There are security implications here. - // This data is user-supplied and we're about to play kinda - // fast and loose with data buffers. - if (MatchingTest->Size > sizeof( UNIT_TEST_SAVE_TEST )) - { - UnitTestLogInit(Test, (UINT8*)MatchingTest->Log, MatchingTest->Size - sizeof( UNIT_TEST_SAVE_TEST ) ); - } - } - - // - // If the saved context exists and matches this test, grab it, too. - if (SavedState->HasSavedContext) - { - // If there was a saved context, the "matching test" loop will have placed the FloatingPointer - // at the beginning of the context structure. - SavedContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - if ((SavedContext->Size - sizeof(UNIT_TEST_SAVE_CONTEXT)) > 0 && - CompareFingerprints( &Test->Fingerprint[0], &SavedContext->Fingerprint[0] )) - { - // Override the test context with the saved context. - Test->Context = (VOID*)SavedContext->Data; - } - } - - return; -} // UpdateTestFromSave() - - -STATIC -UNIT_TEST_SAVE_HEADER* -SerializeState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - UNIT_TEST_FRAMEWORK *Framework = FrameworkHandle; - UNIT_TEST_SAVE_HEADER *Header = NULL; - LIST_ENTRY *SuiteListHead, *Suite, *TestListHead, *Test; - UINT32 TestCount, TotalSize; - UINTN LogSize; - UNIT_TEST_SAVE_TEST *TestSaveData; - UNIT_TEST_SAVE_CONTEXT *TestSaveContext; - UNIT_TEST *UnitTest; - UINT8 *FloatingPointer; - - // - // First, let's not make assumptions about the parameters. - if (Framework == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || - ContextToSaveSize > MAX_UINT32) - { - return NULL; - } - - // - // Next, we've gotta figure out the resources that will be required to serialize the - // the framework state so that we can persist it. - // To start with, we're gonna need a header. - TotalSize = sizeof( UNIT_TEST_SAVE_HEADER ); - // Now we need to figure out how many tests there are. - TestCount = 0; - // Iterate all suites. - SuiteListHead = &Framework->TestSuiteList; - for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) - { - // Iterate all tests within the suite. - TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; - for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) - { - UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; - // Account for the size of a test structure. - TotalSize += sizeof( UNIT_TEST_SAVE_TEST ); - // If there's a log, make sure to account for the log size. - if (UnitTest->Log != NULL) - { - // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); - ASSERT( LogSize < MAX_UINT32 ); - TotalSize += (UINT32)LogSize; - } - // Increment the test count. - TestCount++; - } - } - // If there are no tests, we're done here. - if (TestCount == 0) - { - return NULL; - } - // Add room for the context, if there is one. - if (ContextToSave != NULL) - { - TotalSize += sizeof( UNIT_TEST_SAVE_CONTEXT ) + (UINT32)ContextToSaveSize; - } - - // - // Now that we know the size, we need to allocate space for the serialized output. - Header = AllocateZeroPool( TotalSize ); - if (Header == NULL) - { - return NULL; - } - - // - // Alright, let's start setting up some data. - Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; - Header->SaveStateSize = TotalSize; - CopyMem( &Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - CopyMem( &Header->StartTime, &Framework->StartTime, sizeof( EFI_TIME ) ); - Header->TestCount = TestCount; - Header->HasSavedContext = FALSE; - - // - // Start adding all of the test cases. - // Set the floating pointer to the start of the current test save buffer. - FloatingPointer = (UINT8*)Header + sizeof( UNIT_TEST_SAVE_HEADER ); - // Iterate all suites. - SuiteListHead = &Framework->TestSuiteList; - for (Suite = GetFirstNode( SuiteListHead ); Suite != SuiteListHead; Suite = GetNextNode( SuiteListHead, Suite )) - { - // Iterate all tests within the suite. - TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY*)Suite)->UTS.TestCaseList; - for (Test = GetFirstNode( TestListHead ); Test != TestListHead; Test = GetNextNode( TestListHead, Test )) - { - TestSaveData = (UNIT_TEST_SAVE_TEST*)FloatingPointer; - UnitTest = &((UNIT_TEST_LIST_ENTRY*)Test)->UT; - - // Save the fingerprint. - CopyMem( &TestSaveData->Fingerprint[0], &UnitTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - - // Save the result. - TestSaveData->Result = UnitTest->Result; - TestSaveData->FailureType = UnitTest->FailureType; - AsciiStrnCpyS(&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); - - - // If there is a log, save the log. - FloatingPointer += sizeof( UNIT_TEST_SAVE_TEST ); - if (UnitTest->Log != NULL) - { - // The +1 is for the NULL character. Can't forget the NULL character. - LogSize = (AsciiStrLen( UnitTest->Log ) + 1) * sizeof( CHAR8 ); - CopyMem( FloatingPointer, UnitTest->Log, LogSize ); - FloatingPointer += LogSize; - } - - // Update the size once the structure is complete. - // NOTE: Should thise be a straight cast without validation? - // Maybe. - // Am I tired of writing code? - // Yes. - TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8*)TestSaveData); - } - } - - // - // If there is a context to save, let's do that now. - if (ContextToSave != NULL && Framework->CurrentTest != NULL) - { - TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; - TestSaveContext->Size = (UINT32)ContextToSaveSize + sizeof(UNIT_TEST_SAVE_CONTEXT); - CopyMem( &TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); - CopyMem( ((UINT8*)TestSaveContext + sizeof( UNIT_TEST_SAVE_CONTEXT )), ContextToSave, ContextToSaveSize ); - Header->HasSavedContext = TRUE; - } - - return Header; -} - - -EFI_STATUS -EFIAPI -SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, - IN UINTN ContextToSaveSize - ) -{ - EFI_STATUS Status; - UNIT_TEST_SAVE_HEADER *Header = NULL; - - // - // First, let's not make assumptions about the parameters. - if (FrameworkHandle == NULL || (ContextToSave != NULL && ContextToSaveSize == 0) || - ContextToSaveSize > MAX_UINT32) - { - return EFI_INVALID_PARAMETER; - } - - // - // Now, let's package up all the data for saving. - Header = SerializeState( FrameworkHandle, ContextToSave, ContextToSaveSize ); - if (Header == NULL) - { - return EFI_OUT_OF_RESOURCES; - } - - // - // All that should be left to do is save it using the associated persistence lib. - Status = SaveUnitTestCache( FrameworkHandle, Header ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status )); - Status = EFI_DEVICE_ERROR; - } - - // - // Free data that was used. - FreePool( Header ); - - return Status; -} // SaveFrameworkState() diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf deleted file mode 100644 index b9576db4359..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf +++ /dev/null @@ -1,43 +0,0 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibDxe -FILE_GUID = 98CEF9CA-15CE-40A3-ADE8-C299953CD0F6 -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestLib|DXE_DRIVER UEFI_APPLICATION - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UefiRuntimeServicesTableLib - UefiLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf deleted file mode 100644 index 910acb5229e..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf +++ /dev/null @@ -1,41 +0,0 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibPei -FILE_GUID = 7DDA6F03-CD2D-4B5D-BC67-E5EA5AE3014B -VERSION_STRING = 1.0 -MODULE_TYPE = PEIM -LIBRARY_CLASS = UnitTestLib|PEIM - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf deleted file mode 100644 index 32c554d5c5a..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf +++ /dev/null @@ -1,42 +0,0 @@ -## @file -# Library to support Unit Testing from UEFI shell -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLibSmm -FILE_GUID = 9A991713-AE25-4C41-9E3D-F72D6E0E7CEE -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_SMM_DRIVER -PI_SPECIFICATION_VERSION = 0x0001000A -LIBRARY_CLASS = UnitTestLib|DXE_SMM_DRIVER - - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - UnitTestLogLib - UnitTestPersistenceLib - UnitTestResultReportLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLib.c diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c deleted file mode 100644 index c8234eacd3c..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.c +++ /dev/null @@ -1,216 +0,0 @@ -/** - -Implement UnitTestLogLib - Unit test debugging log - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include -#include -#include - -#include -#include - -#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) -#define UNIT_TEST_MAX_LOG_BUFFER (16 * 1024) - - -struct _UNIT_TEST_LOG_PREFIX_STRING -{ - UNIT_TEST_STATUS LogLevel; - CHAR8 *String; -}; - -struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = -{ - { DEBUG_ERROR, "[ERROR] " }, - { DEBUG_WARN, "[WARNING] " }, - { DEBUG_INFO, "[INFO] " }, - { DEBUG_VERBOSE, "[VERBOSE] " } -}; -UINTN mLogPrefixStringsCount = sizeof( mLogPrefixStrings ) / sizeof( mLogPrefixStrings[0] ); - - - - -//============================================================================= -// -// ---------------- TEST HELPER FUNCTIONS ------------------------------------ -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForStatusLogPrefix ( - IN UINTN LogLevel - ) -{ - UINTN Index; - CHAR8 *Result = NULL; - - for (Index = 0; Index < mLogPrefixStringsCount; Index++) - { - if (mLogPrefixStrings[Index].LogLevel == LogLevel) - { - Result = mLogPrefixStrings[Index].String; - break; - } - } - - return Result; -} - - - -STATIC -EFI_STATUS -AddStringToUnitTestLog ( - IN OUT UNIT_TEST *UnitTest, - IN CONST CHAR8 *String - ) -{ - EFI_STATUS Status; - - // - // Make sure that you're cooking with gas. - // - if (UnitTest == NULL || String == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // If this is the first log for the test allocate log space - if (UnitTest->Log == NULL) - { - UnitTestLogInit(UnitTest, NULL, 0); - } - - if (UnitTest->Log == NULL) - { - DEBUG((DEBUG_ERROR, "Failed to allocate space for unit test log\n")); - ASSERT(UnitTest->Log != NULL); - return EFI_OUT_OF_RESOURCES; - } - - Status = AsciiStrnCatS(UnitTest->Log, UNIT_TEST_MAX_LOG_BUFFER / sizeof(CHAR8), String, UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH); - if(EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); - return Status; - } - - return EFI_SUCCESS; -} - - -//============================================================================= -// -// ---------------- PUBLIC FUNCTIONS ------------------------------------ -// -//============================================================================= - -/** - This function is responsible for initializing the log buffer for a single test. It can - be used internally, but may also be consumed by the test framework to add pre-existing - data to a log before it's used. - - @param[in,out] TestHandle A handle to the test being initialized. - @param[in] Buffer [Optional] A pointer to pre-existing log data that should - be used to initialize the log. Should include a NULL terminator. - @param[in] BufferSize [Optional] The size of the pre-existing log data. - -**/ -VOID -EFIAPI -UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer OPTIONAL, - IN UINTN BufferSize OPTIONAL - ) -{ - UNIT_TEST *Test; - - Test = (UNIT_TEST*)TestHandle; - - // - // Make sure that you're cooking with gas. - // - if (Test == NULL) - { - DEBUG((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); - return; - } - - // If this is the first log for the test allocate log space - if (Test->Log == NULL) - { - Test->Log = AllocateZeroPool(UNIT_TEST_MAX_LOG_BUFFER); - } - - //check again to make sure allocate worked - if(Test->Log == NULL) - { - DEBUG((DEBUG_ERROR, "Failed to allocate memory for the log\n")); - return; - } - - if((Buffer != NULL) && (BufferSize > 0) && ((BufferSize <= UNIT_TEST_MAX_LOG_BUFFER))) - { - CopyMem(Test->Log, Buffer, BufferSize); - } -} // UnitTestLogInit() - -VOID -EFIAPI -UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, - ... - ) -{ - CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CONST CHAR8 *LogTypePrefix = NULL; - VA_LIST Marker; - UINTN LogLevel = (UINTN) PcdGet32(UnitTestLogLevel); - // - // Make sure that this debug mode is enabled. - // - if ((ErrorLevel & LogLevel) == 0) { - return; - } - - // - // If we need to define a new format string... - // well... get to it. - // - LogTypePrefix = GetStringForStatusLogPrefix( ErrorLevel ); - if (LogTypePrefix != NULL) - { - AsciiSPrint( NewFormatString, sizeof( NewFormatString ), "%a%a", LogTypePrefix, Format ); - } - else - { - AsciiStrCpyS( NewFormatString, sizeof( NewFormatString ), Format ); - } - - // - // Convert the message to an ASCII String - // - VA_START (Marker, Format); - AsciiVSPrint( LogString, sizeof( LogString ), NewFormatString, Marker ); - VA_END (Marker); - - // - // Finally, add the string to the log. - // - AddStringToUnitTestLog( ((UNIT_TEST_FRAMEWORK*)Framework)->CurrentTest, LogString ); - - return; -} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf deleted file mode 100644 index 90f70ea5c7c..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf +++ /dev/null @@ -1,42 +0,0 @@ -## @file -# Library to support Logging in the Unit Tests -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestLogLib -FILE_GUID = D5F2DF71-6378-4E17-AE59-AE4109D34B5A -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestLogLib - -[LibraryClasses] - DebugLib - MemoryAllocationLib - BaseMemoryLib - BaseLib - PrintLib - PcdLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestLogLib.c - -[Pcd] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES - diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c deleted file mode 100644 index 0e487ebc2bc..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ /dev/null @@ -1,94 +0,0 @@ -/** @file -- UnitTestNullPersistenceLib.c -This is an instance of the Unit Test Persistence Lib that does nothing. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ - -#include - -#include -#include -#include - - -/** - Determines whether a persistence cache already exists for - the given framework. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - - @retval TRUE - @retval FALSE Cache doesn't exist or an error occurred. - -**/ -BOOLEAN -EFIAPI -DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - return FALSE; -} // DoesCacheExist() - - -/** - Will save the data associated with an internal Unit Test Framework - state in a manner that can persist a Unit Test Application quit or - even a system reboot. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer to the buffer containing the serialized - framework internal state. - - @retval EFI_SUCCESS Data is persisted and the test can be safely quit. - @retval Others Data is not persisted and test cannot be resumed upon exit. - -**/ -EFI_STATUS -EFIAPI -SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData - ) -{ - return EFI_UNSUPPORTED; -} // SaveUnitTestCache() - - -/** - Will retrieve any cached state associated with the given framework. - Will allocate a buffer to hold the loaded data. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address - of the loaded data buffer. - - @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated - with a pointer to the buffer. - @retval Others An error has occurred and no data has been loaded. SaveData - is set to NULL. - -**/ -EFI_STATUS -EFIAPI -LoadUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData - ) -{ - return EFI_UNSUPPORTED; -} // LoadUnitTestCache() diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c deleted file mode 100644 index 0b1cf98b299..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.c +++ /dev/null @@ -1,210 +0,0 @@ -/** - -Implement UnitTestResultReportLib doing plain txt out to console - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include - -#include -#include -#include - - - -struct _UNIT_TEST_STATUS_STRING -{ - UNIT_TEST_STATUS Status; - CHAR8 *String; -}; - -struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = -{ - { UNIT_TEST_PASSED, "PASSED" }, - { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, - { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, - { UNIT_TEST_RUNNING, "RUNNING" }, - { UNIT_TEST_PENDING, "PENDING" } -}; -UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); -CHAR8 *mUnknownStatus = "**UNKNOWN**"; - -struct _UNIT_TEST_FAILURE_TYPE_STRING -{ - FAILURE_TYPE Type; - CHAR8 *String; -}; - -struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= -{ - { FAILURETYPE_NOFAILURE, "NO FAILURE"}, - { FAILURETYPE_OTHER, "OTHER FAILURE" }, - { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, - { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, - { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, - { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } -}; -UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); -CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; - -//============================================================================= -// -// ---------------- TEST REPORTING FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForUnitTestStatus ( - IN UNIT_TEST_STATUS Status - ) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownStatus; - for (Index = 0; Index < mStatusStringsCount; Index++) - { - if (mStatusStrings[Index].Status == Status) - { - Result = mStatusStrings[Index].String; - break; - } - } - - return Result; -} - -STATIC -CONST CHAR8* -GetStringForFailureType( - IN FAILURE_TYPE Failure -) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownFailureType; - for (Index = 0; Index < mFailureTypeStringsCount; Index++) - { - if (mFailureTypeStrings[Index].Type == Failure) - { - Result = mFailureTypeStrings[Index].String; - break; - } - } - if (Result == mUnknownFailureType) - { - DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); - } - - return Result; -} - -/* -Method to print the Unit Test run results - -@retval Success -*/ -EFI_STATUS -EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - INTN Passed = 0; - INTN Failed = 0; - INTN NotRun = 0; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); - DEBUG((DEBUG_INFO, "------------- UNIT TEST FRAMEWORK RESULTS ---------------\n")); - DEBUG((DEBUG_INFO, "---------------------------------------------------------\n")); - - //print the version and time - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - UNIT_TEST_LIST_ENTRY *Test = NULL; - INTN SPassed = 0; - INTN SFailed = 0; - INTN SNotRun = 0; - - DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); - DEBUG((DEBUG_INFO, " SUITE: %a\n", Suite->UTS.Title)); - DEBUG((DEBUG_INFO, " PACKAGE: %a\n", Suite->UTS.Package)); - DEBUG((DEBUG_INFO, "/////////////////////////////////////////////////////////\n")); - - // - // Iterate all tests within the suite - // - for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); - (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); - Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) - { - - DEBUG((DEBUG_INFO, "*********************************************************\n")); - DEBUG((DEBUG_INFO, " CLASS NAME: %a\n", Test->UT.ClassName)); - DEBUG((DEBUG_INFO, " TEST: %a\n", Test->UT.Description)); - DEBUG((DEBUG_INFO, " STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ))); - DEBUG((DEBUG_INFO, " FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType))); - DEBUG((DEBUG_INFO, " FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage)); - - if (Test->UT.Log != NULL) - { - DEBUG((DEBUG_INFO, " LOG:\n")); - // NOTE: This has to be done directly because all of the other - // "formatted" print statements have caps on the string size. - DEBUG((DEBUG_INFO, "%a", Test->UT.Log)); - } - - switch (Test->UT.Result) - { - case UNIT_TEST_PASSED: SPassed++; break; - case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; - case UNIT_TEST_PENDING: // Fall through... - case UNIT_TEST_RUNNING: // Fall through... - case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; - default: break; - } - DEBUG((DEBUG_INFO, "**********************************************************\n")); - } //End Test iteration - - DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); - DEBUG((DEBUG_INFO, "Suite Stats\n")); - DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun))); - DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun))); - DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun))); - DEBUG((DEBUG_INFO, "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n")); - - Passed += SPassed; //add to global counters - Failed += SFailed; //add to global counters - NotRun += SNotRun; //add to global coutners - }//End Suite iteration - - DEBUG((DEBUG_INFO, "=========================================================\n")); - DEBUG((DEBUG_INFO, "Total Stats\n")); - DEBUG((DEBUG_INFO, " Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, " Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, " Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun))); - DEBUG((DEBUG_INFO, "=========================================================\n")); - - return EFI_SUCCESS; -} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf b/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf deleted file mode 100644 index a0215630e37..00000000000 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf +++ /dev/null @@ -1,34 +0,0 @@ -## @file -# Library to support printing out the unit test report using printlib and conout -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestResultReportLibDebug -FILE_GUID = BED736D4-D197-475F-B7CE-0D828FF2C9A6 -VERSION_STRING = 1.0 -MODULE_TYPE = BASE -LIBRARY_CLASS = UnitTestResultReportLib - -[LibraryClasses] - DebugLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestResultReportLibDebug.c diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c deleted file mode 100644 index 7a18df0919c..00000000000 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ /dev/null @@ -1,112 +0,0 @@ -/** - -Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should -work on all platforms - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include -#include -#include - -EFI_STATUS -EFIAPI -SetBootNextDevice( - VOID -) -{ - EFI_STATUS Status; - EFI_BOOT_MANAGER_LOAD_OPTION NewOption; - UINT32 Attributes; - UINT8 *OptionalData = NULL; - UINT32 OptionalDataSize = 0; - UINT16 BootNextValue = 0xABCD; // this should be a safe number... - USB_CLASS_DEVICE_PATH UsbDp; - EFI_DEVICE_PATH_PROTOCOL *DpEnd = NULL; - EFI_DEVICE_PATH_PROTOCOL *Dp = NULL; - BOOLEAN NewOptionValid = FALSE; - - UsbDp.Header.Length[0] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) & 0xff); - UsbDp.Header.Length[1] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) >> 8); - UsbDp.Header.Type = MESSAGING_DEVICE_PATH; - UsbDp.Header.SubType = MSG_USB_CLASS_DP; - UsbDp.VendorId = 0xFFFF; - UsbDp.ProductId = 0xFFFF; - UsbDp.DeviceClass = 0xFF; - UsbDp.DeviceSubClass = 0xFF; - UsbDp.DeviceProtocol = 0xFF; - - Attributes = LOAD_OPTION_ACTIVE; - - DpEnd = AppendDevicePathNode(NULL, NULL); - if (DpEnd == NULL) - { - DEBUG((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); - Status = EFI_OUT_OF_RESOURCES; - goto CLEANUP; - } - - Dp = AppendDevicePathNode(DpEnd, (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp); //@MRT --- Is this memory leak becasue we lose the old Dp memory - if (Dp == NULL) - { - DEBUG((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); - Status = EFI_OUT_OF_RESOURCES; - goto CLEANUP; - } - - Status = EfiBootManagerInitializeLoadOption( - &NewOption, - (UINTN) BootNextValue, - LoadOptionTypeBoot, - Attributes, - L"Generic USB Class Device", - Dp, - OptionalData, - OptionalDataSize - ); - - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); - goto CLEANUP; - } - - NewOptionValid = TRUE; - DEBUG((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); - Status = EfiBootManagerLoadOptionToVariable(&NewOption); - if (EFI_ERROR(Status)) { - DEBUG((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); - goto CLEANUP; - } - - //Set Boot Next - Status = gRT->SetVariable(L"BootNext", - &gEfiGlobalVariableGuid, - (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE), - sizeof(BootNextValue), - &(BootNextValue)); - - DEBUG((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); - -CLEANUP: - if (Dp != NULL) - { - FreePool(Dp); - } - - if (DpEnd != NULL) - { - FreePool(DpEnd); - } - - if (NewOptionValid) - { - EfiBootManagerFreeLoadOption(&NewOption); - } - - return Status; -} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c deleted file mode 100644 index 3c4aafb6eaa..00000000000 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.c +++ /dev/null @@ -1,416 +0,0 @@ -/** @file -- UnitTestPersistenceFilesystemLib.c - -This is an instance of the Unit Test Persistence Lib that will utilize -the filesystem that a test application is running from to save a serialized -version of the internal test state in case the test needs to quit and restore. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. - -**/ -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include - -/** - TODO: STUFF!! - - @retval !NULL A pointer to the EFI_FILE protocol instance for the filesystem. - @retval NULL Filesystem could not be found or an error occurred. - -**/ -STATIC -EFI_DEVICE_PATH_PROTOCOL* -GetCacheFileDevicePath ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; - EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; - CHAR16 *AppPath = NULL, *CacheFilePath = NULL; - CHAR16 *TestName = NULL; - CHAR16 *FileSuffix = L"_Cache.dat"; - UINTN DirectorySlashOffset, CacheFilePathLength; - EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath = NULL; - - // - // First, we need to get some information from the loaded image. - // Namely, where the hell are you? - // - Status = gBS->HandleProtocol( gImageHandle, - &gEfiLoadedImageProtocolGuid, - (VOID**)&LoadedImage ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status )); - return NULL; - } - - // Before we can start, we should change our test name from ASCII to Unicode. - CacheFilePathLength = AsciiStrLen( Framework->ShortTitle ) + 1; - TestName = AllocatePool( CacheFilePathLength ); - if (!TestName) { - goto Exit; - } - AsciiStrToUnicodeStrS( Framework->ShortTitle, TestName, CacheFilePathLength ); - - // - // Now we should have the device path of the root device and a file path for the rest. - // In order to target the directory for the test application, we must process - // the file path a little. - // - // NOTE: This may not be necessary... Path processing functions exist... - // PathCleanUpDirectories (FileNameCopy); - // if (PathRemoveLastItem (FileNameCopy)) { - AppPath = ConvertDevicePathToText( LoadedImage->FilePath, TRUE, TRUE ); // NOTE: This must be freed. - DirectorySlashOffset = StrLen( AppPath ); - // Make sure we didn't get any weird data. - if (DirectorySlashOffset == 0) - { - DEBUG(( DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__ )); - goto Exit; - } - // Now that we know we have a decent string, let's take a deeper look. - do - { - if (AppPath[DirectorySlashOffset] == L'\\') - { - break; - } - DirectorySlashOffset--; - } while (DirectorySlashOffset > 0); - - // - // After that little maneuver, DirectorySlashOffset should be pointing at the last '\' in AppString. - // That would be the path to the parent directory that the test app is executing from. - // Let's check and make sure that's right. - // - if (AppPath[DirectorySlashOffset] != L'\\') - { - DEBUG(( DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__ )); - goto Exit; - } - - // - // Now we know some things, we're ready to produce our output string, I think. - // - CacheFilePathLength = DirectorySlashOffset + 1; - CacheFilePathLength += StrLen( TestName ); - CacheFilePathLength += StrLen( FileSuffix ); - CacheFilePathLength += 1; // Don't forget the NULL terminator. - CacheFilePath = AllocateZeroPool( CacheFilePathLength * sizeof( CHAR16 ) ); - if (!CacheFilePath) { - goto Exit; - } - - // - // Let's produce our final path string, shall we? - // - StrnCpyS( CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1 ); // Copy the path for the parent directory. - StrCatS( CacheFilePath, CacheFilePathLength, TestName ); // Copy the base name for the test cache. - StrCatS( CacheFilePath, CacheFilePathLength, FileSuffix ); // Copy the file suffix. - - // - // Finally, try to create the device path for the thing thing. - // - CacheFileDevicePath = FileDevicePath( LoadedImage->DeviceHandle, CacheFilePath ); - -Exit: - // Always put away your toys. - if (AppPath != NULL) - { - FreePool( AppPath ); - } - if (CacheFilePath != NULL) - { - FreePool( CacheFilePath); - } - if (TestName != NULL) - { - FreePool( TestName); - } - - return CacheFileDevicePath; -} // GetCacheFileDevicePath() - - -/** - Determines whether a persistence cache already exists for - the given framework. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - - @retval TRUE - @retval FALSE Cache doesn't exist or an error occurred. - -**/ -BOOLEAN -EFIAPI -DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle - ) -{ - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - EFI_STATUS Status; - SHELL_FILE_HANDLE FileHandle; - - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // Check to see whether the file exists. - // If the file can be opened for reading, it exists. - // Otherwise, probably not. - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - EFI_FILE_MODE_READ, - 0 ); - if (!EFI_ERROR( Status )) - { - ShellCloseFile( &FileHandle ); - } - - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - - DEBUG(( DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR( Status ) )); - - return !EFI_ERROR( Status ); -} // DoesCacheExist() - - -/** - Will save the data associated with an internal Unit Test Framework - state in a manner that can persist a Unit Test Application quit or - even a system reboot. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer to the buffer containing the serialized - framework internal state. - - @retval EFI_SUCCESS Data is persisted and the test can be safely quit. - @retval Others Data is not persisted and test cannot be resumed upon exit. - -**/ -EFI_STATUS -EFIAPI -SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData - ) -{ - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - EFI_STATUS Status; - SHELL_FILE_HANDLE FileHandle; - UINTN WriteCount; - - // - // Check the inputs for sanity. - if (FrameworkHandle == NULL || SaveData == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Determine the path for the cache file. - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // - //First lets open the file if it exists so we can delete it...This is the work around for truncation - // - Status = ShellOpenFileByDevicePath(&FileDevicePath, - &FileHandle, - (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE), - 0); - - if (!EFI_ERROR(Status)) - { - //if file handle above was opened it will be closed by the delete. - Status = ShellDeleteFile(&FileHandle); - if (EFI_ERROR(Status)) - { - DEBUG((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); - } - } - - // - // Now that we know the path to the file... let's open it for writing. - // - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE), - 0 ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); - goto Exit; - } - - // - // Write the data to the file. - // - WriteCount = SaveData->SaveStateSize; - DEBUG(( DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount )); - Status = ShellWriteFile( FileHandle, - &WriteCount, - SaveData ); - - if (EFI_ERROR( Status ) || WriteCount != SaveData->SaveStateSize) - { - DEBUG(( DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status )); - } - else - { - DEBUG(( DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__ )); - } - - // - // No matter what, we should probably close the file. - // - ShellCloseFile( &FileHandle ); - -Exit: - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - - return Status; -} // SaveUnitTestCache() - - -/** - Will retrieve any cached state associated with the given framework. - Will allocate a buffer to hold the loaded data. - - @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @param[in] SaveData A pointer pointer that will be updated with the address - of the loaded data buffer. - - @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated - with a pointer to the buffer. - @retval Others An error has occurred and no data has been loaded. SaveData - is set to NULL. - -**/ -EFI_STATUS -EFIAPI -LoadUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - OUT UNIT_TEST_SAVE_HEADER **SaveData - ) -{ - EFI_STATUS Status; - EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; - SHELL_FILE_HANDLE FileHandle; - BOOLEAN IsFileOpened = FALSE; - UINT64 LargeFileSize; - UINTN FileSize; - UNIT_TEST_SAVE_HEADER *Buffer = NULL; - - // - // Check the inputs for sanity. - if (FrameworkHandle == NULL || SaveData == NULL) - { - return EFI_INVALID_PARAMETER; - } - - // - // Determine the path for the cache file. - // NOTE: This devpath is allocated and must be freed. - FileDevicePath = GetCacheFileDevicePath( FrameworkHandle ); - - // - // Now that we know the path to the file... let's open it for writing. - // - Status = ShellOpenFileByDevicePath( &FileDevicePath, - &FileHandle, - EFI_FILE_MODE_READ, - 0 ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status )); - goto Exit; - } - else - { - IsFileOpened = TRUE; - } - - // - // Now that the file is opened, we need to determine how large a buffer we need. - Status = ShellGetFileSize( FileHandle, &LargeFileSize ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status )); - goto Exit; - } - - // - // Now that we know the size, let's allocated a buffer to hold the contents. - FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. - Buffer = AllocatePool( FileSize ); - if (Buffer == NULL) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status )); - Status = EFI_OUT_OF_RESOURCES; - goto Exit; - } - - // - // Finally, let's read the bloody data. - Status = ShellReadFile( FileHandle, &FileSize, Buffer ); - if (EFI_ERROR( Status )) - { - DEBUG(( DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status )); - } - -Exit: - // - // Always put away your toys. - if (FileDevicePath != NULL) - { - FreePool( FileDevicePath ); - } - if (IsFileOpened) - { - ShellCloseFile( &FileHandle ); - } - - // - // If we're returning an error, make sure - // the state is sane. - if (EFI_ERROR( Status ) && Buffer != NULL) - { - FreePool( Buffer ); - Buffer = NULL; - } - - *SaveData = Buffer; - return Status; -} // LoadUnitTestCache() diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c deleted file mode 100644 index 15410c203bf..00000000000 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.c +++ /dev/null @@ -1,227 +0,0 @@ -/** - -Implement UnitTestResultReportLib doing plain txt out to console - -Copyright (c) Microsoft -**/ - -#include -#include -#include -#include -#include - -#include -#include -#include - - - -struct _UNIT_TEST_STATUS_STRING -{ - UNIT_TEST_STATUS Status; - CHAR8 *String; -}; - -struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = -{ - { UNIT_TEST_PASSED, "PASSED" }, - { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED" }, - { UNIT_TEST_ERROR_TEST_FAILED, "FAILED" }, - { UNIT_TEST_RUNNING, "RUNNING" }, - { UNIT_TEST_PENDING, "PENDING" } -}; -UINTN mStatusStringsCount = sizeof( mStatusStrings ) / sizeof( mStatusStrings[0] ); -CHAR8 *mUnknownStatus = "**UNKNOWN**"; - -struct _UNIT_TEST_FAILURE_TYPE_STRING -{ - FAILURE_TYPE Type; - CHAR8 *String; -}; - -struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[]= -{ - { FAILURETYPE_NOFAILURE, "NO FAILURE"}, - { FAILURETYPE_OTHER, "OTHER FAILURE" }, - { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE" }, - { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE" }, - { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, - { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, - { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE" } -}; -UINTN mFailureTypeStringsCount = sizeof(mFailureTypeStrings) / sizeof(mFailureTypeStrings[0]); -CHAR8 *mUnknownFailureType = "*UNKNOWN* Failure"; - -//============================================================================= -// -// ---------------- TEST REPORTING FUNCTIONS --------------------------------- -// -//============================================================================= - -STATIC -CONST CHAR8* -GetStringForUnitTestStatus ( - IN UNIT_TEST_STATUS Status - ) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownStatus; - for (Index = 0; Index < mStatusStringsCount; Index++) - { - if (mStatusStrings[Index].Status == Status) - { - Result = mStatusStrings[Index].String; - break; - } - } - - return Result; -} - -STATIC -CONST CHAR8* -GetStringForFailureType( - IN FAILURE_TYPE Failure -) -{ - UINTN Index; - CHAR8 *Result; - - Result = mUnknownFailureType; - for (Index = 0; Index < mFailureTypeStringsCount; Index++) - { - if (mFailureTypeStrings[Index].Type == Failure) - { - Result = mFailureTypeStrings[Index].String; - break; - } - } - if (Result == mUnknownFailureType) - { - DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); - } - - return Result; -} - -/* -Method to print the Unit Test run results - -@retval Success -*/ -EFI_STATUS -EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework - ) -{ - INTN Passed = 0; - INTN Failed = 0; - INTN NotRun = 0; - UNIT_TEST_SUITE_LIST_ENTRY *Suite = NULL; - UINT16 *LogString = NULL; - UINTN LogStringLength = 0; - - if (Framework == NULL) - { - return EFI_INVALID_PARAMETER; - } - - Print( L"---------------------------------------------------------\n" ); - Print( L"------------- UNIT TEST FRAMEWORK RESULTS ---------------\n" ); - Print( L"---------------------------------------------------------\n" ); - - //print the version and time - - // - // Iterate all suites - // - for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); - (LIST_ENTRY*)Suite != &Framework->TestSuiteList; - Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) - { - UNIT_TEST_LIST_ENTRY *Test = NULL; - INTN SPassed = 0; - INTN SFailed = 0; - INTN SNotRun = 0; - - Print( L"/////////////////////////////////////////////////////////\n" ); - Print( L" SUITE: %a\n", Suite->UTS.Title ); - Print( L" PACKAGE: %a\n", Suite->UTS.Package); - Print( L"/////////////////////////////////////////////////////////\n" ); - - // - // Iterate all tests within the suite - // - for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); - (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); - Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) - { - - Print (L"*********************************************************\n" ); - Print (L" CLASS NAME: %a\n", Test->UT.ClassName); - Print( L" TEST: %a\n", Test->UT.Description ); - Print( L" STATUS: %a\n", GetStringForUnitTestStatus( Test->UT.Result ) ); - Print( L" FAILURE: %a\n", GetStringForFailureType(Test->UT.FailureType)); - Print( L" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); - - if (Test->UT.Log != NULL) - { - // Make sure that we can expand the string into the unicode buffer. - if (LogStringLength <= AsciiStrnLenS( Test->UT.Log, MAX_UINT32 )) { - LogStringLength = AsciiStrnLenS( Test->UT.Log, MAX_UINT32 ) + 1; - if (LogString) { - FreePool( LogString ); - } - LogString = AllocatePool( LogStringLength * sizeof(CHAR16) ); - } - AsciiStrToUnicodeStrS( Test->UT.Log, LogString, LogStringLength ); - - Print( L" LOG:\n" ); - // NOTE: This has to be done directly because all of the other - // "formatted" print statements have caps on the string size. - gST->ConOut->OutputString( gST->ConOut, LogString ); - } - - switch (Test->UT.Result) - { - case UNIT_TEST_PASSED: SPassed++; break; - case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; break; - case UNIT_TEST_PENDING: // Fall through... - case UNIT_TEST_RUNNING: // Fall through... - case UNIT_TEST_ERROR_PREREQ_NOT_MET: SNotRun++; break; - default: break; - } - Print( L"**********************************************************\n" ); - } //End Test iteration - - Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); - Print( L"Suite Stats\n" ); - Print( L" Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun) ); - Print( L" Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun) ); - Print( L" Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun) ); - Print( L"+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); - - Passed += SPassed; //add to global counters - Failed += SFailed; //add to global counters - NotRun += SNotRun; //add to global coutners - }//End Suite iteration - - Print( L"=========================================================\n" ); - Print( L"Total Stats\n" ); - Print( L" Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun) ); - Print( L" Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun) ); - Print( L" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun) ); - Print( L"=========================================================\n" ); - - if (LogString) { - FreePool( LogString ); - } - - return EFI_SUCCESS; -} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf b/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf deleted file mode 100644 index 6620f85f296..00000000000 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf +++ /dev/null @@ -1,37 +0,0 @@ -## @file -# Library to support printing out the unit test report using printlib and conout -# -# -# @copyright -# Copyright (c) 2016 Microsoft Corporation. All rights reserved -# -# @par Specification Reference: -# -## - - -[Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestResultReportLibPlainTextOutput -FILE_GUID = C659641D-BA1F-4B58-946E-B1E1103903F9 -VERSION_STRING = 1.0 -MODULE_TYPE = DXE_DRIVER -LIBRARY_CLASS = UnitTestResultReportLib|DXE_DRIVER UEFI_APPLICATION - - -[LibraryClasses] - DebugLib - UefiLib - UefiBootServicesTableLib - - -[Packages] - MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - -[Guids] - - -[Sources] - UnitTestResultReportLibPlainTextOutput.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c new file mode 100644 index 00000000000..2e8be9418fc --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c @@ -0,0 +1,25 @@ +/** + NULL implementation for UnitTestBootLib to allow simple compliation + + Copyright (c) Microsoft +**/ + +#include + +/** + Set the boot manager to boot from a specific device on the next boot. This + should be set only for the next boot and shouldn't require any manual clean up + + @retval EFI_SUCCESS Boot device for next boot was set. + @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not + supportted. + @retval Other Boot devide for next boot can not be set. +**/ +EFI_STATUS +EFIAPI +SetBootNextDevice( + VOID + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf new file mode 100644 index 00000000000..2e1a16a0a9f --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf @@ -0,0 +1,22 @@ +## @file +# NULL library for UnitTestBootUsb +# +# Copyright (c) 2018 Microsoft Corporation. All rights reserved +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestBootLibNull + MODULE_UNI_FILE = UnitTestBootLibNull.uni + FILE_GUID = f143e75d-76e1-4040-b134-8f4f0bd5e3bd + VERSION_STRING = 1.0 + MODULE_TYPE = DXE_DRIVER + LIBRARY_CLASS = UnitTestBootLib + +[Sources] + UnitTestBootLibNull.c + +[Packages] + MdePkg/MdePkg.dec + diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.uni b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.uni new file mode 100644 index 00000000000..1ed3b205443 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.uni @@ -0,0 +1,11 @@ +// /** @file +// NULL library for UnitTestBootUsb +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "NULL library for UnitTestBootUsb" + +#string STR_MODULE_DESCRIPTION #language en-US "NULL library for UnitTestBootUsb." diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c new file mode 100644 index 00000000000..242daf53d43 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -0,0 +1,126 @@ +/** + Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should + work on all platforms + + Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include + +/** + Set the boot manager to boot from a specific device on the next boot. This + should be set only for the next boot and shouldn't require any manual clean up + + @retval EFI_SUCCESS Boot device for next boot was set. + @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not + supportted. + @retval Other Boot devide for next boot can not be set. +**/ +EFI_STATUS +EFIAPI +SetBootNextDevice ( + VOID + ) +{ + EFI_STATUS Status; + EFI_BOOT_MANAGER_LOAD_OPTION NewOption; + UINT32 Attributes; + UINT8 *OptionalData; + UINT32 OptionalDataSize; + UINT16 BootNextValue; + USB_CLASS_DEVICE_PATH UsbDp; + EFI_DEVICE_PATH_PROTOCOL *DpEnd; + EFI_DEVICE_PATH_PROTOCOL *Dp; + BOOLEAN NewOptionValid; + + OptionalData = NULL; + OptionalDataSize = 0; + BootNextValue = 0xABCD; // this should be a safe number... + DpEnd = NULL; + Dp = NULL; + NewOptionValid = FALSE; + + UsbDp.Header.Length[0] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) & 0xff); + UsbDp.Header.Length[1] = (UINT8)(sizeof(USB_CLASS_DEVICE_PATH) >> 8); + UsbDp.Header.Type = MESSAGING_DEVICE_PATH; + UsbDp.Header.SubType = MSG_USB_CLASS_DP; + UsbDp.VendorId = 0xFFFF; + UsbDp.ProductId = 0xFFFF; + UsbDp.DeviceClass = 0xFF; + UsbDp.DeviceSubClass = 0xFF; + UsbDp.DeviceProtocol = 0xFF; + + Attributes = LOAD_OPTION_ACTIVE; + + DpEnd = AppendDevicePathNode (NULL, NULL); + if (DpEnd == NULL) { + DEBUG ((DEBUG_ERROR, "%a: Unable to create device path. DpEnd is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + //@MRT --- Is this memory leak becasue we lose the old Dp memory + Dp = AppendDevicePathNode ( + DpEnd, + (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp + ); + if (Dp == NULL) { + DEBUG((DEBUG_ERROR, "%a: Unable to create device path. Dp is NULL.\n", __FUNCTION__)); + Status = EFI_OUT_OF_RESOURCES; + goto CLEANUP; + } + + Status = EfiBootManagerInitializeLoadOption ( + &NewOption, + (UINTN) BootNextValue, + LoadOptionTypeBoot, + Attributes, + L"Generic USB Class Device", + Dp, + OptionalData, + OptionalDataSize + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Error creating load option. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + NewOptionValid = TRUE; + DEBUG ((DEBUG_VERBOSE, "%a: Generic USB Class Device boot option created.\n", __FUNCTION__)); + Status = EfiBootManagerLoadOptionToVariable (&NewOption); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a: Error Saving boot option NV variable. Status = %r\n", __FUNCTION__, Status)); + goto CLEANUP; + } + + // + // Set Boot Next + // + Status = gRT->SetVariable ( + L"BootNext", + &gEfiGlobalVariableGuid, + (EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_NON_VOLATILE), + sizeof(BootNextValue), + &(BootNextValue) + ); + + DEBUG((DEBUG_VERBOSE, "%a - Set BootNext Status (%r)\n", __FUNCTION__, Status)); + +CLEANUP: + if (Dp != NULL) { + FreePool (Dp); + } + if (DpEnd != NULL) { + FreePool (DpEnd); + } + if (NewOptionValid) { + EfiBootManagerFreeLoadOption (&NewOption); + } + return Status; +} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf similarity index 64% rename from UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf rename to UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index 5fb2b8f7829..2e9f1c0c767 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -2,23 +2,26 @@ # Library to support booting to USB on the next boot # This instance uses the industry standard usb class boot option. # -# -# @copyright # Copyright (c) 2016 Microsoft Corporation. All rights reserved # -# @par Specification Reference: -# ## - [Defines] -INF_VERSION = 0x00010017 -BASE_NAME = UnitTestBootLibUsbClass -FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 -VERSION_STRING = 1.0 -MODULE_TYPE = UEFI_APPLICATION -LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestBootLibUsbClass + MODULE_UNI_FILE = UnitTestBootLibUsbClass.uni + FILE_GUID = DFADE2A2-DB69-47DE-A37A-40FB6D52E844 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_APPLICATION + LIBRARY_CLASS = UnitTestBootLib +[Sources] + UnitTestBootLibUsbClass.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] DebugLib @@ -27,16 +30,5 @@ LIBRARY_CLASS = UnitTestBootLib|UEFI_APPLICATION DevicePathLib UefiBootManagerLib - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - - [Guids] gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. - - -[Sources] - UnitTestBootLibUsbClass.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.uni b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.uni new file mode 100644 index 00000000000..8468b3537c2 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.uni @@ -0,0 +1,12 @@ +// /** @file +// Library to support booting to USB on the next boot +// This instance uses the industry standard usb class boot option. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Library to support booting to USB on the next boot" + +#string STR_MODULE_DESCRIPTION #language en-US "This instance uses the industry standard usb class boot option.." diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c new file mode 100644 index 00000000000..bdd3064ddc2 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -0,0 +1,215 @@ +/** + Implement UnitTestLib assert services + + Copyright (c) Microsoft +**/ + +#include +#include +#include +#include +#include +#include +#include + +STATIC +EFI_STATUS +AddUnitTestFailure ( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR8 *FailureMessage, + IN FAILURE_TYPE FailureType + ) +{ + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || FailureMessage == NULL) + { + return EFI_INVALID_PARAMETER; + } + + UnitTest->FailureType = FailureType; + AsciiStrCpyS (&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + + return EFI_SUCCESS; +} + +STATIC +VOID +UnitTestLogFailure ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + VA_LIST Marker; + + // + // Convert the message to an ASCII String + // + VA_START (Marker, Format); + AsciiVSPrint (LogString, sizeof (LogString), Format, Marker); + VA_END (Marker); + + // + // Finally, add the string to the log. + // + AddUnitTestFailure (((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, LogString, FailureType); + + return; +} + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (!Expression) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); + UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); + } + return Expression; +} + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (Expression) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + } + return !Expression; +} + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if (EFI_ERROR (Status)) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); + UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); + } + return !EFI_ERROR( Status ); +} + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA != ValueB)) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + return FALSE; + } + return TRUE; +} + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + if ((ValueA == ValueB)) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); + UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); + } + return (ValueA != ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + if ((Status != Expected)) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); + UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); + } + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + if (Pointer == NULL) { + UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + } + return (Pointer != NULL); +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c new file mode 100644 index 00000000000..3fb2050e18d --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -0,0 +1,183 @@ +/** @file + Implement UnitTestLib assert services using cmocka services + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include + +#define MAX_STRING_SIZE 1025 + +BOOLEAN +EFIAPI +UnitTestAssertTrue ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); + _assert_true (Expression, Description, FileName, (INT32)LineNumber); + + return Expression; +} + +BOOLEAN +EFIAPI +UnitTestAssertFalse ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); + _assert_true (!Expression, Description, FileName, (INT32)LineNumber); + + return !Expression; +} + +BOOLEAN +EFIAPI +UnitTestAssertNotEfiError ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); + _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); + + return !EFI_ERROR (Status); +} + +BOOLEAN +EFIAPI +UnitTestAssertEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA == ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertMemEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + BOOLEAN Result; + + Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); + _assert_true (Result, TempStr, FileName, (INT32)LineNumber); + + return Result; +} + +BOOLEAN +EFIAPI +UnitTestAssertNotEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); + _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + + return (ValueA != ValueB); +} + +BOOLEAN +EFIAPI +UnitTestAssertStatusEqual ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); + _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); + + return (Status == Expected); +} + +BOOLEAN +EFIAPI +UnitTestAssertNotNull ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName + ) +{ + CHAR8 TempStr[MAX_STRING_SIZE]; + + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); + _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); + + return (Pointer != NULL); +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c new file mode 100644 index 00000000000..a98be88bf44 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -0,0 +1,195 @@ +/** + Implemnet UnitTestLib log services + + Copyright (c) Microsoft + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH (512) +#define UNIT_TEST_MAX_LOG_BUFFER SIZE_16KB + +struct _UNIT_TEST_LOG_PREFIX_STRING { + UNIT_TEST_STATUS LogLevel; + CHAR8 *String; +}; + +struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = { + { DEBUG_ERROR, "[ERROR] " }, + { DEBUG_WARN, "[WARNING] " }, + { DEBUG_INFO, "[INFO] " }, + { DEBUG_VERBOSE, "[VERBOSE] " } +}; + +// +// Unit-Test Log helper functions +// + +STATIC +CONST CHAR8* +GetStringForStatusLogPrefix ( + IN UINTN LogLevel + ) +{ + UINTN Index; + CHAR8 *Result; + + Result = NULL; + for (Index = 0; Index < ARRAY_SIZE (mLogPrefixStrings); Index++) { + if (mLogPrefixStrings[Index].LogLevel == LogLevel) { + Result = mLogPrefixStrings[Index].String; + break; + } + } + return Result; +} + +STATIC +EFI_STATUS +AddStringToUnitTestLog ( + IN OUT UNIT_TEST *UnitTest, + IN CONST CHAR8 *String + ) +{ + EFI_STATUS Status; + + // + // Make sure that you're cooking with gas. + // + if (UnitTest == NULL || String == NULL) { + return EFI_INVALID_PARAMETER; + } + + // If this is the first log for the test allocate log space + if (UnitTest->Log == NULL) { + UnitTestLogInit (UnitTest, NULL, 0); + } + + if (UnitTest->Log == NULL) { + DEBUG ((DEBUG_ERROR, "Failed to allocate space for unit test log\n")); + ASSERT (UnitTest->Log != NULL); + return EFI_OUT_OF_RESOURCES; + } + + Status = AsciiStrnCatS ( + UnitTest->Log, + UNIT_TEST_MAX_LOG_BUFFER / sizeof (CHAR8), + String, + UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH + ); + if(EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed to add unit test log string. Status = %r\n", Status)); + return Status; + } + + return EFI_SUCCESS; +} + +/** + This function is responsible for initializing the log buffer for a single test. It can + be used internally, but may also be consumed by the test framework to add pre-existing + data to a log before it's used. + + @param[in,out] TestHandle A handle to the test being initialized. + @param[in] Buffer [Optional] A pointer to pre-existing log data that should + be used to initialize the log. Should include a NULL terminator. + @param[in] BufferSize [Optional] The size of the pre-existing log data. + +**/ +VOID +EFIAPI +UnitTestLogInit ( + IN OUT UNIT_TEST_HANDLE TestHandle, + IN UINT8 *Buffer, OPTIONAL + IN UINTN BufferSize OPTIONAL + ) +{ + UNIT_TEST *Test; + + Test = (UNIT_TEST *)TestHandle; + + // + // Make sure that you're cooking with gas. + // + if (Test == NULL) { + DEBUG ((DEBUG_ERROR, "%a called with invalid Test parameter\n", __FUNCTION__)); + return; + } + + // + // If this is the first log for the test allocate log space + // + if (Test->Log == NULL) { + Test->Log = AllocateZeroPool (UNIT_TEST_MAX_LOG_BUFFER); + } + + // + //check again to make sure allocate worked + // + if(Test->Log == NULL) { + DEBUG ((DEBUG_ERROR, "Failed to allocate memory for the log\n")); + return; + } + + if((Buffer != NULL) && (BufferSize > 0) && ((BufferSize <= UNIT_TEST_MAX_LOG_BUFFER))) { + CopyMem (Test->Log, Buffer, BufferSize); + } +} + +VOID +EFIAPI +UnitTestLog ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, + ... + ) +{ + CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CONST CHAR8 *LogTypePrefix; + VA_LIST Marker; + UINTN LogLevel; + + LogTypePrefix = NULL; + LogLevel = (UINTN)PcdGet32 (UnitTestLogLevel); + + // + // Make sure that this debug mode is enabled. + // + if ((ErrorLevel & LogLevel) == 0) { + return; + } + + // + // If we need to define a new format string... + // well... get to it. + // + LogTypePrefix = GetStringForStatusLogPrefix (ErrorLevel); + if (LogTypePrefix != NULL) { + AsciiSPrint (NewFormatString, sizeof (NewFormatString), "%a%a", LogTypePrefix, Format); + } else { + AsciiStrCpyS (NewFormatString, sizeof (NewFormatString), Format); + } + + // + // Convert the message to an ASCII String + // + VA_START (Marker, Format); + AsciiVSPrint (LogString, sizeof (LogString), NewFormatString, Marker); + VA_END (Marker); + + // + // Finally, add the string to the log. + // + AddStringToUnitTestLog (((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, LogString); +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c new file mode 100644 index 00000000000..aaba00a5e2f --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -0,0 +1,144 @@ +/** + UnitTestLib APIs to run unit tests + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +STATIC +EFI_STATUS +RunTestSuite ( + IN UNIT_TEST_SUITE *Suite + ) +{ + UNIT_TEST_LIST_ENTRY *TestEntry; + UNIT_TEST *Test; + UNIT_TEST_FRAMEWORK *ParentFramework; + + TestEntry = NULL; + ParentFramework = (UNIT_TEST_FRAMEWORK *)Suite->ParentFramework; + + if (Suite == NULL) { + return EFI_INVALID_PARAMETER; + } + + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG ((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + if (Suite->Setup != NULL) { + Suite->Setup (Suite->ParentFramework); + } + + // + // Iterate all tests within the suite + // + for (TestEntry = (UNIT_TEST_LIST_ENTRY *)GetFirstNode (&(Suite->TestCaseList)); + (LIST_ENTRY*)TestEntry != &(Suite->TestCaseList); + TestEntry = (UNIT_TEST_LIST_ENTRY *)GetNextNode (&(Suite->TestCaseList), (LIST_ENTRY *)TestEntry)) { + Test = &TestEntry->UT; + ParentFramework->CurrentTest = Test; + + DEBUG ((DEBUG_VERBOSE, "*********************************************************\n")); + DEBUG ((DEBUG_VERBOSE, " RUNNING TEST: %a:\n", Test->Description)); + DEBUG ((DEBUG_VERBOSE, "**********************************************************\n")); + + // + // First, check to see whether the test has already been run. + // NOTE: This would generally only be the case if a saved state was detected and loaded. + // + if (Test->Result != UNIT_TEST_PENDING && Test->Result != UNIT_TEST_RUNNING) { + DEBUG ((DEBUG_VERBOSE, "Test was run on a previous pass. Skipping.\n")); + ParentFramework->CurrentTest = NULL; + continue; + } + + // + // Next, if we're still running, make sure that our test prerequisites are in place. + if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) { + DEBUG ((DEBUG_VERBOSE, "PREREQ\n")); + if (Test->PreReq (Suite->ParentFramework, Test->Context) != UNIT_TEST_PASSED) { + DEBUG ((DEBUG_ERROR, "PreReq Not Met\n")); + Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; + ParentFramework->CurrentTest = NULL; + continue; + } + } + + // + // Now we should be ready to call the actual test. + // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot + // or quit. The UNIT_TEST_RUNNING state will allow the test to resume + // but will prevent the PreReq from being dispatched a second time. + Test->Result = UNIT_TEST_RUNNING; + Test->Result = Test->RunTest (Suite->ParentFramework, Test->Context); + + // + // Finally, clean everything up, if need be. + if (Test->CleanUp != NULL) { + DEBUG (( DEBUG_VERBOSE, "CLEANUP\n")); + Test->CleanUp (Suite->ParentFramework, Test->Context); + } + + // + // End the test. + // + ParentFramework->CurrentTest = NULL; + } + + if (Suite->Teardown != NULL) { + Suite->Teardown( Suite->ParentFramework ); + } + + return EFI_SUCCESS; +} + +EFI_STATUS +EFIAPI +RunAllTestSuites ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_SUITE_LIST_ENTRY *Suite; + EFI_STATUS Status; + + Framework = (UNIT_TEST_FRAMEWORK *)FrameworkHandle; + Suite = NULL; + + if (Framework == NULL) { + return EFI_INVALID_PARAMETER; + } + + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG ((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY *)GetFirstNode (&Framework->TestSuiteList); + (LIST_ENTRY *)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY *)GetNextNode (&Framework->TestSuiteList, (LIST_ENTRY *)Suite)) { + Status = RunTestSuite (&(Suite->UTS)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); + } + } + + // + // Save current state so if test is started again it doesn't have to run. It will just report + // + SaveFrameworkState (FrameworkHandle, NULL, 0); + OutputUnitTestFrameworkReport (FrameworkHandle); + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c new file mode 100644 index 00000000000..911dda49d4c --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -0,0 +1,121 @@ +/** @file + UnitTestLib APIs to run unit tests using cmocka + + Copyright (c) 2019, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include +#include + +STATIC +EFI_STATUS +RunTestSuite ( + IN UNIT_TEST_SUITE *Suite + ) +{ + UNIT_TEST_LIST_ENTRY *TestEntry; + UNIT_TEST *UnitTest; + struct CMUnitTest *Tests; + UINTN Index; + + TestEntry = NULL; + + if (Suite == NULL) { + return EFI_INVALID_PARAMETER; + } + + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG ((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); + DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + if (Suite->Setup != NULL) { + Suite->Setup (Suite->ParentFramework); + } + + // + // Alocate buffer of CMUnitTest entries + // + Tests = AllocateZeroPool (Suite->NumTests * sizeof (struct CMUnitTest)); + ASSERT (Tests != NULL); + + // + // Populate buffer of CMUnitTest entries + // + Index = 0; + for (TestEntry = (UNIT_TEST_LIST_ENTRY *)GetFirstNode (&(Suite->TestCaseList)); + (LIST_ENTRY *)TestEntry != &(Suite->TestCaseList); + TestEntry = (UNIT_TEST_LIST_ENTRY *)GetNextNode (&(Suite->TestCaseList), (LIST_ENTRY *)TestEntry)) { + UnitTest = &TestEntry->UT; + Tests[Index].name = UnitTest->Description; + Tests[Index].test_func = (CMUnitTestFunction)(UnitTest->RunTest); + Tests[Index].setup_func = (CMFixtureFunction)(UnitTest->PreReq); + Tests[Index].teardown_func = (CMFixtureFunction)(UnitTest->CleanUp); + Tests[Index].initial_state = NULL; + Index++; + } + ASSERT (Index == Suite->NumTests); + + // + // Run all unit tests in a test suite + // + _cmocka_run_group_tests ( + Suite->Title, + Tests, + Suite->NumTests, + (CMFixtureFunction)(Suite->Setup), + (CMFixtureFunction)(Suite->Teardown) + ); + FreePool (Tests); + + return EFI_SUCCESS; +} + +EFI_STATUS +EFIAPI +RunAllTestSuites ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_SUITE_LIST_ENTRY *Suite; + EFI_STATUS Status; + + Framework = (UNIT_TEST_FRAMEWORK *)FrameworkHandle; + Suite = NULL; + + if (Framework == NULL) { + return EFI_INVALID_PARAMETER; + } + + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); + DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY *)GetFirstNode (&Framework->TestSuiteList); + (LIST_ENTRY *)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY *)GetNextNode (&Framework->TestSuiteList, (LIST_ENTRY *)Suite)) { + Status = RunTestSuite (&(Suite->UTS)); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Test Suite Failed with Error. %r\n", Status)); + } + } + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c new file mode 100644 index 00000000000..8c507155dbb --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -0,0 +1,736 @@ +/** + Implement UnitTestLib + + Copyright (c) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include + +// +// Forward declaration of prototype +// +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ); + +/** + This function will determine whether the short name violates any rules that would + prevent it from being used as a reporting name or as a serialization name. + + Example: If the name cannot be serialized to a filesystem file name. + + @param[in] ShortTitleString A pointer to the short title string to be evaluated. + + @retval TRUE The string is acceptable. + @retval FALSE The string should not be used. + +**/ +STATIC +BOOLEAN +IsFrameworkShortNameValid ( + IN CHAR8 *ShortTitleString + ) +{ + // TODO: Finish this function. + return TRUE; +} + +STATIC +CHAR8* +AllocateAndCopyString ( + IN CHAR8 *StringToCopy + ) +{ + CHAR8 *NewString; + UINTN NewStringLength; + + NewString = NULL; + NewStringLength = AsciiStrnLenS (StringToCopy, UNIT_TEST_MAX_STRING_LENGTH) + 1; + NewString = AllocatePool (NewStringLength * sizeof( CHAR8 )); + if (NewString != NULL) { + AsciiStrCpyS (NewString, NewStringLength, StringToCopy); + } + return NewString; +} + +STATIC +VOID +SetFrameworkFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework + ) +{ + UINT32 NewFingerprint; + + // For this one we'll just use the title and version as the unique fingerprint. + NewFingerprint = CalculateCrc32( Framework->Title, (AsciiStrLen( Framework->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Framework->VersionString, (AsciiStrLen( Framework->VersionString ) * sizeof( CHAR8 )) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} + +STATIC +VOID +SetSuiteFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_FRAMEWORK *Framework, + IN UNIT_TEST_SUITE *Suite + ) +{ + UINT32 NewFingerprint; + + // For this one, we'll use the fingerprint from the framework, and the title of the suite. + NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} + +STATIC +VOID +SetTestFingerprint ( + OUT UINT8 *Fingerprint, + IN UNIT_TEST_SUITE *Suite, + IN UNIT_TEST *Test + ) +{ + UINT32 NewFingerprint; + + // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. + NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); + + CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); + return; +} + +STATIC +BOOLEAN +CompareFingerprints ( + IN UINT8 *FingerprintA, + IN UINT8 *FingerprintB + ) +{ + return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); +} + +EFI_STATUS +EFIAPI +FreeUnitTestFramework ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} + +STATIC +EFI_STATUS +FreeUnitTestSuiteEntry ( + IN UNIT_TEST_SUITE_LIST_ENTRY *SuiteEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} + +STATIC +EFI_STATUS +FreeUnitTestTestEntry ( + IN UNIT_TEST_LIST_ENTRY *TestEntry + ) +{ + // TODO: Finish this function. + return EFI_SUCCESS; +} + +/* + Method to Initialize the Unit Test framework + + @retval Success - Unit Test init. + @retval EFI_ERROR - Unit Tests init failed. +*/ +EFI_STATUS +EFIAPI +InitUnitTestFramework ( + OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + IN CHAR8 *Title, + IN CHAR8 *ShortTitle, + IN CHAR8 *VersionString + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *NewFramework; + UNIT_TEST_SAVE_HEADER *SavedState; + + Status = EFI_SUCCESS; + NewFramework = NULL; + + // + // First, check all pointers and make sure nothing's broked. + // + if (Framework == NULL || Title == NULL || + ShortTitle == NULL || VersionString == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Next, determine whether all of the strings are good to use. + // + if (!IsFrameworkShortNameValid (ShortTitle)) { + return EFI_INVALID_PARAMETER; + } + + // + // Next, set aside some space to start messing with the framework. + // + NewFramework = AllocateZeroPool (sizeof (UNIT_TEST_FRAMEWORK)); + if (NewFramework == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Next, set up all the test data. + // + NewFramework->Title = AllocateAndCopyString (Title); + NewFramework->ShortTitle = AllocateAndCopyString (ShortTitle); + NewFramework->VersionString = AllocateAndCopyString (VersionString); + NewFramework->Log = NULL; + NewFramework->CurrentTest = NULL; + NewFramework->SavedState = NULL; + if (NewFramework->Title == NULL || + NewFramework->ShortTitle == NULL || + NewFramework->VersionString == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + InitializeListHead (&(NewFramework->TestSuiteList)); + + // + // Create the framework fingerprint. + // + SetFrameworkFingerprint (&NewFramework->Fingerprint[0], NewFramework); + + // + // If there is a persisted context, load it now. + // + if (DoesCacheExist (NewFramework)) { + SavedState = (UNIT_TEST_SAVE_HEADER *)NewFramework->SavedState; + Status = LoadUnitTestCache (NewFramework, &SavedState); + if (EFI_ERROR (Status)) { + // + // Don't actually report it as an error, but emit a warning. + // + DEBUG (( DEBUG_ERROR, "%a - Cache was detected, but failed to load.\n", __FUNCTION__ )); + Status = EFI_SUCCESS; + } + } + +Exit: + // + // If we're good, then let's copy the framework. + // + if (!EFI_ERROR (Status)) { + *Framework = NewFramework; + } else { + // + // Otherwise, we need to undo this horrible thing that we've done. + // + FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); + } + + return Status; +} + +EFI_STATUS +EFIAPI +CreateUnitTestSuite ( + OUT UNIT_TEST_SUITE_HANDLE *Suite, + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN CHAR8 *Title, + IN CHAR8 *Package, + IN UNIT_TEST_SUITE_SETUP Sup, OPTIONAL + IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + ) +{ + EFI_STATUS Status; + UNIT_TEST_SUITE_LIST_ENTRY *NewSuiteEntry; + UNIT_TEST_FRAMEWORK *Framework; + + Status = EFI_SUCCESS; + Framework = (UNIT_TEST_FRAMEWORK *)FrameworkHandle; + + // + // First, let's check to make sure that our parameters look good. + // + if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + // + NewSuiteEntry = AllocateZeroPool (sizeof (UNIT_TEST_SUITE_LIST_ENTRY)); + if (NewSuiteEntry == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + // + NewSuiteEntry->UTS.NumTests = 0; + NewSuiteEntry->UTS.Title = AllocateAndCopyString (Title); + NewSuiteEntry->UTS.Package = AllocateAndCopyString (Package); + NewSuiteEntry->UTS.Setup = Sup; + NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.ParentFramework = Framework; + InitializeListHead (&(NewSuiteEntry->Entry)); // List entry for sibling suites. + InitializeListHead (&(NewSuiteEntry->UTS.TestCaseList)); // List entry for child tests. + if (NewSuiteEntry->UTS.Title == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + if (NewSuiteEntry->UTS.Package == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the suite fingerprint. + // + SetSuiteFingerprint( &NewSuiteEntry->UTS.Fingerprint[0], Framework, &NewSuiteEntry->UTS ); + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + // + if (!EFI_ERROR( Status )) { + InsertTailList (&(Framework->TestSuiteList), (LIST_ENTRY *)NewSuiteEntry); + *Suite = &NewSuiteEntry->UTS; + } else { + // + // Otherwise, make with the destruction. + // + FreeUnitTestSuiteEntry (NewSuiteEntry); + } + + return Status; +} + +EFI_STATUS +EFIAPI +AddTestCase ( + IN UNIT_TEST_SUITE_HANDLE SuiteHandle, + IN CHAR8 *Description, + IN CHAR8 *ClassName, + IN UNIT_TEST_FUNCTION Func, + IN UNIT_TEST_PREREQ PreReq, OPTIONAL + IN UNIT_TEST_CLEANUP CleanUp, OPTIONAL + IN UNIT_TEST_CONTEXT Context OPTIONAL + ) +{ + EFI_STATUS Status; + UNIT_TEST_LIST_ENTRY *NewTestEntry; + UNIT_TEST_FRAMEWORK *ParentFramework; + UNIT_TEST_SUITE *Suite; + + Status = EFI_SUCCESS; + Suite = (UNIT_TEST_SUITE *)SuiteHandle; + ParentFramework = (UNIT_TEST_FRAMEWORK *)Suite->ParentFramework; + + // + // First, let's check to make sure that our parameters look good. + // + if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) { + return EFI_INVALID_PARAMETER; + } + + // + // Create the new entry. + NewTestEntry = AllocateZeroPool (sizeof( UNIT_TEST_LIST_ENTRY )); + if (NewTestEntry == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Copy the fields we think we need. + NewTestEntry->UT.Description = AllocateAndCopyString (Description); + NewTestEntry->UT.ClassName = AllocateAndCopyString (ClassName); + NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; + NewTestEntry->UT.FailureMessage[0] = '\0'; + NewTestEntry->UT.Log = NULL; + NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.CleanUp = CleanUp; + NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.Context = Context; + NewTestEntry->UT.Result = UNIT_TEST_PENDING; + NewTestEntry->UT.ParentSuite = Suite; + InitializeListHead (&(NewTestEntry->Entry)); // List entry for sibling tests. + if (NewTestEntry->UT.Description == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Create the test fingerprint. + // + SetTestFingerprint (&NewTestEntry->UT.Fingerprint[0], Suite, &NewTestEntry->UT); + + // TODO: Make sure that duplicate fingerprints cannot be created. + + // + // If there is saved test data, update this record. + // + if (ParentFramework->SavedState != NULL) { + UpdateTestFromSave (&NewTestEntry->UT, ParentFramework->SavedState); + } + +Exit: + // + // If everything is going well, add the new suite to the tail list for the framework. + // + if (!EFI_ERROR (Status)) { + InsertTailList (&(Suite->TestCaseList), (LIST_ENTRY*)NewTestEntry); + Suite->NumTests++; + } else { + // + // Otherwise, make with the destruction. + // + FreeUnitTestTestEntry (NewTestEntry); + } + + return Status; +} + +STATIC +VOID +UpdateTestFromSave ( + IN OUT UNIT_TEST *Test, + IN UNIT_TEST_SAVE_HEADER *SavedState + ) +{ + UNIT_TEST_SAVE_TEST *CurrentTest; + UNIT_TEST_SAVE_TEST *MatchingTest; + UINT8 *FloatingPointer; + UNIT_TEST_SAVE_CONTEXT *SavedContext; + UINTN Index; + + // + // First, evaluate the inputs. + // + if (Test == NULL || SavedState == NULL) { + return; + } + if (SavedState->TestCount == 0) { + return; + } + + // + // Next, determine whether a matching test can be found. + // Start at the beginning. + // + MatchingTest = NULL; + FloatingPointer = (UINT8 *)SavedState + sizeof (*SavedState); + for (Index = 0; Index < SavedState->TestCount; Index++) { + CurrentTest = (UNIT_TEST_SAVE_TEST *)FloatingPointer; + if (CompareFingerprints (&Test->Fingerprint[0], &CurrentTest->Fingerprint[0])) { + MatchingTest = CurrentTest; + // + // If there's a saved context, it's important that we iterate through the entire list. + // + if (!SavedState->HasSavedContext) { + break; + } + } + + // + // If we didn't find it, we have to increment to the next test. + // + FloatingPointer = (UINT8 *)CurrentTest + CurrentTest->Size; + } + + // + // If a matching test was found, copy the status. + // + if (MatchingTest) { + // + // Override the test status with the saved status. + // + Test->Result = MatchingTest->Result; + + Test->FailureType = MatchingTest->FailureType; + AsciiStrnCpyS ( + &Test->FailureMessage[0], + UNIT_TEST_TESTFAILUREMSG_LENGTH, + &MatchingTest->FailureMessage[0], + UNIT_TEST_TESTFAILUREMSG_LENGTH + ); + + // + // If there is a log string associated, grab that. + // We can tell that there's a log string because the "size" will be larger than + // the structure size. + // IMPORTANT NOTE: There are security implications here. + // This data is user-supplied and we're about to play kinda + // fast and loose with data buffers. + // + if (MatchingTest->Size > sizeof (UNIT_TEST_SAVE_TEST)) { + UnitTestLogInit (Test, (UINT8 *)MatchingTest->Log, MatchingTest->Size - sizeof (UNIT_TEST_SAVE_TEST)); + } + } + + // + // If the saved context exists and matches this test, grab it, too. + // + if (SavedState->HasSavedContext) { + // + // If there was a saved context, the "matching test" loop will have placed the FloatingPointer + // at the beginning of the context structure. + // + SavedContext = (UNIT_TEST_SAVE_CONTEXT *)FloatingPointer; + if ((SavedContext->Size - sizeof (UNIT_TEST_SAVE_CONTEXT)) > 0 && + CompareFingerprints (&Test->Fingerprint[0], &SavedContext->Fingerprint[0])) { + // + // Override the test context with the saved context. + // + Test->Context = (VOID*)SavedContext->Data; + } + } +} + +STATIC +UNIT_TEST_SAVE_HEADER* +SerializeState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave, OPTIONAL + IN UINTN ContextToSaveSize + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_SAVE_HEADER *Header; + LIST_ENTRY *SuiteListHead; + LIST_ENTRY *Suite; + LIST_ENTRY *TestListHead; + LIST_ENTRY *Test; + UINT32 TestCount; + UINT32 TotalSize; + UINTN LogSize; + UNIT_TEST_SAVE_TEST *TestSaveData; + UNIT_TEST_SAVE_CONTEXT *TestSaveContext; + UNIT_TEST *UnitTest; + UINT8 *FloatingPointer; + + Framework = (UNIT_TEST_FRAMEWORK *)FrameworkHandle; + Header = NULL; + + // + // First, let's not make assumptions about the parameters. + // + if (Framework == NULL || + (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) { + return NULL; + } + + // + // Next, we've gotta figure out the resources that will be required to serialize the + // the framework state so that we can persist it. + // To start with, we're gonna need a header. + // + TotalSize = sizeof (UNIT_TEST_SAVE_HEADER); + // + // Now we need to figure out how many tests there are. + // + TestCount = 0; + // + // Iterate all suites. + // + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode (SuiteListHead); Suite != SuiteListHead; Suite = GetNextNode (SuiteListHead, Suite)) { + // + // Iterate all tests within the suite. + // + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY *)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode (TestListHead); Test != TestListHead; Test = GetNextNode (TestListHead, Test)) { + UnitTest = &((UNIT_TEST_LIST_ENTRY *)Test)->UT; + // + // Account for the size of a test structure. + // + TotalSize += sizeof( UNIT_TEST_SAVE_TEST ); + // + // If there's a log, make sure to account for the log size. + // + if (UnitTest->Log != NULL) { + // + // The +1 is for the NULL character. Can't forget the NULL character. + // + LogSize = (AsciiStrLen (UnitTest->Log) + 1) * sizeof (CHAR8); + ASSERT (LogSize < MAX_UINT32); + TotalSize += (UINT32)LogSize; + } + // + // Increment the test count. + // + TestCount++; + } + } + // + // If there are no tests, we're done here. + // + if (TestCount == 0) { + return NULL; + } + // + // Add room for the context, if there is one. + // + if (ContextToSave != NULL) { + TotalSize += sizeof (UNIT_TEST_SAVE_CONTEXT) + (UINT32)ContextToSaveSize; + } + + // + // Now that we know the size, we need to allocate space for the serialized output. + // + Header = AllocateZeroPool (TotalSize); + if (Header == NULL) { + return NULL; + } + + // + // Alright, let's start setting up some data. + // + Header->Version = UNIT_TEST_PERSISTENCE_LIB_VERSION; + Header->SaveStateSize = TotalSize; + CopyMem (&Header->Fingerprint[0], &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE); + CopyMem (&Header->StartTime, &Framework->StartTime, sizeof (EFI_TIME)); + Header->TestCount = TestCount; + Header->HasSavedContext = FALSE; + + // + // Start adding all of the test cases. + // Set the floating pointer to the start of the current test save buffer. + // + FloatingPointer = (UINT8*)Header + sizeof( UNIT_TEST_SAVE_HEADER ); + // + // Iterate all suites. + // + SuiteListHead = &Framework->TestSuiteList; + for (Suite = GetFirstNode (SuiteListHead); Suite != SuiteListHead; Suite = GetNextNode (SuiteListHead, Suite)) { + // + // Iterate all tests within the suite. + // + TestListHead = &((UNIT_TEST_SUITE_LIST_ENTRY *)Suite)->UTS.TestCaseList; + for (Test = GetFirstNode (TestListHead); Test != TestListHead; Test = GetNextNode (TestListHead, Test)) { + TestSaveData = (UNIT_TEST_SAVE_TEST *)FloatingPointer; + UnitTest = &((UNIT_TEST_LIST_ENTRY *)Test)->UT; + + // + // Save the fingerprint. + // + CopyMem (&TestSaveData->Fingerprint[0], &UnitTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE); + + // + // Save the result. + // + TestSaveData->Result = UnitTest->Result; + TestSaveData->FailureType = UnitTest->FailureType; + AsciiStrnCpyS (&TestSaveData->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, &UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH); + + + // + // If there is a log, save the log. + // + FloatingPointer += sizeof (UNIT_TEST_SAVE_TEST); + if (UnitTest->Log != NULL) { + // + // The +1 is for the NULL character. Can't forget the NULL character. + // + LogSize = (AsciiStrLen (UnitTest->Log) + 1) * sizeof (CHAR8); + CopyMem (FloatingPointer, UnitTest->Log, LogSize); + FloatingPointer += LogSize; + } + + // + // Update the size once the structure is complete. + // NOTE: Should thise be a straight cast without validation? + // + TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8 *)TestSaveData); + } + } + + // + // If there is a context to save, let's do that now. + // + if (ContextToSave != NULL && Framework->CurrentTest != NULL) { + TestSaveContext = (UNIT_TEST_SAVE_CONTEXT*)FloatingPointer; + TestSaveContext->Size = (UINT32)ContextToSaveSize + sizeof (UNIT_TEST_SAVE_CONTEXT); + CopyMem (&TestSaveContext->Fingerprint[0], &Framework->CurrentTest->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE); + CopyMem (((UINT8 *)TestSaveContext + sizeof (UNIT_TEST_SAVE_CONTEXT)), ContextToSave, ContextToSaveSize); + Header->HasSavedContext = TRUE; + } + + return Header; +} + +EFI_STATUS +EFIAPI +SaveFrameworkState ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_CONTEXT ContextToSave, OPTIONAL + IN UINTN ContextToSaveSize + ) +{ + EFI_STATUS Status; + UNIT_TEST_SAVE_HEADER *Header; + + Header = NULL; + + // + // First, let's not make assumptions about the parameters. + // + if (FrameworkHandle == NULL || + (ContextToSave != NULL && ContextToSaveSize == 0) || + ContextToSaveSize > MAX_UINT32) { + return EFI_INVALID_PARAMETER; + } + + // + // Now, let's package up all the data for saving. + // + Header = SerializeState (FrameworkHandle, ContextToSave, ContextToSaveSize); + if (Header == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // All that should be left to do is save it using the associated persistence lib. + // + Status = SaveUnitTestCache (FrameworkHandle, Header); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Could not save state! %r\n", __FUNCTION__, Status)); + Status = EFI_DEVICE_ERROR; + } + + // + // Free data that was used. + // + FreePool (Header); + + return Status; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf new file mode 100644 index 00000000000..8fd168d22c0 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf @@ -0,0 +1,37 @@ +## @file +# Library to support Unit Testing from PEI, DXE, SMM, and UEFI Applications. +# +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestLib + MODULE_UNI_FILE = UnitTestLib.uni + FILE_GUID = 98CEF9CA-15CE-40A3-ADE8-C299953CD0F6 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_DRIVER + LIBRARY_CLASS = UnitTestLib|PEIM DXE_DRIVER DXE_SMM_DRIVER UEFI_DRIVER UEFI_APPLICATION + +[Sources] + UnitTestLib.c + RunTests.c + Assert.c + Log.c + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + PcdLib + DebugLib + MemoryAllocationLib + UnitTestPersistenceLib + UnitTestResultReportLib + +[Pcd] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.uni b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.uni new file mode 100644 index 00000000000..fe7c9c7f715 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.uni @@ -0,0 +1,11 @@ +// /** @file +// Library to support Unit Testing from PEI, DXE, SMM, and UEFI Applications. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Library to support Unit Testing from PEI, DXE, SMM, and UEFI Applications" + +#string STR_MODULE_DESCRIPTION #language en-US "Library to support Unit Testing from PEI, DXE, SMM, and UEFI Applications." diff --git a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf similarity index 51% rename from UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf rename to UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf index a59f3c107b9..cc6931937da 100644 --- a/UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf @@ -1,4 +1,5 @@ ## @file +# Library to support Unit Testing from host environments using Cmocka services. # # Copyright (c) 2019, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -8,19 +9,31 @@ [Defines] INF_VERSION = 0x00010017 BASE_NAME = UnitTestLibCmocka + MODULE_UNI_FILE = UnitTestLibCmocka.uni FILE_GUID = C800595F-45A3-45A1-8B50-28F01C2A5A4F VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestLib + MODULE_TYPE = UEFI_DRIVER + LIBRARY_CLASS = UnitTestLib|HOST_APPLICATION -[LibraryClasses] - BaseLib - MemoryAllocationLib - CmockaLib +[Sources] + UnitTestLib.c + RunTestsCmocka.c + AssertCmocka.c + Log.c [Packages] MdePkg/MdePkg.dec UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec -[Sources] - UnitTestLib.c +[LibraryClasses] + BaseLib + BaseMemoryLib + PcdLib + DebugLib + MemoryAllocationLib + UnitTestPersistenceLib + UnitTestResultReportLib + CmockaLib + +[Pcd] + gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.uni b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.uni new file mode 100644 index 00000000000..aa25a44e359 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.uni @@ -0,0 +1,11 @@ +// /** @file +// Library to support Unit Testing from host environments using Cmocka services. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Library to support Unit Testing from host environments using Cmocka services" + +#string STR_MODULE_DESCRIPTION #language en-US "Library to support Unit Testing from host environments using Cmocka services." diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c new file mode 100644 index 00000000000..299e4d99b49 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -0,0 +1,88 @@ +/** @file -- UnitTestNullPersistenceLib.c + This is an instance of the Unit Test Persistence Lib that does nothing. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + + + Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + return FALSE; +} + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + return EFI_UNSUPPORTED; +} + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + return EFI_UNSUPPORTED; +} diff --git a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf similarity index 77% rename from UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf index 3b1090fa25c..989d4bb5f77 100644 --- a/UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -1,7 +1,6 @@ -## @file UnitTestPersistenceLibNull.inf +## @file # This is an instance of the Unit Test Persistence Lib does nothing. # -# @copyright # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -19,14 +18,14 @@ # ## - [Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestPersistenceLibNull - FILE_GUID = B8553C7A-0B0B-4BBD-9DF3-825804BF26AB - VERSION_STRING = 1.0 - MODULE_TYPE = BASE - LIBRARY_CLASS = UnitTestPersistenceLib + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibNull + MODULE_UNI_FILE = UnitTestPersistenceLibNull.uni + FILE_GUID = B8553C7A-0B0B-4BBD-9DF3-825804BF26AB + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_DRIVER + LIBRARY_CLASS = UnitTestPersistenceLib # # The following information is for reference only and not required by the build tools. @@ -34,11 +33,9 @@ # VALID_ARCHITECTURES = IA32 X64 # - [Sources] UnitTestPersistenceLibNull.c - [Packages] MdePkg/MdePkg.dec UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.uni b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.uni new file mode 100644 index 00000000000..00f7d8d7f00 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.uni @@ -0,0 +1,11 @@ +// /** @file +// NULL library for Unit Test Persistence Lib. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "NULL library for Unit Test Persistence Lib" + +#string STR_MODULE_DESCRIPTION #language en-US "NULL library for Unit Test Persistence Lib." diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c new file mode 100644 index 00000000000..039b86223b8 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c @@ -0,0 +1,428 @@ +/** @file + This is an instance of the Unit Test Persistence Lib that will utilize + the filesystem that a test application is running from to save a serialized + version of the internal test state in case the test needs to quit and restore. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" + AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE + LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR + CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF + SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS + INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN + CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) + ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF + THE POSSIBILITY OF SUCH DAMAGE. + + Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + +**/ + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define CACHE_FILE_SUFFIX L"_Cache.dat" + +/** + Generate the device path to the cache file. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval !NULL A pointer to the EFI_FILE protocol instance for the filesystem. + @retval NULL Filesystem could not be found or an error occurred. + +**/ +STATIC +EFI_DEVICE_PATH_PROTOCOL* +GetCacheFileDevicePath ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK *Framework; + EFI_LOADED_IMAGE_PROTOCOL *LoadedImage; + CHAR16 *AppPath; + CHAR16 *CacheFilePath; + CHAR16 *TestName; + UINTN DirectorySlashOffset; + UINTN CacheFilePathLength; + EFI_DEVICE_PATH_PROTOCOL *CacheFileDevicePath; + + Framework = (UNIT_TEST_FRAMEWORK*)FrameworkHandle; + AppPath = NULL; + CacheFilePath = NULL; + TestName = NULL; + CacheFileDevicePath = NULL; + + // + // First, we need to get some information from the loaded image. + // + Status = gBS->HandleProtocol ( + gImageHandle, + &gEfiLoadedImageProtocolGuid, + (VOID**)&LoadedImage + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_WARN, "%a - Failed to locate DevicePath for loaded image. %r\n", __FUNCTION__, Status)); + return NULL; + } + + // + // Before we can start, change test name from ASCII to Unicode. + // + CacheFilePathLength = AsciiStrLen (Framework->ShortTitle) + 1; + TestName = AllocatePool (CacheFilePathLength); + if (!TestName) { + goto Exit; + } + AsciiStrToUnicodeStrS (Framework->ShortTitle, TestName, CacheFilePathLength); + + // + // Now we should have the device path of the root device and a file path for the rest. + // In order to target the directory for the test application, we must process + // the file path a little. + // + // NOTE: This may not be necessary... Path processing functions exist... + // PathCleanUpDirectories (FileNameCopy); + // if (PathRemoveLastItem (FileNameCopy)) { + // + AppPath = ConvertDevicePathToText (LoadedImage->FilePath, TRUE, TRUE); // NOTE: This must be freed. + DirectorySlashOffset = StrLen (AppPath); + // + // Make sure we didn't get any weird data. + // + if (DirectorySlashOffset == 0) { + DEBUG ((DEBUG_ERROR, "%a - Weird 0-length string when processing app path.\n", __FUNCTION__)); + goto Exit; + } + + // + // Now that we know we have a decent string, let's take a deeper look. + // + do { + if (AppPath[DirectorySlashOffset] == L'\\') { + break; + } + DirectorySlashOffset--; + } while (DirectorySlashOffset > 0); + + // + // After that little maneuver, DirectorySlashOffset should be pointing at the last '\' in AppString. + // That would be the path to the parent directory that the test app is executing from. + // Let's check and make sure that's right. + // + if (AppPath[DirectorySlashOffset] != L'\\') { + DEBUG ((DEBUG_ERROR, "%a - Could not find a single directory separator in app path.\n", __FUNCTION__)); + goto Exit; + } + + // + // Now we know some things, we're ready to produce our output string, I think. + // + CacheFilePathLength = DirectorySlashOffset + 1; + CacheFilePathLength += StrLen (TestName); + CacheFilePathLength += StrLen (CACHE_FILE_SUFFIX); + CacheFilePathLength += 1; // Don't forget the NULL terminator. + CacheFilePath = AllocateZeroPool (CacheFilePathLength * sizeof (CHAR16)); + if (!CacheFilePath) { + goto Exit; + } + + // + // Let's produce our final path string, shall we? + // + StrnCpyS (CacheFilePath, CacheFilePathLength, AppPath, DirectorySlashOffset + 1); // Copy the path for the parent directory. + StrCatS (CacheFilePath, CacheFilePathLength, TestName); // Copy the base name for the test cache. + StrCatS (CacheFilePath, CacheFilePathLength, CACHE_FILE_SUFFIX); // Copy the file suffix. + + // + // Finally, try to create the device path for the thing thing. + // + CacheFileDevicePath = FileDevicePath (LoadedImage->DeviceHandle, CacheFilePath); + +Exit: + // + // Free allocated buffers. + // + if (AppPath != NULL) { + FreePool (AppPath); + } + if (CacheFilePath != NULL) { + FreePool (CacheFilePath); + } + if (TestName != NULL) { + FreePool (TestName); + } + + return CacheFileDevicePath; +} + +/** + Determines whether a persistence cache already exists for + the given framework. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + + @retval TRUE + @retval FALSE Cache doesn't exist or an error occurred. + +**/ +BOOLEAN +EFIAPI +DoesCacheExist ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + + // + // NOTE: This devpath is allocated and must be freed. + // + FileDevicePath = GetCacheFileDevicePath (FrameworkHandle); + + // + // Check to see whether the file exists. If the file can be opened for + // reading, it exists. Otherwise, probably not. + // + Status = ShellOpenFileByDevicePath ( + &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 + ); + if (!EFI_ERROR (Status)) { + ShellCloseFile (&FileHandle); + } + + if (FileDevicePath != NULL) { + FreePool (FileDevicePath); + } + + DEBUG ((DEBUG_VERBOSE, "%a - Returning %d\n", __FUNCTION__, !EFI_ERROR (Status))); + + return (!EFI_ERROR (Status)); +} + +/** + Will save the data associated with an internal Unit Test Framework + state in a manner that can persist a Unit Test Application quit or + even a system reboot. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer to the buffer containing the serialized + framework internal state. + + @retval EFI_SUCCESS Data is persisted and the test can be safely quit. + @retval Others Data is not persisted and test cannot be resumed upon exit. + +**/ +EFI_STATUS +EFIAPI +SaveUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData + ) +{ + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + EFI_STATUS Status; + SHELL_FILE_HANDLE FileHandle; + UINTN WriteCount; + + // + // Check the inputs for sanity. + // + if (FrameworkHandle == NULL || SaveData == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + // + FileDevicePath = GetCacheFileDevicePath (FrameworkHandle); + + // + //First lets open the file if it exists so we can delete it...This is the work around for truncation + // + Status = ShellOpenFileByDevicePath ( + &FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE), + 0 + ); + + if (!EFI_ERROR (Status)) { + // + // If file handle above was opened it will be closed by the delete. + // + Status = ShellDeleteFile (&FileHandle); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a failed to delete file %r\n", __FUNCTION__, Status)); + } + } + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath ( + &FileDevicePath, + &FileHandle, + (EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE | EFI_FILE_MODE_CREATE), + 0 + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status)); + goto Exit; + } + + // + // Write the data to the file. + // + WriteCount = SaveData->SaveStateSize; + DEBUG ((DEBUG_INFO, "%a - Writing %d bytes to file...\n", __FUNCTION__, WriteCount)); + Status = ShellWriteFile ( + FileHandle, + &WriteCount, + SaveData + ); + + if (EFI_ERROR (Status) || WriteCount != SaveData->SaveStateSize) { + DEBUG ((DEBUG_ERROR, "%a - Writing to file failed! %r\n", __FUNCTION__, Status)); + } else { + DEBUG ((DEBUG_INFO, "%a - SUCCESS!\n", __FUNCTION__)); + } + + // + // No matter what, we should probably close the file. + // + ShellCloseFile (&FileHandle); + +Exit: + if (FileDevicePath != NULL) { + FreePool (FileDevicePath); + } + + return Status; +} + +/** + Will retrieve any cached state associated with the given framework. + Will allocate a buffer to hold the loaded data. + + @param[in] FrameworkHandle A pointer to the framework that is being persisted. + @param[in] SaveData A pointer pointer that will be updated with the address + of the loaded data buffer. + + @retval EFI_SUCCESS Data has been loaded successfully and SaveData is updated + with a pointer to the buffer. + @retval Others An error has occurred and no data has been loaded. SaveData + is set to NULL. + +**/ +EFI_STATUS +EFIAPI +LoadUnitTestCache ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + OUT UNIT_TEST_SAVE_HEADER **SaveData + ) +{ + EFI_STATUS Status; + EFI_DEVICE_PATH_PROTOCOL *FileDevicePath; + SHELL_FILE_HANDLE FileHandle; + BOOLEAN IsFileOpened; + UINT64 LargeFileSize; + UINTN FileSize; + UNIT_TEST_SAVE_HEADER *Buffer; + + IsFileOpened = FALSE; + Buffer = NULL; + + // + // Check the inputs for sanity. + // + if (FrameworkHandle == NULL || SaveData == NULL) { + return EFI_INVALID_PARAMETER; + } + + // + // Determine the path for the cache file. + // NOTE: This devpath is allocated and must be freed. + // + FileDevicePath = GetCacheFileDevicePath (FrameworkHandle); + + // + // Now that we know the path to the file... let's open it for writing. + // + Status = ShellOpenFileByDevicePath ( + &FileDevicePath, + &FileHandle, + EFI_FILE_MODE_READ, + 0 + ); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Opening file for writing failed! %r\n", __FUNCTION__, Status)); + goto Exit; + } else { + IsFileOpened = TRUE; + } + + // + // Now that the file is opened, we need to determine how large a buffer we need. + // + Status = ShellGetFileSize (FileHandle, &LargeFileSize); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Failed to determine file size! %r\n", __FUNCTION__, Status)); + goto Exit; + } + + // + // Now that we know the size, let's allocated a buffer to hold the contents. + // + FileSize = (UINTN)LargeFileSize; // You know what... if it's too large, this lib don't care. + Buffer = AllocatePool (FileSize); + if (Buffer == NULL) { + DEBUG ((DEBUG_ERROR, "%a - Failed to allocate a pool to hold the file contents! %r\n", __FUNCTION__, Status)); + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } + + // + // Finally, let's read the data. + // + Status = ShellReadFile (FileHandle, &FileSize, Buffer); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "%a - Failed to read the file contents! %r\n", __FUNCTION__, Status)); + } + +Exit: + // + // Free allocated buffers + // + if (FileDevicePath != NULL) { + FreePool (FileDevicePath); + } + if (IsFileOpened) { + ShellCloseFile (&FileHandle); + } + + // + // If we're returning an error, make sure + // the state is sane. + if (EFI_ERROR (Status) && Buffer != NULL) { + FreePool (Buffer); + Buffer = NULL; + } + + *SaveData = Buffer; + return Status; +} diff --git a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf similarity index 64% rename from UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf rename to UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf index acd37f7227c..31fb168e732 100644 --- a/UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf @@ -1,9 +1,10 @@ -## @file UnitTestPersistenceLibFileSystem.inf -# This is an instance of the Unit Test Persistence Lib that will utilize -# the filesystem that a test application is running from to save a serialized -# version of the internal test state in case the test needs to quit and restore. +## @file +# UEFI Simple File System based version of the Unit Test Persistence Lib +# +# Instance of the Unit Test Persistence Lib that utilizes the UEFI filesystem +# that a test application is running from to save a serialized version of the +# internal test state in case the test needs to quit and restore. # -# @copyright # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE @@ -16,19 +17,18 @@ # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF # THE POSSIBILITY OF SUCH DAMAGE. # -# # Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. # ## - [Defines] - INF_VERSION = 0x00010017 - BASE_NAME = UnitTestPersistenceLibFileSystem - FILE_GUID = 9200844A-CDFD-4368-B4BD-106354702605 - VERSION_STRING = 1.0 - MODULE_TYPE = UEFI_APPLICATION - LIBRARY_CLASS = UnitTestPersistenceLib|UEFI_APPLICATION + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestPersistenceLibSimpleFileSystem + MODULE_UNI_FILE = UnitTestPersistenceLibSimpleFileSystem.uni + FILE_GUID = 9200844A-CDFD-4368-B4BD-106354702605 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_APPLICATION + LIBRARY_CLASS = UnitTestPersistenceLib # # The following information is for reference only and not required by the build tools. @@ -36,29 +36,24 @@ # VALID_ARCHITECTURES = IA32 X64 # - [Sources] - UnitTestPersistenceLibFileSystem.c - + UnitTestPersistenceLibSimpleFileSystem.c [Packages] MdePkg/MdePkg.dec UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec ShellPkg/ShellPkg.dec - [LibraryClasses] DebugLib UefiBootServicesTableLib BaseLib ShellLib - [Protocols] gEfiLoadedImageProtocolGuid gEfiSimpleFileSystemProtocolGuid - [Guids] gEfiFileInfoGuid gEfiFileSystemInfoGuid diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.uni b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.uni new file mode 100644 index 00000000000..e6593be137d --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.uni @@ -0,0 +1,15 @@ +// /** @file +// UEFI Simple File System based version of the Unit Test Persistence Lib +// +// Instance of the Unit Test Persistence Lib that utilizes the UEFI filesystem +// that a test application is running from to save a serialized version of the +// internal test state in case the test needs to quit and restore. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "UEFI Simple File System based version of the Unit Test Persistence Lib" + +#string STR_MODULE_DESCRIPTION #language en-US "UEFI Simple File System based version of the Unit Test Persistence Lib." diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c new file mode 100644 index 00000000000..64ae67a4cdf --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -0,0 +1,217 @@ +/** @file + + Implement UnitTestResultReportLib doing plain txt out to console + + Copyright (c) Microsoft + +**/ + +#include +#include +#include +#include + +VOID +ReportPrint ( + IN CONST CHAR8 *Format, + ... + ); + +VOID +ReportOutput ( + IN CONST CHAR8 *Output + ); + +struct _UNIT_TEST_STATUS_STRING { + UNIT_TEST_STATUS Status; + CHAR8 *String; +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING { + FAILURE_TYPE Type; + CHAR8 *String; +}; + +struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = { + { UNIT_TEST_PASSED, "PASSED"}, + { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED"}, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED"}, + { UNIT_TEST_RUNNING, "RUNNING"}, + { UNIT_TEST_PENDING, "PENDING"}, + { 0, "**UNKNOWN**"} +}; + +struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[] = { + { FAILURETYPE_NOFAILURE, "NO FAILURE"}, + { FAILURETYPE_OTHER, "OTHER FAILURE"}, + { FAILURETYPE_ASSERTTRUE, "ASSERT_TRUE FAILURE"}, + { FAILURETYPE_ASSERTFALSE, "ASSERT_FALSE FAILURE"}, + { FAILURETYPE_ASSERTEQUAL, "ASSERT_EQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEQUAL, "ASSERT_NOTEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTEFIERROR, "ASSERT_NOTEFIERROR FAILURE"}, + { FAILURETYPE_ASSERTSTATUSEQUAL, "ASSERT_STATUSEQUAL FAILURE"}, + { FAILURETYPE_ASSERTNOTNULL , "ASSERT_NOTNULL FAILURE"}, + { 0, "*UNKNOWN* Failure"} +}; + +// +// TEST REPORTING FUNCTIONS +// + +STATIC +CONST CHAR8* +GetStringForUnitTestStatus ( + IN UNIT_TEST_STATUS Status + ) +{ + UINTN Index; + + for (Index = 0; Index < ARRAY_SIZE (mStatusStrings); Index++) { + if (mStatusStrings[Index].Status == Status) { + // + // Return string from matching entry + // + return mStatusStrings[Index].String; + } + } + // + // Return last entry if no match found. + // + return mStatusStrings[Index].String; +} + +STATIC +CONST CHAR8* +GetStringForFailureType ( + IN FAILURE_TYPE Failure + ) +{ + UINTN Index; + + for (Index = 0; Index < ARRAY_SIZE (mFailureTypeStrings); Index++) { + if (mFailureTypeStrings[Index].Type == Failure) { + // + // Return string from matching entry + // + return mFailureTypeStrings[Index].String; + } + } + // + // Return last entry if no match found. + // + DEBUG((DEBUG_INFO, "%a Failure Type does not have string defined 0x%X\n", __FUNCTION__, (UINT32)Failure)); + return mFailureTypeStrings[Index].String; +} + +/* + Method to print the Unit Test run results + + @retval Success +*/ +EFI_STATUS +EFIAPI +OutputUnitTestFrameworkReport ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + INTN Passed; + INTN Failed; + INTN NotRun; + UNIT_TEST_SUITE_LIST_ENTRY *Suite; + UNIT_TEST_LIST_ENTRY *Test; + INTN SPassed; + INTN SFailed; + INTN SNotRun; + + Passed = 0; + Failed = 0; + NotRun = 0; + Suite = NULL; + + Framework = (UNIT_TEST_FRAMEWORK *)FrameworkHandle; + if (Framework == NULL) { + return EFI_INVALID_PARAMETER; + } + + ReportPrint ("---------------------------------------------------------\n"); + ReportPrint ("------------- UNIT TEST FRAMEWORK RESULTS ---------------\n"); + ReportPrint ("---------------------------------------------------------\n"); + + //print the version and time + + // + // Iterate all suites + // + for (Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetFirstNode(&Framework->TestSuiteList); + (LIST_ENTRY*)Suite != &Framework->TestSuiteList; + Suite = (UNIT_TEST_SUITE_LIST_ENTRY*)GetNextNode(&Framework->TestSuiteList, (LIST_ENTRY*)Suite)) { + + Test = NULL; + SPassed = 0; + SFailed = 0; + SNotRun = 0; + + ReportPrint ("/////////////////////////////////////////////////////////\n"); + ReportPrint (" SUITE: %a\n", Suite->UTS.Title); + ReportPrint (" PACKAGE: %a\n", Suite->UTS.Package); + ReportPrint ("/////////////////////////////////////////////////////////\n"); + + // + // Iterate all tests within the suite + // + for (Test = (UNIT_TEST_LIST_ENTRY*)GetFirstNode(&(Suite->UTS.TestCaseList)); + (LIST_ENTRY*)Test != &(Suite->UTS.TestCaseList); + Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) { + + ReportPrint ("*********************************************************\n"); + ReportPrint (" CLASS NAME: %a\n", Test->UT.ClassName); + ReportPrint (" TEST: %a\n", Test->UT.Description); + ReportPrint (" STATUS: %a\n", GetStringForUnitTestStatus (Test->UT.Result)); + ReportPrint (" FAILURE: %a\n", GetStringForFailureType (Test->UT.FailureType)); + ReportPrint (" FAILURE MESSAGE:\n%a\n", Test->UT.FailureMessage); + + if (Test->UT.Log != NULL) { + ReportPrint (" LOG:\n"); + ReportOutput (Test->UT.Log); + } + + switch (Test->UT.Result) { + case UNIT_TEST_PASSED: + SPassed++; + break; + case UNIT_TEST_ERROR_TEST_FAILED: + SFailed++; + break; + case UNIT_TEST_PENDING: // Fall through... + case UNIT_TEST_RUNNING: // Fall through... + case UNIT_TEST_ERROR_PREREQ_NOT_MET: + SNotRun++; + break; + default: + break; + } + ReportPrint ("**********************************************************\n"); + } //End Test iteration + + ReportPrint ("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n"); + ReportPrint ("Suite Stats\n"); + ReportPrint (" Passed: %d (%d%%)\n", SPassed, (SPassed * 100)/(SPassed+SFailed+SNotRun)); + ReportPrint (" Failed: %d (%d%%)\n", SFailed, (SFailed * 100) / (SPassed + SFailed + SNotRun)); + ReportPrint (" Not Run: %d (%d%%)\n", SNotRun, (SNotRun * 100) / (SPassed + SFailed + SNotRun)); + ReportPrint ("+++++++++++++++++++++++++++++++++++++++++++++++++++++++++\n" ); + + Passed += SPassed; //add to global counters + Failed += SFailed; //add to global counters + NotRun += SNotRun; //add to global coutners + }//End Suite iteration + + ReportPrint ("=========================================================\n"); + ReportPrint ("Total Stats\n"); + ReportPrint (" Passed: %d (%d%%)\n", Passed, (Passed * 100) / (Passed + Failed + NotRun)); + ReportPrint (" Failed: %d (%d%%)\n", Failed, (Failed * 100) / (Passed + Failed + NotRun)); + ReportPrint (" Not Run: %d (%d%%)\n", NotRun, (NotRun * 100) / (Passed + Failed + NotRun)); + ReportPrint ("=========================================================\n" ); + + return EFI_SUCCESS; +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c new file mode 100644 index 00000000000..6d37871516b --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c @@ -0,0 +1,49 @@ +/** @file + + Implement UnitTestResultReportLib doing plain txt out to console + + Copyright (c) Microsoft + +**/ + +#include +#include +#include +#include +#include + +VOID +ReportPrint ( + IN CONST CHAR8 *Format, + ... + ) +{ + VA_LIST Marker; + CHAR16 String[256]; + UINTN Length; + + VA_START (Marker, Format); + Length = UnicodeVSPrintAsciiFormat (String, sizeof (String), Format, Marker); + if (Length == 0) { + DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __FUNCTION__)); + } else { + gST->ConOut->OutputString (gST->ConOut, String); + } + VA_END (Marker); +} + +VOID +ReportOutput ( + IN CONST CHAR8 *Output + ) +{ + CHAR8 AsciiString[128]; + UINTN Length; + UINTN Index; + + Length = AsciiStrLen (Output); + for (Index = 0; Index < Length; Index += (sizeof (AsciiString) - 1)) { + AsciiStrCpyS (AsciiString, sizeof (AsciiString), &Output[Index]); + ReportPrint ("%a", AsciiString); + } +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf new file mode 100644 index 00000000000..1dda101973c --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf @@ -0,0 +1,29 @@ +## @file +# Library to support printing out the unit test report to a UEFI console +# +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestResultReportLibConOut + MODULE_UNI_FILE = UnitTestResultReportLibConOut.uni + FILE_GUID = C659641D-BA1F-4B58-946E-B1E1103903F9 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_DRIVER + LIBRARY_CLASS = UnitTestResultReportLib + +[LibraryClasses] + BaseLib + DebugLib + UefiBootServicesTableLib + PrintLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[Sources] + UnitTestResultReportLib.c + UnitTestResultReportLibConOut.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.uni b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.uni new file mode 100644 index 00000000000..92ba1b84da3 --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.uni @@ -0,0 +1,11 @@ +// /** @file +// Library to support printing out the unit test report to a UEFI console +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Library to support printing out the unit test report to a UEFI console" + +#string STR_MODULE_DESCRIPTION #language en-US "Library to support printing out the unit test report to a UEFI console." diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c new file mode 100644 index 00000000000..3f7cd61052c --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c @@ -0,0 +1,48 @@ +/** @file + + Implement UnitTestResultReportLib doing plain txt out to console + + Copyright (c) Microsoft + +**/ + +#include +#include +#include +#include + +VOID +ReportPrint ( + IN CONST CHAR8 *Format, + ... + ) +{ + VA_LIST Marker; + CHAR8 String[256]; + UINTN Length; + + VA_START (Marker, Format); + Length = AsciiVSPrint (String, sizeof (String), Format, Marker); + if (Length == 0) { + DEBUG ((DEBUG_ERROR, "%a formatted string is too long\n", __FUNCTION__)); + } else { + DEBUG ((DEBUG_INFO, String)); + } + VA_END (Marker); +} + +VOID +ReportOutput ( + IN CONST CHAR8 *Output + ) +{ + CHAR8 AsciiString[128]; + UINTN Length; + UINTN Index; + + Length = AsciiStrLen (Output); + for (Index = 0; Index < Length; Index += (sizeof (AsciiString) - 1)) { + AsciiStrCpyS (AsciiString, sizeof (AsciiString), &Output[Index]); + DEBUG ((DEBUG_INFO, AsciiString)); + } +} diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf new file mode 100644 index 00000000000..86c352aa76a --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf @@ -0,0 +1,28 @@ +## @file +# Library to support printing out the unit test report using DEBUG() macros. +# +# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# +## + +[Defines] + INF_VERSION = 0x00010017 + BASE_NAME = UnitTestResultReportLibDebugLib + MODULE_UNI_FILE = UnitTestResultReportLibDebugLib.uni + FILE_GUID = BED736D4-D197-475F-B7CE-0D828FF2C9A6 + VERSION_STRING = 1.0 + MODULE_TYPE = UEFI_DRIVER + LIBRARY_CLASS = UnitTestResultReportLib + +[LibraryClasses] + BaseLib + DebugLib + PrintLib + +[Packages] + MdePkg/MdePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[Sources] + UnitTestResultReportLib.c + UnitTestResultReportLibDebugLib.c diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.uni b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.uni new file mode 100644 index 00000000000..4f1993417ad --- /dev/null +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.uni @@ -0,0 +1,11 @@ +// /** @file +// Library to support printing out the unit test report using DEBUG() macros. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_MODULE_ABSTRACT #language en-US "Library to support printing out the unit test report using DEBUG() macros" + +#string STR_MODULE_DESCRIPTION #language en-US "Library to support printing out the unit test report using DEBUG() macros." diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h index a65b0506be5..8cf151c5e70 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h @@ -1,7 +1,8 @@ /** @file - Provides a library function that can be customized to set the platform to boot from USB on the next boot. - This allows the test framework to reboot back to USB. Since boot managers are not all the same creating a lib to - support platform customization will make porting to new code base/platform easier. + Provides a library function that can be customized to set the platform to boot + from USB on the next boot. This allows the test framework to reboot back to + USB. Since boot managers are not all the same creating a lib to support + platform customization will make porting to new code base/platform easier. Copyright (c) 2016, Microsoft Corporation. All rights reserved.
Copyright (c) 2019, Intel Corporation. All rights reserved.
@@ -13,13 +14,18 @@ #define __UNIT_TEST_BOOT_LIB_H__ /** -Set the boot manager to boot from a specific device on the next boot. -This should be set only for the next boot and shouldn't -require any manual clean up + Set the boot manager to boot from a specific device on the next boot. This + should be set only for the next boot and shouldn't require any manual clean up + + @retval EFI_SUCCESS Boot device for next boot was set. + @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not + supportted. + @retval Other Boot devide for next boot can not be set. **/ EFI_STATUS EFIAPI -SetBootNextDevice ( VOID ); - +SetBootNextDevice ( + VOID + ); #endif diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h index fdec8dead59..44e2b8484f8 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h @@ -1,4 +1,4 @@ -/** @file -- UnitTestPersistenceLib.h +/** @file This header file describes a library that contains functions to save and restore unit test internal state, in case the test needs to pause and resume (eg. a reboot-based test). @@ -12,8 +12,9 @@ #ifndef _UNIT_TEST_PERSISTENCE_LIB_H_ #define _UNIT_TEST_PERSISTENCE_LIB_H_ -#define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 +#include +#define UNIT_TEST_PERSISTENCE_LIB_VERSION 1 /** Determines whether a persistence cache already exists for @@ -28,10 +29,9 @@ BOOLEAN EFIAPI DoesCacheExist ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle ); - /** Will save the data associated with an internal Unit Test Framework state in a manner that can persist a Unit Test Application quit or @@ -48,11 +48,10 @@ DoesCacheExist ( EFI_STATUS EFIAPI SaveUnitTestCache ( - IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_SAVE_HEADER *SaveData + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, + IN UNIT_TEST_SAVE_HEADER *SaveData ); - /** Will retrieve any cached state associated with the given framework. Will allocate a buffer to hold the loaded data. @@ -74,4 +73,4 @@ LoadUnitTestCache ( OUT UNIT_TEST_SAVE_HEADER **SaveData ); -#endif // _UNIT_TEST_PERSISTENCE_LIB_H_ +#endif diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h index cd12e8831c8..abd6daa926a 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h @@ -1,6 +1,6 @@ /** @file - Provides a unit test result report. This allows new result output formats to be easily - customized. + Provides a unit test result report. This allows new result output formats to + be easily customized. Copyright (c) 2016, Microsoft Corporation. All rights reserved.
Copyright (c) 2019, Intel Corporation. All rights reserved.
@@ -11,15 +11,17 @@ #ifndef __UNIT_TEST_RESULT_REPORT_LIB_H__ #define __UNIT_TEST_RESULT_REPORT_LIB_H__ -/* +#include + +/** Method to produce the Unit Test run results @retval Success -*/ +**/ EFI_STATUS EFIAPI -OutputUnitTestFrameworkReport( - IN UNIT_TEST_FRAMEWORK *Framework -); +OutputUnitTestFrameworkReport ( + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle + ); #endif diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 9b1509029f1..90de1df4c81 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -10,6 +10,8 @@ #ifndef __UNIT_TEST_TYPES_H__ #define __UNIT_TEST_TYPES_H__ +#include + ///================================================================================================ ///================================================================================================ /// @@ -17,21 +19,21 @@ /// ///================================================================================================ ///================================================================================================ -#define UNIT_TEST_MAX_STRING_LENGTH (120) +#define UNIT_TEST_MAX_STRING_LENGTH (120) -#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. -#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) +#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. +#define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) typedef UINT32 FAILURE_TYPE; -#define FAILURETYPE_NOFAILURE (0) -#define FAILURETYPE_OTHER (1) -#define FAILURETYPE_ASSERTTRUE (2) -#define FAILURETYPE_ASSERTFALSE (3) -#define FAILURETYPE_ASSERTEQUAL (4) -#define FAILURETYPE_ASSERTNOTEQUAL (5) -#define FAILURETYPE_ASSERTNOTEFIERROR (6) -#define FAILURETYPE_ASSERTSTATUSEQUAL (7) -#define FAILURETYPE_ASSERTNOTNULL (8) +#define FAILURETYPE_NOFAILURE (0) +#define FAILURETYPE_OTHER (1) +#define FAILURETYPE_ASSERTTRUE (2) +#define FAILURETYPE_ASSERTFALSE (3) +#define FAILURETYPE_ASSERTEQUAL (4) +#define FAILURETYPE_ASSERTNOTEQUAL (5) +#define FAILURETYPE_ASSERTNOTEFIERROR (6) +#define FAILURETYPE_ASSERTSTATUSEQUAL (7) +#define FAILURETYPE_ASSERTNOTNULL (8) ///================================================================================================ @@ -63,6 +65,7 @@ typedef struct { } UNIT_TEST_LIST_ENTRY; typedef struct { + UINTN NumTests; CHAR8 *Title; CHAR8 *Package; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf index 81756eea8e1..0a9f864ceb8 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -23,19 +23,12 @@ [Packages] MdePkg/MdePkg.dec -[Protocols] - - [LibraryClasses] BaseLib UefiApplicationEntryPoint DebugLib UnitTestLib - UnitTestAssertLib PrintLib -[Guids] - - diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf index e9e07a6d265..13c3c106df9 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -23,19 +23,13 @@ [Packages] MdePkg/MdePkg.dec -[Protocols] - - [LibraryClasses] BaseLib PeimEntryPoint DebugLib UnitTestLib - UnitTestAssertLib PrintLib -[Guids] - [Depex] gEfiPeiMemoryDiscoveredPpiGuid diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf index 3acc8dba2f3..f134939678e 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -24,19 +24,13 @@ [Packages] MdePkg/MdePkg.dec -[Protocols] - - [LibraryClasses] BaseLib UefiDriverEntryPoint DebugLib UnitTestLib - UnitTestAssertLib PrintLib -[Guids] - [Depex] gEfiSmmCpuProtocolGuid diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index bffa17149b8..1675b0fce68 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,9 +30,7 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf", - "UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf", - "UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf" + "UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf" ] }, "GuidCheck": { diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 007ddfd90fa..f6def29f356 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -9,15 +9,15 @@ ## [Defines] - DEC_SPECIFICATION = 0x00010005 - PACKAGE_NAME = UnitTestPkg - PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 - PACKAGE_VERSION = 1.00 + DEC_SPECIFICATION = 0x00010005 + PACKAGE_NAME = UnitTestPkg + PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 + PACKAGE_VERSION = 1.00 [Includes.Common.Private] PrivateInclude - Library/HostCmocka/CmockaLib/cmocka/include - Library/HostCmocka/CmockaLib/cmocka/include/cmockery + Library/CmockaLib/cmocka/include + Library/CmockaLib/cmocka/include/cmockery [LibraryClasses.Common.Private] ## @libraryclass Allows save and restore unit test internal state diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index d199c1d2373..4ca2e092396 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -3,19 +3,19 @@ # # Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
# -# SPDX-License-Identifier: BSD-2-Clause-Patent +# SPDX-License-Identifier: BSD-2-Clause-Patent # ## [Defines] - PLATFORM_NAME = UnitTestFrameworkPkg - PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 - PLATFORM_VERSION = 1.00 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg - SUPPORTED_ARCHITECTURES = IA32|IPF|X64|EBC|ARM|AARCH64 - BUILD_TARGETS = DEBUG|RELEASE|NOOPT - SKUID_IDENTIFIER = DEFAULT + PLATFORM_NAME = UnitTestFrameworkPkg + PLATFORM_GUID = 7420CC7E-334E-4EFF-B974-A39613455168 + PLATFORM_VERSION = 1.00 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg + SUPPORTED_ARCHITECTURES = IA32|X64|EBC|ARM|AARCH64 + BUILD_TARGETS = DEBUG|RELEASE|NOOPT + SKUID_IDENTIFIER = DEFAULT ################################################################################################### # @@ -149,40 +149,31 @@ # NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf - # - # UnitTestFrameworkPkg - # +# +# UnitTestFrameworkPkg +# [LibraryClasses] - UnitTestAssertLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestLogLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf - UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf -[LibraryClasses.common.PEIM] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - -[LibraryClasses.common.DXE_SMM_DRIVER] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf +[LibraryClasses.common.UEFI_APPLICATION] + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf -[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - UnitTestLib|UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf +[LibraryClasses.common.HOST_APPLICATION] + CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf + DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf [Components] -# UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf -# UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestAssertLib/UnitTestAssertLib.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibDxe.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibPei.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLib/UnitTestLibSmm.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestLogLib/UnitTestLogLib.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestResultReportLibDebug/UnitTestResultReportLibDebug.inf - UnitTestFrameworkPkg/Library/Uefi/UnitTestBootLibNull/UnitTestBootLibNull.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestResultReportLibPlainTextOutput/UnitTestResultReportLibPlainTextOutput.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf - UnitTestFrameworkPkg/Library/UefiShell/UnitTestPersistenceLibFileSystem/UnitTestPersistenceLibFileSystem.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf + UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf + UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf + UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf + UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf + UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf diff --git a/MdePkg/Test/MdePkgTest.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc similarity index 52% rename from MdePkg/Test/MdePkgTest.dsc rename to UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 530cd465b64..4f7371b0911 100644 --- a/MdePkg/Test/MdePkgTest.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -5,41 +5,14 @@ # ## -[Defines] - PLATFORM_NAME = MdePkgTest - PLATFORM_GUID = 50652B4C-88CB-4481-96E8-37F2D0034440 - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/MdePkg/Test - SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT - -[LibraryClasses] - BaseLib|MdePkg/Library/BaseLib/BaseLib.inf - BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf - DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf - MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf - PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc [LibraryClasses.common.HOST_APPLICATION] - CmockaLib|UnitTestFrameworkPkg/Library/HostCmocka/CmockaLib/CmockaLib.inf - UnitTestAssertLib|UnitTestFrameworkPkg/Library/HostCmocka/UnitTestAssertLibCmocka/UnitTestAssertLibCmocka.inf - UnitTestLib|UnitTestFrameworkPkg/Library/HostCmocka/UnitTestLibCmocka/UnitTestLibCmocka.inf - + CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf -[Components] - # - # Build HOST_APPLICATION that tests the SafeIntLib - # - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf - [BuildOptions] GCC:*_*_*_CC_FLAGS = -fno-pie @@ -66,16 +39,7 @@ # GCC:*_*_IA32_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m32 GCC:*_*_X64_DLINK_FLAGS == -o $(BIN_DIR)/$(BASE_NAME) -m64 - GCC:*_*_*_DLINK2_FLAGS == -lgcov - - # - # GCC CLANG9 - # - GCC:*_CLANG9_X64_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x64" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x64" /LIBPATH:"%VCToolsInstallDir%lib\x64" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:AMD64 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint - GCC:*_CLANG9_X64_CC_FLAGS == -m64 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE - - GCC:*_CLANG9_IA32_DLINK_FLAGS == /out:"$(BIN_DIR)\$(BASE_NAME).exe" /base:0x10000000 /pdb:"$(BIN_DIR)\$(BASE_NAME).pdb" /LIBPATH:"%UniversalCRTSdkDir%lib\%UCRTVersion%\ucrt\x86" /LIBPATH:"%WindowsSdkDir%lib\%WindowsSDKLibVersion%\um\x86" /LIBPATH:"%VCToolsInstallDir%ib\x86" /NOLOGO /SUBSYSTEM:CONSOLE /NODEFAULTLIB /IGNORE:4086 /OPT:REF /DEBUG /MACHINE:I386 Kernel32.lib MSVCRTD.lib vcruntimed.lib ucrtd.lib Gdi32.lib User32.lib Winmm.lib Advapi32.lib /lldmap /EXPORT:InitializeDriver=_ModuleEntryPoint - GCC:*_CLANG9_IA32_CC_FLAGS == -m32 -g -fshort-wchar -fno-strict-aliasing -Wall -c -include AutoGen.h -D _CRT_SECURE_NO_WARNINGS -Wnonportable-include-path -D UNICODE -D _CRT_SECURE_NO_DEPRECATE + GCC:*_*_*_DLINK2_FLAGS == -lgcov # # Need to do this link via gcc and not ld as the pathing to libraries changes from OS version to OS version diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc new file mode 100644 index 00000000000..27e7fbe90cf --- /dev/null +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc @@ -0,0 +1,57 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[LibraryClasses] + # + # Entry point + # + PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf + UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf + UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf + + BaseLib|MdePkg/Library/BaseLib/BaseLib.inf + BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf + DebugLib|MdePkg/Library/BaseDebugLibNull/BaseDebugLibNull.inf + MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf + PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf + PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf + PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf + PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf + UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf + + UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf + UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf + +[LibraryClasses.ARM, LibraryClasses.AARCH64] + # + # It is not possible to prevent ARM compiler calls to generic intrinsic functions. + # This library provides the instrinsic functions generated by a given compiler. + # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. + # + NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf + + # + # Since software stack checking may be heuristically enabled by the compiler + # include BaseStackCheckLib unconditionally. + # + NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf + +[LibraryClasses.common.PEIM] + HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf + MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf + PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf + +[LibraryClasses.common.UEFI_APPLICATION] + UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf + +[PcdsFixedAtBuild] + gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0x17 + +[BuildOptions] + MSFT:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES + GCC:*_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 2649a735b249e54a4ddd7bd2b8d62bfe77e8d6da Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daud? Date: Thu, 2 Jan 2020 20:16:56 +0800 Subject: [PATCH 305/384] BaseTools/PatchCheck.py: Ignore CR and LF characters in subject length REF: https://bugzilla.tianocore.org/show_bug.cgi?id=113 Strip the trailing characters before checking the subject line is less than 72 characters. Fixes: e61406708c83f Cc: Liming Gao Cc: Jordan Justen Reviewed-by: Jordan Justen Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Scripts/PatchCheck.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 2a4e6f603e7..9668025798d 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -196,7 +196,7 @@ def check_overall_format(self): self.error('Empty commit message!') return - if count >= 1 and len(lines[0]) >= 72: + if count >= 1 and len(lines[0].rstrip()) >= 72: self.error('First line of commit message (subject line) ' + 'is too long.') From cf3ad972a2105ffa3795ddb1d9c149c7fc369f9b Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 8 Jan 2020 15:38:42 +0100 Subject: [PATCH 306/384] OvmfPkg: reorganize TPM2 support in DSC/FDF files Put the TPM2 related DXE modules together in the DSC, and add a TPM2 support header comment while at it. Signed-off-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek --- OvmfPkg/OvmfPkgIa32.dsc | 9 ++++++--- OvmfPkg/OvmfPkgIa32.fdf | 3 +++ OvmfPkg/OvmfPkgIa32X64.dsc | 9 ++++++--- OvmfPkg/OvmfPkgIa32X64.fdf | 3 +++ OvmfPkg/OvmfPkgX64.dsc | 9 ++++++--- OvmfPkg/OvmfPkgX64.fdf | 3 +++ 6 files changed, 27 insertions(+), 9 deletions(-) diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index 9a60eb8fe2b..f9e0b4b5bc5 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -632,9 +632,6 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } -!if $(TPM2_CONFIG_ENABLE) == TRUE - SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf -!endif !endif # @@ -902,6 +899,9 @@ } !endif + # + # TPM2 support + # !if $(TPM2_ENABLE) == TRUE SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf { @@ -914,4 +914,7 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } +!if $(TPM2_CONFIG_ENABLE) == TRUE + SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf +!endif !endif diff --git a/OvmfPkg/OvmfPkgIa32.fdf b/OvmfPkg/OvmfPkgIa32.fdf index 586bbff0858..63607551ed7 100644 --- a/OvmfPkg/OvmfPkgIa32.fdf +++ b/OvmfPkg/OvmfPkgIa32.fdf @@ -343,6 +343,9 @@ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf !endif +# +# TPM2 support +# !if $(TPM2_ENABLE) == TRUE INF SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf !if $(TPM2_CONFIG_ENABLE) == TRUE diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index 1d1480b50b0..ee83bbaa537 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -644,9 +644,6 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } -!if $(TPM2_CONFIG_ENABLE) == TRUE - SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf -!endif !endif [Components.X64] @@ -916,6 +913,9 @@ } !endif + # + # TPM2 support + # !if $(TPM2_ENABLE) == TRUE SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf { @@ -928,4 +928,7 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } +!if $(TPM2_CONFIG_ENABLE) == TRUE + SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf +!endif !endif diff --git a/OvmfPkg/OvmfPkgIa32X64.fdf b/OvmfPkg/OvmfPkgIa32X64.fdf index e49adc425fc..0488e5d95ff 100644 --- a/OvmfPkg/OvmfPkgIa32X64.fdf +++ b/OvmfPkg/OvmfPkgIa32X64.fdf @@ -350,6 +350,9 @@ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf !endif +# +# TPM2 support +# !if $(TPM2_ENABLE) == TRUE INF SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf !if $(TPM2_CONFIG_ENABLE) == TRUE diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index c287a436f8e..af40075e34b 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -643,9 +643,6 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } -!if $(TPM2_CONFIG_ENABLE) == TRUE - SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf -!endif !endif # @@ -914,6 +911,9 @@ } !endif + # + # TPM2 support + # !if $(TPM2_ENABLE) == TRUE SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf { @@ -926,4 +926,7 @@ NULL|SecurityPkg/Library/HashInstanceLibSha512/HashInstanceLibSha512.inf NULL|SecurityPkg/Library/HashInstanceLibSm3/HashInstanceLibSm3.inf } +!if $(TPM2_CONFIG_ENABLE) == TRUE + SecurityPkg/Tcg/Tcg2Config/Tcg2ConfigDxe.inf +!endif !endif diff --git a/OvmfPkg/OvmfPkgX64.fdf b/OvmfPkg/OvmfPkgX64.fdf index e49adc425fc..0488e5d95ff 100644 --- a/OvmfPkg/OvmfPkgX64.fdf +++ b/OvmfPkg/OvmfPkgX64.fdf @@ -350,6 +350,9 @@ INF MdeModulePkg/Universal/FaultTolerantWriteDxe/FaultTolerantWriteDxe.inf INF MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf !endif +# +# TPM2 support +# !if $(TPM2_ENABLE) == TRUE INF SecurityPkg/Tcg/Tcg2Dxe/Tcg2Dxe.inf !if $(TPM2_CONFIG_ENABLE) == TRUE From f55477fe2d62687ae0b91e3c5e68db2c22cbaf5c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Wed, 8 Jan 2020 15:38:43 +0100 Subject: [PATCH 307/384] OvmfPkg: use HII type PCDs for TPM2 config related variables The HII pages that are part of Tcg2ConfigDxe expect the following PCDs to be of dynamic HII type, so declare them as such. gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev Currently, the TPM2 ACPI table is not produced, since we do not incorporate the Tcg2Smm module, which implements the SMI based physical presence interface exposed to the OS. Signed-off-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek --- OvmfPkg/OvmfPkgIa32.dsc | 6 ++++++ OvmfPkg/OvmfPkgIa32X64.dsc | 6 ++++++ OvmfPkg/OvmfPkgX64.dsc | 6 ++++++ 3 files changed, 18 insertions(+) diff --git a/OvmfPkg/OvmfPkgIa32.dsc b/OvmfPkg/OvmfPkgIa32.dsc index f9e0b4b5bc5..1da6cc7f234 100644 --- a/OvmfPkg/OvmfPkgIa32.dsc +++ b/OvmfPkg/OvmfPkgIa32.dsc @@ -575,6 +575,12 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} !endif +[PcdsDynamicHii] +!if $(TPM2_ENABLE) == TRUE && $(TPM2_CONFIG_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS + gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS +!endif + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform. diff --git a/OvmfPkg/OvmfPkgIa32X64.dsc b/OvmfPkg/OvmfPkgIa32X64.dsc index ee83bbaa537..213e70345fb 100644 --- a/OvmfPkg/OvmfPkgIa32X64.dsc +++ b/OvmfPkg/OvmfPkgIa32X64.dsc @@ -587,6 +587,12 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} !endif +[PcdsDynamicHii] +!if $(TPM2_ENABLE) == TRUE && $(TPM2_CONFIG_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS + gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS +!endif + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform. diff --git a/OvmfPkg/OvmfPkgX64.dsc b/OvmfPkg/OvmfPkgX64.dsc index af40075e34b..4d0173dfd29 100644 --- a/OvmfPkg/OvmfPkgX64.dsc +++ b/OvmfPkg/OvmfPkgX64.dsc @@ -586,6 +586,12 @@ gEfiSecurityPkgTokenSpaceGuid.PcdTpmInstanceGuid|{0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} !endif +[PcdsDynamicHii] +!if $(TPM2_ENABLE) == TRUE && $(TPM2_CONFIG_ENABLE) == TRUE + gEfiSecurityPkgTokenSpaceGuid.PcdTcgPhysicalPresenceInterfaceVer|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x0|"1.3"|NV,BS + gEfiSecurityPkgTokenSpaceGuid.PcdTpm2AcpiTableRev|L"TCG2_VERSION"|gTcg2ConfigFormSetGuid|0x8|3|NV,BS +!endif + ################################################################################ # # Components Section - list of all EDK II Modules needed by this Platform. From 49a1aab21099af262ecb59a0fd4001eb5028ae68 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 11:15:54 -0800 Subject: [PATCH 308/384] Standardize all copyrights and headers. --- .../HostUnitTestCompilerPlugin/Readme.md | 6 +++++ .../HostUnitTestDscCompleteCheck.py | 2 +- MdePkg/Include/Library/UnitTestLib.h | 2 +- .../IA32/SafeIntLibUintnIntnUnitTests.c | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLibDxe.inf | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLibHost.inf | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLibPei.inf | 23 ++----------------- .../BaseSafeIntLib/TestBaseSafeIntLibSmm.inf | 23 ++----------------- .../TestBaseSafeIntLibUefiShell.inf | 23 ++----------------- .../X64/SafeIntLibUintnIntnUnitTests.c | 23 ++----------------- Readme-RFC.md | 6 +++++ .../UnitTestBootLibNull/UnitTestBootLibNull.c | 3 ++- .../UnitTestBootLibNull.inf | 3 ++- .../UnitTestBootLibUsbClass.c | 3 ++- .../UnitTestBootLibUsbClass.inf | 3 ++- .../Library/UnitTestLib/Assert.c | 3 ++- .../Library/UnitTestLib/Log.c | 3 ++- .../Library/UnitTestLib/UnitTestLib.inf | 3 ++- .../UnitTestPersistenceLibNull.c | 16 ++----------- .../UnitTestPersistenceLibNull.inf | 16 ++----------- .../UnitTestPersistenceLibSimpleFileSystem.c | 15 ++---------- ...UnitTestPersistenceLibSimpleFileSystem.inf | 15 ++---------- .../UnitTestResultReportLib.c | 3 ++- .../UnitTestResultReportLibConOut.c | 3 ++- .../UnitTestResultReportLibConOut.inf | 3 ++- .../UnitTestResultReportLibDebugLib.c | 3 ++- .../UnitTestResultReportLibDebugLib.inf | 3 ++- .../PrivateInclude/Library/UnitTestBootLib.h | 2 +- .../Library/UnitTestPersistenceLib.h | 2 +- .../Library/UnitTestResultReportLib.h | 2 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 2 +- UnitTestFrameworkPkg/ReadMe.md | 1 + .../SampleUnitTestApp/SampleUnitTestApp.c | 16 ++----------- .../SampleUnitTestApp/SampleUnitTestApp.inf | 3 ++- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 16 ++----------- .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 3 ++- .../SampleUnitTestSmm/SampleUnitTestSmm.c | 16 ++----------- .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 3 ++- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 3 ++- 41 files changed, 83 insertions(+), 307 deletions(-) diff --git a/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md b/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md index dac7c4fb858..f0def4c55c1 100644 --- a/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md +++ b/.pytool/Plugin/HostUnitTestCompilerPlugin/Readme.md @@ -16,3 +16,9 @@ The package relative path of the DSC file to build. ### DscPath Package relative path to the DSC file to build. + +## Copyright + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py index 182b42675b7..a0c7c269ef9 100644 --- a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py @@ -3,7 +3,7 @@ # This is a copy of DscCompleteCheck with different filtering logic. # It should be discussed if this should be one plugin # -# Copyright (c) Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent ## import logging diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 1d0cd644222..71af830d6af 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -2,7 +2,7 @@ Provides a unit test framework. This allows tests to focus on testing logic and the framework to focus on runnings, reporting, statistics, etc. - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c index e2f90dfeb25..045810263ac 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -2,28 +2,9 @@ IA32-specific functions for unit-testing INTN and UINTN functions in SafeIntLib. - Copyright (c) 2017, Microsoft Corporation + Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
- - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 082fb0518f0..997e67ea71f 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -1,28 +1,9 @@ /** @file UEFI OS based application for unit testing the SafeIntLib. - Copyright (c) 2017, Microsoft Corporation + Copyright (c) Microsoft Corporation.
Copyright (c) 2018, Intel Corporation. All rights reserved.
- - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index d4e946743ff..d97fa5aec86 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -1,28 +1,9 @@ /** @file UEFI OS based application for unit testing the SafeIntLib. - Copyright (c) 2017, Microsoft Corporation + Copyright (c) Microsoft Corporation.
Copyright (c) 2018, Intel Corporation. All rights reserved.
- - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf index b693ac7777f..172cacf2993 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf @@ -1,28 +1,9 @@ ## @file # DXE Driver that Unit Tests the SafeIntLib # -# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) Microsoft Corporation.
# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-License-Identifier: BSD-2-Clause-Patent ## [Defines] diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf index b72f329bc68..fa1fdd8f874 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf @@ -1,28 +1,9 @@ ## @file # Host OS based Application that Unit Tests the SafeIntLib # -# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) Microsoft Corporation.
# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-License-Identifier: BSD-2-Clause-Patent ## [Defines] diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf index aac2e41cb17..0c886bf9ca3 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf @@ -1,28 +1,9 @@ ## @file # PEIM that Unit Tests the SafeIntLib # -# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) Microsoft Corporation.
# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-License-Identifier: BSD-2-Clause-Patent ## [Defines] diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf index e21b2e5a452..b8c57d294e1 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf @@ -1,28 +1,9 @@ ## @file # SMM Driver that Unit Tests the SafeIntLib # -# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) Microsoft Corporation.
# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-License-Identifier: BSD-2-Clause-Patent ## [Defines] diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf index 12571ee13fc..06bb0b32642 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf @@ -1,28 +1,9 @@ ## @file # UEFI Shell based Application that Unit Tests the SafeIntLib # -# Copyright (c) 2017, Microsoft Corporation +# Copyright (c) Microsoft Corporation.
# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# -# All rights reserved. -# Redistribution and use in source and binary forms, with or without -# modification, are permitted provided that the following conditions are met: -# 1. Redistributions of source code must retain the above copyright notice, -# this list of conditions and the following disclaimer. -# 2. Redistributions in binary form must reproduce the above copyright notice, -# this list of conditions and the following disclaimer in the documentation -# and/or other materials provided with the distribution. -# -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND -# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. -# IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -# BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF -# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE -# OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF -# ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# SPDX-License-Identifier: BSD-2-Clause-Patent ## [Defines] diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c index d84f8eee171..d5a3beb1c3a 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -2,28 +2,9 @@ x64-specific functions for unit-testing INTN and UINTN functions in SafeIntLib. - Copyright (c) 2017, Microsoft Corporation + Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
- - All rights reserved. - Redistribution and use in source and binary forms, with or without - modification, are permitted provided that the following conditions are met: - 1. Redistributions of source code must retain the above copyright notice, - this list of conditions and the following disclaimer. - 2. Redistributions in binary form must reproduce the above copyright notice, - this list of conditions and the following disclaimer in the documentation - and/or other materials provided with the distribution. - - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND - ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. - IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, - INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, - BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, - DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF - LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE - OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF - ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/Readme-RFC.md b/Readme-RFC.md index 46021034d5e..54edb0298f1 100644 --- a/Readme-RFC.md +++ b/Readme-RFC.md @@ -79,3 +79,9 @@ Code/Test | Location `6)` Non-Host-Based (PEI/DXE/SMM/Shell) Tests for a functionality or feature | If the feature is in one package, should be located in the *Pkg/Test/[Shell|Dxe|Smm|Pei]Test directory.

(Or)

if the feature spans multiple packages, should be located in UefiTestPkg/Feature/Functional/[Shell|Dxe|Smm|Pei]Test

=============
* PEI Example: MP_SERVICE_PPI. Or check MTRR configuration in a notification function.
* SMM Example: a test in a protocol callback function. (It is different with the solution that SmmAgent+ShellApp)
* DXE Example: a test in a UEFI event call back to check SPI/SMRAM status.
* Shell Example: the SMM handler audit test has a shell-based app that interacts with an SMM handler to get information. The SMM paging audit test gathers information about both DXE and SMM. And the SMM paging functional test actually forces errors into SMM via a DXE driver.
=============

`7)` Host-Based Library Implementations | Host-Based Implementations of common libraries (eg. MemoryAllocationLibHost) should live in the same package that declares the library interface in its .DEC file in the `*Pkg/HostLibrary` directory. Should have 'Host' in the name. `8)` Host-Based Mocks and Stubs | Mock and Stub libraries should live in the `UefiHostTestPkg/Helpers` with either 'Mock' or 'Stub' in the library name. + +## Copyright + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c index 2e8be9418fc..d457c9223dc 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c @@ -1,7 +1,8 @@ /** NULL implementation for UnitTestBootLib to allow simple compliation - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf index 2e1a16a0a9f..a4a907b65b0 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.inf @@ -1,7 +1,8 @@ ## @file # NULL library for UnitTestBootUsb # -# Copyright (c) 2018 Microsoft Corporation. All rights reserved +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c index 242daf53d43..f070d1bd551 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -2,7 +2,8 @@ Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should work on all platforms - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index 2e9f1c0c767..ea69b43b20d 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -2,7 +2,8 @@ # Library to support booting to USB on the next boot # This instance uses the industry standard usb class boot option. # -# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index bdd3064ddc2..2447f6c91d5 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -1,7 +1,8 @@ /** Implement UnitTestLib assert services - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index a98be88bf44..4a494954541 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -1,7 +1,8 @@ /** Implemnet UnitTestLib log services - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf index 8fd168d22c0..0df2f8afec4 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf @@ -1,7 +1,8 @@ ## @file # Library to support Unit Testing from PEI, DXE, SMM, and UEFI Applications. # -# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index 299e4d99b49..a45cca0a6b6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -1,20 +1,8 @@ /** @file -- UnitTestNullPersistenceLib.c This is an instance of the Unit Test Persistence Lib that does nothing. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - THE POSSIBILITY OF SUCH DAMAGE. - - - Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf index 989d4bb5f77..737f9f44462 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -1,20 +1,8 @@ ## @file # This is an instance of the Unit Test Persistence Lib does nothing. # -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -# THE POSSIBILITY OF SUCH DAMAGE. -# -# -# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c index 039b86223b8..86dc0f28275 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c @@ -3,19 +3,8 @@ the filesystem that a test application is running from to save a serialized version of the internal test state in case the test needs to quit and restore. - THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" - AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE - IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE - LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF - THE POSSIBILITY OF SUCH DAMAGE. - - Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf index 31fb168e732..787048e1eda 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf @@ -5,19 +5,8 @@ # that a test application is running from to save a serialized version of the # internal test state in case the test needs to quit and restore. # -# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -# THE POSSIBILITY OF SUCH DAMAGE. -# -# Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c index 64ae67a4cdf..2ee89bdf36a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -2,7 +2,8 @@ Implement UnitTestResultReportLib doing plain txt out to console - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c index 6d37871516b..a511c9f573b 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c @@ -2,7 +2,8 @@ Implement UnitTestResultReportLib doing plain txt out to console - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf index 1dda101973c..1679c868c99 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf @@ -1,7 +1,8 @@ ## @file # Library to support printing out the unit test report to a UEFI console # -# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c index 3f7cd61052c..5981fc0f373 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c @@ -2,7 +2,8 @@ Implement UnitTestResultReportLib doing plain txt out to console - Copyright (c) Microsoft + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf index 86c352aa76a..b15f9ec1508 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf @@ -1,7 +1,8 @@ ## @file # Library to support printing out the unit test report using DEBUG() macros. # -# Copyright (c) 2016 Microsoft Corporation. All rights reserved +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h index 8cf151c5e70..5f7b97d908d 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h @@ -4,7 +4,7 @@ USB. Since boot managers are not all the same creating a lib to support platform customization will make porting to new code base/platform easier. - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h index 44e2b8484f8..8682a8b895d 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h @@ -3,7 +3,7 @@ restore unit test internal state, in case the test needs to pause and resume (eg. a reboot-based test). - Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h index abd6daa926a..0a75a1faa4c 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h @@ -2,7 +2,7 @@ Provides a unit test result report. This allows new result output formats to be easily customized. - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 90de1df4c81..4d510347b43 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -1,7 +1,7 @@ /** @file Provides the basic types and common elements of the unit test framework - Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+ Copyright (c) Microsoft Corporation.
Copyright (c) 2019, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 2d8b3c76551..c4244c5f89d 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -235,3 +235,4 @@ stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NO Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent + diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c index 6affa13d3a4..8ccf9804790 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c @@ -1,20 +1,8 @@ /** @file -- SampleUnitTestApp.c This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf index 0a9f864ceb8..16a7ff73c45 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf @@ -1,5 +1,6 @@ ## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent ## diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c index 45dda89b7e8..40e80c026bd 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c @@ -1,20 +1,8 @@ /** @file -- SampleUnitTestPeim.c This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf index 13c3c106df9..0f677f3df9b 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf @@ -1,5 +1,6 @@ ## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent ## diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c index d3005ed5f34..3b2c506b069 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c @@ -1,20 +1,8 @@ /** @file -- SampleUnitTestSmm.c This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" -AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE -IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE -ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE -LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR -CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF -SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS -INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN -CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) -ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF -THE POSSIBILITY OF SUCH DAMAGE. - - -Copyright (C) 2016 Microsoft Corporation. All Rights Reserved. + Copyright (c) Microsoft Corporation.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf index f134939678e..ccf65cd74f1 100644 --- a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf @@ -1,5 +1,6 @@ ## @file -## Copyright (c) 2016, Microsoft Corporation. All rights reserved.
+# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent ## diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index f6def29f356..db5ffa34068 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -4,7 +4,8 @@ # and library classes) and libraries instances, which are used to support Unit # Testing and Interface testing # -# Copyright (c) 2017, Microsoft Corporation. All rights reserved. +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent # ## From 589751111f0c60b4c32092e989c346e7f31f9099 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 12:08:14 -0800 Subject: [PATCH 309/384] Remove an unnecessary package dependency. --- .../UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf | 1 - .../UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf | 1 - .../UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf | 1 - .../UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf | 1 - .../Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf | 1 - 5 files changed, 5 deletions(-) diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf index 172cacf2993..7bfeeef4182 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf @@ -33,7 +33,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] UefiDriverEntryPoint diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf index fa1fdd8f874..1ff4074b06b 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf @@ -32,7 +32,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] BaseLib diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf index 0c886bf9ca3..a21aca18c13 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf @@ -33,7 +33,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] PeimEntryPoint diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf index b8c57d294e1..012d33c9e47 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf @@ -33,7 +33,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] UefiDriverEntryPoint diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf index 06bb0b32642..19e3148f7f8 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf @@ -33,7 +33,6 @@ [Packages] MdePkg/MdePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec [LibraryClasses] UefiApplicationEntryPoint From 3c1f52e565e295fe6185a50add913ff679a8755e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 12:08:22 -0800 Subject: [PATCH 310/384] Get back to CI parity. --- MdePkg/MdePkg.ci.yaml | 11 +++++++++-- UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml | 5 ++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index e827946fc0b..d565cac81f7 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -12,7 +12,7 @@ ## options defined ci/Plugin/HostUnitTestCompilerPlugin "HostUnitTestCompilerPlugin": { - "DscPath": "Test/MdePkgTest.dsc" + "DscPath": "Test/MdePkgHostTest.dsc" }, ## options defined ci/Plugin/CharEncodingCheck @@ -36,7 +36,14 @@ ## options defined ci/Plugin/DscCompleteCheck "DscCompleteCheck": { - "IgnoreInf": [""], + "IgnoreInf": [ + # TODO: Figure out what to do about these... + # Should they just move to the standard DSC? + "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf", + "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf", + "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf", + "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf", + ], "DscPath": "MdePkg.dsc" }, diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 1675b0fce68..8fc19da3085 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -30,7 +30,10 @@ "IgnoreInf": [ # Don't need to build these. # These are host-based only. - "UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf" + "UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf", + "UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf", + "UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf", + "UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf", ] }, "GuidCheck": { From a09d24abe8ed25ec69f82c2af46109b386573b85 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 14:29:56 -0800 Subject: [PATCH 311/384] Comment on all of UnitTestLib.h --- MdePkg/Include/Library/UnitTestLib.h | 325 ++++++++++++++++++++++++--- 1 file changed, 295 insertions(+), 30 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 71af830d6af..8151cab8c87 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -24,9 +24,24 @@ typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE* typedef VOID* UNIT_TEST_HANDLE; // Same as a UNIT_TEST* typedef VOID* UNIT_TEST_CONTEXT; -// -// Unit-Test Function pointer type. -// +/** + The prototype for a single UnitTest case function. + Funtions with this prototype are registered to be dispatched by the + UnitTest framework, and results are recorded as test Pass or Fail. + + @param[in] Framework A handle to the current running framework that dispatched the test. + Necessary for recording certain test events with the framework. + @param[in] Context [Optional] An optional paramter that enables: 1) test-case reuse with varied + parameters and 2) test-case re-entry for Target tests that need a reboot. + This parameter is a VOID* and it is the responsibility of the test + author to ensure that the contents are well understood by all test + cases that may consume it. + + + @retval UNIT_TEST_PASSED Test has completed and test case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test assertion has failed. + +**/ typedef UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_FUNCTION)( @@ -34,10 +49,20 @@ UNIT_TEST_STATUS UNIT_TEST_CONTEXT Context ); -// -// Unit-Test Prerequisite Function pointer type. -// NOTE: Should be the same as UnitTest. -// +/** + Unit-Test Prerequisite Function pointer type. + NOTE: Should be the same as UnitTest. + Funtions with this prototype are registered to be dispatched by the + UnitTest framework prior to a given test case. If this prereq function returns + UNIT_TEST_ERROR_PREREQ_NOT_MET, the test case will be skipped. + + @param[in] Framework Identical to UNIT_TEST_FUNCTION. + @param[in] Context Identical to UNIT_TEST_FUNCTION. + + @retval UNIT_TEST_PASSED Test case prerequisites are met. + @retval UNIT_TEST_ERROR_PREREQ_NOT_MET Test case should be skipped. + +**/ typedef UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_PREREQ)( @@ -45,9 +70,18 @@ UNIT_TEST_STATUS UNIT_TEST_CONTEXT Context ); -// -// Unit-Test Test Cleanup (after) function pointer type. -// +/** + Unit-Test Test Cleanup (after) function pointer type. + Funtions with this prototype are registered to be dispatched by the + UnitTest framework after a given test case. This will be called even if the Test + Case returns an error, but not if the prerequisite fails and the test is skipped. + + The purpose of this function is to clean up any global state or test data. + + @param[in] Framework Identical to UNIT_TEST_FUNCTION. + @param[in] Context Identical to UNIT_TEST_FUNCTION. + +**/ typedef VOID (EFIAPI *UNIT_TEST_CLEANUP)( @@ -55,18 +89,34 @@ VOID UNIT_TEST_CONTEXT Context ); -// -// Unit-Test Test Suite Setup (before) function pointer type. -// +/** + Unit-Test Test Suite Setup (before) function pointer type. + Funtions with this prototype are registered to be dispatched by the + UnitTest framework prior to running any of the test cases in a test suite. + It will only be run once at the beginning of the suite (not prior to each case). + + The purpose of this function is to set up any global state or test data. + + @param[in] Framework Identical to UNIT_TEST_FUNCTION. + +**/ typedef VOID (EFIAPI *UNIT_TEST_SUITE_SETUP)( UNIT_TEST_FRAMEWORK_HANDLE Framework ); -// -// Unit-Test Test Suite Teardown (after) function pointer type. -// +/** + Unit-Test Test Suite Teardown (after) function pointer type. + Funtions with this prototype are registered to be dispatched by the + UnitTest framework after= running all of the test cases in a test suite. + It will only be run once at the end of the suite. + + The purpose of this function is to clean up any global state or test data. + + @param[in] Framework Identical to UNIT_TEST_FUNCTION. + +**/ typedef VOID (EFIAPI *UNIT_TEST_SUITE_TEARDOWN)( @@ -77,17 +127,20 @@ VOID /// Unit-Test Library Functions /// -/* - Method to Initialize the Unit Test framework +/** + Method to Initialize the Unit Test framework. + This function registers the test name and also initializes the internal + state of the test framework to receive any new suites and tests. @param Framework - Unit test framework to be created. @param Title - String name of the framework. String is copied. @param ShortTitle - Short string name of the framework. String is copied. @param VersionString - Version string for the framework. String is copied. - @retval Success - Unit Test init. - @retval EFI_ERROR - Unit Tests init failed. -*/ + @retval Success + @retval EFI_ERROR() + +**/ EFI_STATUS EFIAPI InitUnitTestFramework ( @@ -97,8 +150,10 @@ InitUnitTestFramework ( IN CHAR8 *VersionString ); -/* - Creates Unit Test Suite in the Unit Test Framework +/** + Registers a Unit Test Suite in the Unit Test Framework + At least one test suite must be registered, because all test cases must be + within a unit test suite. @param Suite - Suite to create @param Framework - Framework to add suite to @@ -107,9 +162,10 @@ InitUnitTestFramework ( @param Sup - Setup function, runs before suite. @param Tdn - Teardown function, runs after suite. - @retval Success - Unit Test Suite was created. - @retval EFI_OUT_OF_RESOURCES - Unit Test Suite failed to be created. -*/ + @retval Success + @retval EFI_OUT_OF_RESOURCES + +**/ EFI_STATUS EFIAPI CreateUnitTestSuite ( @@ -121,7 +177,7 @@ CreateUnitTestSuite ( IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL ); -/* +/** Adds test case to Suite @param Suite - Suite to add test to. @@ -132,9 +188,10 @@ CreateUnitTestSuite ( @param CleanUp - Clean up function, runs after test. @param Context - Pointer to context. - @retval Success - Unit test was added. - @retval EFI_OUT_OF_RESOURCES - Unit test failed to be added. -*/ + @retval Success + @retval EFI_OUT_OF_RESOURCES + +**/ EFI_STATUS EFIAPI AddTestCase ( @@ -147,18 +204,61 @@ AddTestCase ( IN UNIT_TEST_CONTEXT Context OPTIONAL ); +/** + The primary driver of UnitTest execution. + + Once a test framework is initialized and all suites and test cases are registered, + this function will cause the test framework to dispatch all test cases in sequence + and record the results for reporting. + + @param[in] Framework + + @retval Success + @retval EFI_ERROR() + +**/ EFI_STATUS EFIAPI RunAllTestSuites( IN UNIT_TEST_SUITE_HANDLE Framework ); +/** + Cleanup a test framework. + + After tests are run, this will teardown the entire framework and free all + allocated data within. + + @param[in] Framework + + @retval Success + @retval EFI_ERROR() + +**/ EFI_STATUS EFIAPI FreeUnitTestFramework ( IN UNIT_TEST_SUITE_HANDLE Framework ); +/** + Leverages a framework-specific mechanism (see UnitTestPersistenceLib if you're a framework author) + to save the state of the executing framework along with any allocated data so that the test + may be resumed upon reentry. A test case should pass any needed context (which, to prevent an infinite + loop, should be at least the current execution count) which will be saved by the framework and + passed to the test case upon resume. + + Generally called from within a test case prior to quitting or rebooting. + + @param[in] Framework + @param[in] ContextToSave A buffer of test case-specific data to be saved along with framework + state. Will be passed as "Context" to the test case upon resume. + @param[in] ContextToSaveSize Size of the ContextToSave buffer. + + @retval Success + @retval EFI_ERROR() + +**/ EFI_STATUS EFIAPI SaveFrameworkState ( @@ -170,47 +270,133 @@ SaveFrameworkState ( /// /// Unit-Test Assertion Macros and Functions /// +/** + Test assertion macro that checks an expression against the framework assertion logic. + This macro uses the framework assertion logic to check an expression for "TRUE". If the + expression evaluates to TRUE, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param Expression Expression to be evaluated for TRUE. + +**/ #define UT_ASSERT_TRUE(Expression) \ if(!UnitTestAssertTrue (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check an expression for "FALSE". If the + expression evaluates to FALSE, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param Expression Expression to be evaluated for FALSE. + +**/ #define UT_ASSERT_FALSE(Expression) \ if(!UnitTestAssertFalse (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether two simple values are equal. + If the values are equal, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param ValueA, ValueB Values to be compared for equality. Will be compared as UINT64. + +**/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ if(!UnitTestAssertEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether two memory buffers are equal. + If the buffers are equal, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param ValueA, ValueB Pointers to the buffers for comparison. + @param Length Number of bytes to compare. + +**/ #define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ if(!UnitTestAssertMemEqual (Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether two simple values are non-equal. + If the values are non-equal, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param ValueA, ValueB Values to be compared for inequality. Will be compared as UINT64. + +**/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ if(!UnitTestAssertNotEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether an EFI_STATUS value is !EFI_ERROR(). + If the status is !EFI_ERROR(), execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param Status Status to be checked. + +**/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ if(!UnitTestAssertNotEfiError (Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether two EFI_STATUS values are equal. + If the values are equal, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param Status, Expected Values to be compared for equality. + +**/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ if(!UnitTestAssertStatusEqual (Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Test assertion macro that checks an expression against the framework assertion logic. + + This macro uses the framework assertion logic to check whether a pointer is not NULL. + If the pointer is not NULL, execution will continue. Otherwise, the test case + will immediately return UNIT_TEST_ERROR_TEST_FAILED. + + @param Pointer Pointer to be checked. + +**/ #define UT_ASSERT_NOT_NULL(Pointer) \ if(!UnitTestAssertNotNull (Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertTrue ( @@ -222,6 +408,12 @@ UnitTestAssertTrue ( IN CONST CHAR8 *Description ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertFalse ( @@ -233,6 +425,12 @@ UnitTestAssertFalse ( IN CONST CHAR8 *Description ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertNotEfiError ( @@ -244,6 +442,12 @@ UnitTestAssertNotEfiError ( IN CONST CHAR8 *Description ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertEqual ( @@ -257,6 +461,12 @@ UnitTestAssertEqual ( IN CONST CHAR8 *DescriptionB ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertMemEqual ( @@ -271,6 +481,12 @@ UnitTestAssertMemEqual ( IN CONST CHAR8 *DescriptionB ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertNotEqual ( @@ -284,6 +500,12 @@ UnitTestAssertNotEqual ( IN CONST CHAR8 *DescriptionB ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertStatusEqual ( @@ -296,6 +518,12 @@ UnitTestAssertStatusEqual ( IN CONST CHAR8 *Description ); +/** + Helper function for the test assertion macros. + Please call via the public macro. + Do not call directly. + +**/ BOOLEAN EFIAPI UnitTestAssertNotNull ( @@ -310,19 +538,56 @@ UnitTestAssertNotNull ( /// /// Unit-Test Logging Macros and Functions /// +/** + Test logging macro that records an ERROR message in the test framework log. + Record will be associated with this test case during reporting. + + @param Format Standard C formatting string. + @param ... Print args. +**/ #define UT_LOG_ERROR(Format, ...) \ UnitTestLog (Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); +/** + Test logging macro that records a WARNING message in the test framework log. + Record will be associated with this test case during reporting. + + @param Format Standard C formatting string. + @param ... Print args. + +**/ #define UT_LOG_WARNING(Format, ...) \ UnitTestLog (Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); +/** + Test logging macro that records an INFO message in the test framework log. + Record will be associated with this test case during reporting. + + @param Format Standard C formatting string. + @param ... Print args. + +**/ #define UT_LOG_INFO(Format, ...) \ UnitTestLog (Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); +/** + Test logging macro that records a VERBOSE message in the test framework log. + Record will be associated with this test case during reporting. + + @param Format Standard C formatting string. + @param ... Print args. + +**/ #define UT_LOG_VERBOSE(Format, ...) \ UnitTestLog (Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); +/** + Helper function for the test logging macros. + Please call via the public macros. + Do not call directly. + +**/ VOID EFIAPI UnitTestLog ( From 46331439caaad58ee2b8d624bb07f656e1f34932 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 14:37:17 -0800 Subject: [PATCH 312/384] Revert the ignore for the new Test examples and drop into the main package DSC. --- MdePkg/MdePkg.ci.yaml | 9 +-------- MdePkg/MdePkg.dsc | 13 +++++++++++++ MdePkg/Test/MdePkgTargetTest.dsc | 30 ------------------------------ 3 files changed, 14 insertions(+), 38 deletions(-) delete mode 100644 MdePkg/Test/MdePkgTargetTest.dsc diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index d565cac81f7..d214e5e902f 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -36,14 +36,7 @@ ## options defined ci/Plugin/DscCompleteCheck "DscCompleteCheck": { - "IgnoreInf": [ - # TODO: Figure out what to do about these... - # Should they just move to the standard DSC? - "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf", - "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf", - "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf", - "MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf", - ], + "IgnoreInf": [""], "DscPath": "MdePkg.dsc" }, diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index 0aeafaaacca..f8751764977 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -18,6 +18,8 @@ BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc + [PcdsFeatureFlag] gEfiMdePkgTokenSpaceGuid.PcdUgaConsumeSupport|TRUE @@ -26,6 +28,9 @@ gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0x80000000 gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress|0xE0000000 +[LibraryClasses] + SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf + [Components] MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf @@ -115,6 +120,14 @@ MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf + # + # Build PEIM, DXE_DRIVER, SMM_DRIVER, UEFI Shell components that test SafeIntLib + # + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf + MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf + [Components.IA32, Components.X64] MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsicSev.inf diff --git a/MdePkg/Test/MdePkgTargetTest.dsc b/MdePkg/Test/MdePkgTargetTest.dsc deleted file mode 100644 index ddabe8c602e..00000000000 --- a/MdePkg/Test/MdePkgTargetTest.dsc +++ /dev/null @@ -1,30 +0,0 @@ -## @file -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - PLATFORM_NAME = MdePkgTargetTest - PLATFORM_GUID = F79ED988-CA41-4D1D-A71B-C4E257695E15 - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/MdePkg/TargetTest - SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT - -!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc - -[LibraryClasses] - SafeIntLib|MdePkg/Library/BaseSafeIntLib/BaseSafeIntLib.inf - -[Components] - # - # Build PEIM, DXE_DRIVER, SMM_DRIVER, UEFI Shell components that test SafeIntLib - # - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf - MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf From d7f039f8cdede8a2a3d8031338702a52c6d17523 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 15:26:24 -0800 Subject: [PATCH 313/384] Clean up the UnitTestFrameworkPkg.dsc file and move the Samples into the Test directory. --- .../SampleUnitTestApp/SampleUnitTestApp.c | 0 .../SampleUnitTestApp/SampleUnitTestApp.inf | 0 .../SampleUnitTestPeim/SampleUnitTestPeim.c | 0 .../SampleUnitTestPeim/SampleUnitTestPeim.inf | 0 .../SampleUnitTestSmm/SampleUnitTestSmm.c | 0 .../SampleUnitTestSmm/SampleUnitTestSmm.inf | 0 UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 156 +----------------- 7 files changed, 5 insertions(+), 151 deletions(-) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestApp/SampleUnitTestApp.c (100%) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestApp/SampleUnitTestApp.inf (100%) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c (100%) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf (100%) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c (100%) rename UnitTestFrameworkPkg/{ => Test/UnitTest}/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf (100%) diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.c similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.c rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.c diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c diff --git a/UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf similarity index 100% rename from UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 4ca2e092396..3e6a8787c29 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -17,154 +17,7 @@ BUILD_TARGETS = DEBUG|RELEASE|NOOPT SKUID_IDENTIFIER = DEFAULT -################################################################################################### -# -# Components Section - list of the modules and components that will be processed by compilation -# tools and the EDK II tools to generate PE32/PE32+/Coff image files. -# -# Note: The EDK II DSC file is not used to specify how compiled binary images get placed -# into firmware volume images. This section is just a list of modules to compile from -# source into UEFI-compliant binaries. -# It is the FDF file that contains information on combining binary files into firmware -# volume images, whose concept is beyond UEFI and is described in PI specification. -# Binary modules do not need to be listed in this section, as they should be -# specified in the FDF file. For example: Shell binary (Shell_Full.efi), FAT binary (Fat.efi), -# Logo (Logo.bmp), and etc. -# There may also be modules listed in this section that are not required in the FDF file, -# When a module listed here is excluded from FDF file, then UEFI-compliant binary will be -# generated for it, but the binary will not be put into any firmware volume. -# -################################################################################################### - -[LibraryClasses] - # - # Entry point - # - PeiCoreEntryPoint|MdePkg/Library/PeiCoreEntryPoint/PeiCoreEntryPoint.inf - PeimEntryPoint|MdePkg/Library/PeimEntryPoint/PeimEntryPoint.inf - DxeCoreEntryPoint|MdePkg/Library/DxeCoreEntryPoint/DxeCoreEntryPoint.inf - UefiDriverEntryPoint|MdePkg/Library/UefiDriverEntryPoint/UefiDriverEntryPoint.inf - UefiApplicationEntryPoint|MdePkg/Library/UefiApplicationEntryPoint/UefiApplicationEntryPoint.inf - # - # Basic - # - BaseLib|MdePkg/Library/BaseLib/BaseLib.inf - BaseMemoryLib|MdePkg/Library/BaseMemoryLib/BaseMemoryLib.inf - SynchronizationLib|MdePkg/Library/BaseSynchronizationLib/BaseSynchronizationLib.inf - PrintLib|MdePkg/Library/BasePrintLib/BasePrintLib.inf - IoLib|MdePkg/Library/BaseIoLibIntrinsic/BaseIoLibIntrinsic.inf - PciLib|MdePkg/Library/BasePciLibCf8/BasePciLibCf8.inf - PciCf8Lib|MdePkg/Library/BasePciCf8Lib/BasePciCf8Lib.inf - PciSegmentLib|MdePkg/Library/BasePciSegmentLibPci/BasePciSegmentLibPci.inf - CacheMaintenanceLib|MdePkg/Library/BaseCacheMaintenanceLib/BaseCacheMaintenanceLib.inf - PeCoffLib|MdePkg/Library/BasePeCoffLib/BasePeCoffLib.inf - PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf - SortLib|MdeModulePkg/Library/BaseSortLib/BaseSortLib.inf - # - # UEFI & PI - # - UefiBootServicesTableLib|MdePkg/Library/UefiBootServicesTableLib/UefiBootServicesTableLib.inf - UefiRuntimeServicesTableLib|MdePkg/Library/UefiRuntimeServicesTableLib/UefiRuntimeServicesTableLib.inf - UefiRuntimeLib|MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf - UefiLib|MdePkg/Library/UefiLib/UefiLib.inf - UefiHiiServicesLib|MdeModulePkg/Library/UefiHiiServicesLib/UefiHiiServicesLib.inf - HiiLib|MdeModulePkg/Library/UefiHiiLib/UefiHiiLib.inf - DevicePathLib|MdePkg/Library/UefiDevicePathLib/UefiDevicePathLib.inf - UefiDecompressLib|MdePkg/Library/BaseUefiDecompressLib/BaseUefiDecompressLib.inf - PeiServicesTablePointerLib|MdePkg/Library/PeiServicesTablePointerLib/PeiServicesTablePointerLib.inf - PeiServicesLib|MdePkg/Library/PeiServicesLib/PeiServicesLib.inf - DxeServicesLib|MdePkg/Library/DxeServicesLib/DxeServicesLib.inf - DxeServicesTableLib|MdePkg/Library/DxeServicesTableLib/DxeServicesTableLib.inf - SmmServicesTableLib|MdePkg/Library/SmmServicesTableLib/SmmServicesTableLib.inf - UefiBootManagerLib|MdeModulePkg/Library/UefiBootManagerLib/UefiBootManagerLib.inf - # - # Generic Modules - # - UefiUsbLib|MdePkg/Library/UefiUsbLib/UefiUsbLib.inf - UefiScsiLib|MdePkg/Library/UefiScsiLib/UefiScsiLib.inf - SecurityManagementLib|MdeModulePkg/Library/DxeSecurityManagementLib/DxeSecurityManagementLib.inf - TimerLib|MdePkg/Library/BaseTimerLibNullTemplate/BaseTimerLibNullTemplate.inf - SerialPortLib|MdePkg/Library/BaseSerialPortLibNull/BaseSerialPortLibNull.inf - CapsuleLib|MdeModulePkg/Library/DxeCapsuleLibNull/DxeCapsuleLibNull.inf - PcdLib|MdePkg/Library/BasePcdLibNull/BasePcdLibNull.inf - CustomizedDisplayLib|MdeModulePkg/Library/CustomizedDisplayLib/CustomizedDisplayLib.inf - FrameBufferBltLib|MdeModulePkg/Library/FrameBufferBltLib/FrameBufferBltLib.inf - # - # Misc - # - DebugLib|MdeModulePkg/Library/PeiDxeDebugLibReportStatusCode/PeiDxeDebugLibReportStatusCode.inf - DebugPrintErrorLevelLib|MdePkg/Library/BaseDebugPrintErrorLevelLib/BaseDebugPrintErrorLevelLib.inf - ReportStatusCodeLib|MdePkg/Library/BaseReportStatusCodeLibNull/BaseReportStatusCodeLibNull.inf - OemHookStatusCodeLib|MdeModulePkg/Library/OemHookStatusCodeLibNull/OemHookStatusCodeLibNull.inf - PeCoffExtraActionLib|MdePkg/Library/BasePeCoffExtraActionLibNull/BasePeCoffExtraActionLibNull.inf - PerformanceLib|MdePkg/Library/BasePerformanceLibNull/BasePerformanceLibNull.inf - DebugAgentLib|MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.inf - PlatformHookLib|MdeModulePkg/Library/BasePlatformHookLibNull/BasePlatformHookLibNull.inf - ResetSystemLib|MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.inf - SmbusLib|MdePkg/Library/DxeSmbusLib/DxeSmbusLib.inf - S3BootScriptLib|MdeModulePkg/Library/PiDxeS3BootScriptLib/DxeS3BootScriptLib.inf - CpuExceptionHandlerLib|MdeModulePkg/Library/CpuExceptionHandlerLibNull/CpuExceptionHandlerLibNull.inf - PlatformBootManagerLib|MdeModulePkg/Library/PlatformBootManagerLibNull/PlatformBootManagerLibNull.inf - PciHostBridgeLib|MdeModulePkg/Library/PciHostBridgeLibNull/PciHostBridgeLibNull.inf - TpmMeasurementLib|MdeModulePkg/Library/TpmMeasurementLibNull/TpmMeasurementLibNull.inf - AuthVariableLib|MdeModulePkg/Library/AuthVariableLibNull/AuthVariableLibNull.inf - VarCheckLib|MdeModulePkg/Library/VarCheckLib/VarCheckLib.inf - FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf - FileHandleLib|MdePkg/Library/UefiFileHandleLib/UefiFileHandleLib.inf - - # - # Shell - # - ShellLib|ShellPkg/Library/UefiShellLib/UefiShellLib.inf - ShellCommandLib|ShellPkg/Library/UefiShellCommandLib/UefiShellCommandLib.inf - ShellCEntryLib|ShellPkg/Library/UefiShellCEntryLib/UefiShellCEntryLib.inf - HandleParsingLib|ShellPkg/Library/UefiHandleParsingLib/UefiHandleParsingLib.inf - -[LibraryClasses.common.PEIM] - HobLib|MdePkg/Library/PeiHobLib/PeiHobLib.inf - MemoryAllocationLib|MdePkg/Library/PeiMemoryAllocationLib/PeiMemoryAllocationLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/PeiReportStatusCodeLib/PeiReportStatusCodeLib.inf - -[LibraryClasses.common.DXE_DRIVER, LibraryClasses.common.UEFI_APPLICATION] - HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf - MemoryAllocationLib|MdePkg/Library/UefiMemoryAllocationLib/UefiMemoryAllocationLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/DxeReportStatusCodeLib/DxeReportStatusCodeLib.inf - -[LibraryClasses.common.DXE_SMM_DRIVER] - HobLib|MdePkg/Library/DxeHobLib/DxeHobLib.inf - ReportStatusCodeLib|MdeModulePkg/Library/SmmReportStatusCodeLib/SmmReportStatusCodeLib.inf - MemoryAllocationLib|MdePkg/Library/SmmMemoryAllocationLib/SmmMemoryAllocationLib.inf - -[LibraryClasses.ARM, LibraryClasses.AARCH64] - # - # It is not possible to prevent ARM compiler calls to generic intrinsic functions. - # This library provides the instrinsic functions generated by a given compiler. - # [LibraryClasses.ARM] and NULL mean link this library into all ARM images. - # - NULL|ArmPkg/Library/CompilerIntrinsicsLib/CompilerIntrinsicsLib.inf - - # - # Since software stack checking may be heuristically enabled by the compiler - # include BaseStackCheckLib unconditionally. - # - NULL|MdePkg/Library/BaseStackCheckLib/BaseStackCheckLib.inf - -# -# UnitTestFrameworkPkg -# -[LibraryClasses] - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf - UnitTestPersistenceLib|UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf - -[LibraryClasses.common.UEFI_APPLICATION] - UnitTestResultReportLib|UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf - -[LibraryClasses.common.HOST_APPLICATION] - CmockaLib|UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf - UnitTestLib|UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf - DebugLib|UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf - MemoryAllocationLib|UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc [Components] UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf @@ -174,9 +27,10 @@ UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestApp/SampleUnitTestApp.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf - UnitTestFrameworkPkg/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf + + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 324c255c7ec00317da048c362e20ec208732cf5d Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 15:41:01 -0800 Subject: [PATCH 314/384] Combine all existing samples into a single source file. --- .../SampleUnitTest.c} | 54 +++-- .../SampleUnitTestPei.inf} | 13 +- .../SampleUnitTestSmm.inf | 11 +- .../SampleUnitTestUefiShell.inf} | 12 +- .../SampleUnitTestPeim/SampleUnitTestPeim.c | 199 ------------------ .../SampleUnitTestSmm/SampleUnitTestSmm.c | 197 ----------------- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 6 +- 7 files changed, 61 insertions(+), 431 deletions(-) rename UnitTestFrameworkPkg/Test/UnitTest/Sample/{SampleUnitTestApp/SampleUnitTestApp.c => SampleUnitTest/SampleUnitTest.c} (85%) rename UnitTestFrameworkPkg/Test/UnitTest/Sample/{SampleUnitTestPeim/SampleUnitTestPeim.inf => SampleUnitTest/SampleUnitTestPei.inf} (69%) rename UnitTestFrameworkPkg/Test/UnitTest/Sample/{SampleUnitTestSmm => SampleUnitTest}/SampleUnitTestSmm.inf (77%) rename UnitTestFrameworkPkg/Test/UnitTest/Sample/{SampleUnitTestApp/SampleUnitTestApp.inf => SampleUnitTest/SampleUnitTestUefiShell.inf} (67%) delete mode 100644 UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c delete mode 100644 UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c similarity index 85% rename from UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.c rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 8ccf9804790..300e04ad454 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -5,16 +5,16 @@ This is a sample EFI Shell application to demostrate the usage of the Unit Test SPDX-License-Identifier: BSD-2-Clause-Patent **/ +#include #include #include -#include #include - #include +#include -#define UNIT_TEST_APP_NAME "Sample Unit Test Library Application" -#define UNIT_TEST_APP_VERSION "0.1" +#define UNIT_TEST_NAME "Sample Unit Test" +#define UNIT_TEST_VERSION "0.1" BOOLEAN mSampleGlobalTestBoolean = FALSE; @@ -126,32 +126,25 @@ GlobalPointerShouldBeChangeable ( /** - SampleUnitTestApp - - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. + UefiTestMain **/ EFI_STATUS EFIAPI -SampleUnitTestApp ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable +UefiTestMain ( + VOID ) { EFI_STATUS Status; UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION )); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); + Status = InitUnitTestFramework( &Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION ); if (EFI_ERROR( Status )) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); @@ -195,4 +188,33 @@ SampleUnitTestApp ( } return Status; +} // UefiTestMain() + +EFI_STATUS +EFIAPI +PeiEntryPoint ( + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices + ) +{ + return UefiTestMain (); +} + +EFI_STATUS +EFIAPI +DxeEntryPoint ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return UefiTestMain (); +} + +int +main ( + int argc, + char *argv[] + ) +{ + return UefiTestMain (); } diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf similarity index 69% rename from UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf index 0f677f3df9b..84050380a4f 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf @@ -1,4 +1,6 @@ ## @file +# Sample UnitTest built for execution in PEI. +# # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -6,31 +8,30 @@ [Defines] INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestPeim + BASE_NAME = SampleUnitTestPei FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 MODULE_TYPE = PEIM VERSION_STRING = 1.0 - ENTRY_POINT = SampleUnitTestPeim + ENTRY_POINT = PeiEntryPoint # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] - SampleUnitTestPeim.c + SampleUnitTest.c [Packages] MdePkg/MdePkg.dec [LibraryClasses] - BaseLib PeimEntryPoint + BaseLib DebugLib UnitTestLib PrintLib [Depex] gEfiPeiMemoryDiscoveredPpiGuid - diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf similarity index 77% rename from UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf index ccf65cd74f1..56e109236eb 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf @@ -1,4 +1,6 @@ ## @file +# Sample UnitTest built for execution in SMM. +# # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -11,27 +13,26 @@ MODULE_TYPE = DXE_SMM_DRIVER VERSION_STRING = 1.0 PI_SPECIFICATION_VERSION = 0x0001000A - ENTRY_POINT = SampleUnitTestSmm + ENTRY_POINT = DxeEntryPoint # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] - SampleUnitTestSmm.c + SampleUnitTest.c [Packages] MdePkg/MdePkg.dec [LibraryClasses] - BaseLib UefiDriverEntryPoint + BaseLib DebugLib UnitTestLib PrintLib [Depex] gEfiSmmCpuProtocolGuid - diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf similarity index 67% rename from UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf rename to UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf index 16a7ff73c45..1691a3498f5 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf @@ -1,4 +1,6 @@ ## @file +# Sample UnitTest built for execution in UEFI Shell. +# # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -6,27 +8,27 @@ [Defines] INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestApp + BASE_NAME = SampleUnitTestUefiShell FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B MODULE_TYPE = UEFI_APPLICATION VERSION_STRING = 1.0 - ENTRY_POINT = SampleUnitTestApp + ENTRY_POINT = DxeEntryPoint # # The following information is for reference only and not required by the build tools. # -# VALID_ARCHITECTURES = IA32 X64 IPF EBC +# VALID_ARCHITECTURES = IA32 X64 # [Sources] - SampleUnitTestApp.c + SampleUnitTest.c [Packages] MdePkg/MdePkg.dec [LibraryClasses] - BaseLib UefiApplicationEntryPoint + BaseLib DebugLib UnitTestLib PrintLib diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c deleted file mode 100644 index 40e80c026bd..00000000000 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.c +++ /dev/null @@ -1,199 +0,0 @@ -/** @file -- SampleUnitTestPeim.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. - - Copyright (c) Microsoft Corporation.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -#include - - -#define UNIT_TEST_PEIM_NAME "Sample Unit Test Library PEIM" -#define UNIT_TEST_PEIM_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Anything you think might be helpful that isn't a test itself. -// - -UNIT_TEST_STATUS -EFIAPI -MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); - return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() - - -VOID -EFIAPI -ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = NULL; - return; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - - -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - - -UNIT_TEST_STATUS -EFIAPI -GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); - - mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); - - return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - - -UNIT_TEST_STATUS -EFIAPI -GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); - return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -/** - SampleUnitTestPeim - - @param FileHandle Handle of the file being invoked. Type - EFI_PEI_FILE_HANDLE is defined in - FfsFindNextFile(). - @param PeiServices Describes the list of possible PEI Services. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. - -**/ -EFI_STATUS -EFIAPI -SampleUnitTestPeim ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_PEIM_NAME, UNIT_TEST_PEIM_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_PEIM_NAME, gEfiCallerBaseName, UNIT_TEST_PEIM_VERSION ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the SimpleMathTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); - - // - // Populate the GlobalVarTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); - } - - return Status; -} diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c deleted file mode 100644 index 3b2c506b069..00000000000 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.c +++ /dev/null @@ -1,197 +0,0 @@ -/** @file -- SampleUnitTestSmm.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. - - Copyright (c) Microsoft Corporation.
- SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include - -#include - - -#define UNIT_TEST_SMM_NAME "Sample Unit Test Library SMM" -#define UNIT_TEST_SMM_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - - -// -// Anything you think might be helpful that isn't a test itself. -// - -UNIT_TEST_STATUS -EFIAPI -MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); - return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() - - -VOID -EFIAPI -ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = NULL; - return; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - - -UNIT_TEST_STATUS -EFIAPI -OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - UINTN A, B, C; - - A = 1; - B = 1; - C = A + B; - - UT_ASSERT_EQUAL(C, 2); - return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - - -UNIT_TEST_STATUS -EFIAPI -GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); - - mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); - - return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - - -UNIT_TEST_STATUS -EFIAPI -GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID *)-1)); - return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -/** - SampleUnitTestSmm - - @param[in] ImageHandle The firmware allocated handle for the EFI image. - @param[in] SystemTable A pointer to the EFI System Table. - - @retval EFI_SUCCESS The entry point executed successfully. - @retval other Some error occured when executing this entry point. - -**/ -EFI_STATUS -EFIAPI -SampleUnitTestSmm ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_SMM_NAME, UNIT_TEST_SMM_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_SMM_NAME, gEfiCallerBaseName, UNIT_TEST_SMM_VERSION ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the SimpleMathTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); - - // - // Populate the GlobalVarTests Unit Test Suite. - // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); - } - - return Status; -} diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 3e6a8787c29..4729e568f64 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -28,9 +28,9 @@ UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf - UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestApp/SampleUnitTestApp.inf - UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestPeim/SampleUnitTestPeim.inf - UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTestSmm/SampleUnitTestSmm.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf [BuildOptions] *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES From 089f090d10f99ee7186d1d57b8b35a84a2b5c855 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 15:44:50 -0800 Subject: [PATCH 315/384] Add a DXE instance of the SampleTest. --- .../SampleUnitTest/SampleUnitTestDxe.inf | 37 +++++++++++++++++++ UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 1 + 2 files changed, 38 insertions(+) create mode 100644 UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf new file mode 100644 index 00000000000..5d4d2991852 --- /dev/null +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf @@ -0,0 +1,37 @@ +## @file +# Sample UnitTest built for execution in DXE. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestDxe + FILE_GUID = 96BB18BD-FF2B-4B51-B683-0DC9A4BF12CF + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SampleUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + BaseLib + DebugLib + UnitTestLib + PrintLib + +[Depex] + TRUE diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index 4729e568f64..e3e42c2acf4 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -28,6 +28,7 @@ UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf From e18792566c7fb1335e705c3b19334db9271eac90 Mon Sep 17 00:00:00 2001 From: Eric Dong Date: Thu, 9 Jan 2020 13:21:36 +0800 Subject: [PATCH 316/384] UefiCpuPkg/PiSmmCpuDxeSmm: Add missed comments for parameter. This issue caused by below change: SHA-1: b948a496150f4ae4f656c0f0ab672608723c80e6 * UefiCpuPkg/PiSmmCpuDxeSmm: Pre-allocate PROCEDURE_TOKEN buffer REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2388 Reviewed-by: Ray Ni Acked-by: Laszlo Ersek Signed-off-by: Eric Dong --- UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c | 2 ++ 1 file changed, 2 insertions(+) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c index 35a6996ba34..c285a70ebb9 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/MpService.c @@ -1142,6 +1142,8 @@ FindFirstFreeToken ( If no free token, allocate new tokens then return the free one. + @param RunningApsCount The Running Aps count for this token. + @retval return the first free PROCEDURE_TOKEN. **/ From df851da3ceff5b6bcf5e12616f6af60812aab483 Mon Sep 17 00:00:00 2001 From: "Vitaly Cheptsov via Groups.Io" Date: Tue, 7 Jan 2020 18:50:32 +0800 Subject: [PATCH 317/384] MdePkg: Do not use CreateEventEx unless required REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2446 There are many firmwares in the wild not supporting CreateEventEx, including devices less than 5 years old. Signed-off-by: Vitaly Cheptsov Reviewed-by: Liming Gao --- MdePkg/Library/DxeRuntimeDebugLibSerialPort/DebugLib.c | 3 +-- .../DxeRuntimeDebugLibSerialPort.inf | 3 --- .../DxeRuntimePciExpressLib.inf | 4 ---- MdePkg/Library/DxeRuntimePciExpressLib/PciExpressLib.c | 5 ++--- .../PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLib.c | 5 ++--- .../DxeRuntimePciSegmentLibSegmentInfo.inf | 3 --- .../Library/UefiDebugLibConOut/DebugLibConstructor.c | 5 ++--- .../Library/UefiDebugLibConOut/UefiDebugLibConOut.inf | 3 --- .../DebugLibConstructor.c | 5 ++--- .../UefiDebugLibDebugPortProtocol.inf | 3 --- .../Library/UefiDebugLibStdErr/DebugLibConstructor.c | 5 ++--- .../Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf | 3 --- MdePkg/Library/UefiRuntimeLib/RuntimeLib.c | 10 ++++------ MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf | 5 ----- 14 files changed, 15 insertions(+), 47 deletions(-) diff --git a/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DebugLib.c b/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DebugLib.c index 862c6bff09f..cc79843b1cd 100644 --- a/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DebugLib.c +++ b/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DebugLib.c @@ -77,9 +77,8 @@ DxeRuntimeDebugLibSerialPortConstructor ( return Status; } - return SystemTable->BootServices->CreateEventEx (EVT_NOTIFY_SIGNAL, + return SystemTable->BootServices->CreateEvent (EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesEvent, NULL, - &gEfiEventExitBootServicesGuid, &mEfiExitBootServicesEvent); } diff --git a/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf b/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf index 655c1c14c17..31d169ad7c0 100644 --- a/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf +++ b/MdePkg/Library/DxeRuntimeDebugLibSerialPort/DxeRuntimeDebugLibSerialPort.inf @@ -41,9 +41,6 @@ PrintLib SerialPortLib -[Guids] - gEfiEventExitBootServicesGuid ## CONSUMES ## Event - [Pcd] gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue ## SOMETIMES_CONSUMES gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask ## CONSUMES diff --git a/MdePkg/Library/DxeRuntimePciExpressLib/DxeRuntimePciExpressLib.inf b/MdePkg/Library/DxeRuntimePciExpressLib/DxeRuntimePciExpressLib.inf index 45bfe9dc6fc..8d2ba1d1873 100644 --- a/MdePkg/Library/DxeRuntimePciExpressLib/DxeRuntimePciExpressLib.inf +++ b/MdePkg/Library/DxeRuntimePciExpressLib/DxeRuntimePciExpressLib.inf @@ -47,7 +47,3 @@ [Pcd] gEfiMdePkgTokenSpaceGuid.PcdPciExpressBaseAddress ## CONSUMES - -[Guids] - gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event - diff --git a/MdePkg/Library/DxeRuntimePciExpressLib/PciExpressLib.c b/MdePkg/Library/DxeRuntimePciExpressLib/PciExpressLib.c index 6e784763be7..7e5852e641d 100644 --- a/MdePkg/Library/DxeRuntimePciExpressLib/PciExpressLib.c +++ b/MdePkg/Library/DxeRuntimePciExpressLib/PciExpressLib.c @@ -124,12 +124,11 @@ DxeRuntimePciExpressLibConstructor ( // // Register SetVirtualAddressMap () notify function // - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + Status = gBS->CreateEvent ( + EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE, TPL_NOTIFY, DxeRuntimePciExpressLibVirtualNotify, NULL, - &gEfiEventVirtualAddressChangeGuid, &mDxeRuntimePciExpressLibVirtualNotifyEvent ); ASSERT_EFI_ERROR (Status); diff --git a/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLib.c b/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLib.c index 2f503ecffe0..b0dbdec0cf8 100644 --- a/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLib.c +++ b/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLib.c @@ -109,12 +109,11 @@ DxeRuntimePciSegmentLibConstructor ( // // Register SetVirtualAddressMap () notify function // - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + Status = gBS->CreateEvent ( + EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE, TPL_NOTIFY, DxeRuntimePciSegmentLibVirtualNotify, NULL, - &gEfiEventVirtualAddressChangeGuid, &mDxeRuntimePciSegmentLibVirtualNotifyEvent ); ASSERT_EFI_ERROR (Status); diff --git a/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLibSegmentInfo.inf b/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLibSegmentInfo.inf index f6445f4abb0..ae9f11b697d 100644 --- a/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLibSegmentInfo.inf +++ b/MdePkg/Library/PciSegmentLibSegmentInfo/DxeRuntimePciSegmentLibSegmentInfo.inf @@ -45,6 +45,3 @@ MemoryAllocationLib DxeServicesTableLib UefiBootServicesTableLib - -[Guids] - gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event diff --git a/MdePkg/Library/UefiDebugLibConOut/DebugLibConstructor.c b/MdePkg/Library/UefiDebugLibConOut/DebugLibConstructor.c index ed73f928187..b4ac17cf55a 100644 --- a/MdePkg/Library/UefiDebugLibConOut/DebugLibConstructor.c +++ b/MdePkg/Library/UefiDebugLibConOut/DebugLibConstructor.c @@ -64,12 +64,11 @@ DxeDebugLibConstructor( { mDebugST = SystemTable; - SystemTable->BootServices->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + SystemTable->BootServices->CreateEvent ( + EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesCallback, NULL, - &gEfiEventExitBootServicesGuid, &mExitBootServicesEvent ); diff --git a/MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf b/MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf index b577d52ac66..53bbc8ce3f6 100644 --- a/MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf +++ b/MdePkg/Library/UefiDebugLibConOut/UefiDebugLibConOut.inf @@ -46,9 +46,6 @@ PrintLib DebugPrintErrorLevelLib -[Guids] - gEfiEventExitBootServicesGuid ## CONSUMES - [Pcd] gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue ## SOMETIMES_CONSUMES gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask ## CONSUMES diff --git a/MdePkg/Library/UefiDebugLibDebugPortProtocol/DebugLibConstructor.c b/MdePkg/Library/UefiDebugLibDebugPortProtocol/DebugLibConstructor.c index 6ea0912f2b3..96fc1c422fe 100644 --- a/MdePkg/Library/UefiDebugLibDebugPortProtocol/DebugLibConstructor.c +++ b/MdePkg/Library/UefiDebugLibDebugPortProtocol/DebugLibConstructor.c @@ -64,12 +64,11 @@ DxeDebugLibConstructor( { mDebugBS = SystemTable->BootServices; - mDebugBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + mDebugBS->CreateEvent ( + EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesCallback, NULL, - &gEfiEventExitBootServicesGuid, &mExitBootServicesEvent ); diff --git a/MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf b/MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf index ff09a12ce40..e12a1025c6c 100644 --- a/MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf +++ b/MdePkg/Library/UefiDebugLibDebugPortProtocol/UefiDebugLibDebugPortProtocol.inf @@ -46,9 +46,6 @@ PrintLib DebugPrintErrorLevelLib -[Guids] - gEfiEventExitBootServicesGuid ## CONSUMES - [Protocols] gEfiDebugPortProtocolGuid ## CONSUMES diff --git a/MdePkg/Library/UefiDebugLibStdErr/DebugLibConstructor.c b/MdePkg/Library/UefiDebugLibStdErr/DebugLibConstructor.c index ed73f928187..b4ac17cf55a 100644 --- a/MdePkg/Library/UefiDebugLibStdErr/DebugLibConstructor.c +++ b/MdePkg/Library/UefiDebugLibStdErr/DebugLibConstructor.c @@ -64,12 +64,11 @@ DxeDebugLibConstructor( { mDebugST = SystemTable; - SystemTable->BootServices->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + SystemTable->BootServices->CreateEvent ( + EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, ExitBootServicesCallback, NULL, - &gEfiEventExitBootServicesGuid, &mExitBootServicesEvent ); diff --git a/MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf b/MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf index 11f7594626e..5ecb971a0ac 100644 --- a/MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf +++ b/MdePkg/Library/UefiDebugLibStdErr/UefiDebugLibStdErr.inf @@ -44,9 +44,6 @@ PrintLib DebugPrintErrorLevelLib -[Guids] - gEfiEventExitBootServicesGuid ## CONSUMES - [Pcd] gEfiMdePkgTokenSpaceGuid.PcdDebugClearMemoryValue ## SOMETIMES_CONSUMES gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask ## CONSUMES diff --git a/MdePkg/Library/UefiRuntimeLib/RuntimeLib.c b/MdePkg/Library/UefiRuntimeLib/RuntimeLib.c index 933e0099cee..a2eadafac86 100644 --- a/MdePkg/Library/UefiRuntimeLib/RuntimeLib.c +++ b/MdePkg/Library/UefiRuntimeLib/RuntimeLib.c @@ -93,23 +93,21 @@ RuntimeDriverLibConstruct ( // // Register SetVirtualAddressMap () notify function // - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + Status = gBS->CreateEvent ( + EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE, TPL_NOTIFY, RuntimeLibVirtualNotifyEvent, NULL, - &gEfiEventVirtualAddressChangeGuid, &mEfiVirtualNotifyEvent ); ASSERT_EFI_ERROR (Status); - Status = gBS->CreateEventEx ( - EVT_NOTIFY_SIGNAL, + Status = gBS->CreateEvent ( + EVT_SIGNAL_EXIT_BOOT_SERVICES, TPL_NOTIFY, RuntimeLibExitBootServicesEvent, NULL, - &gEfiEventExitBootServicesGuid, &mEfiExitBootServicesEvent ); diff --git a/MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf b/MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf index 5527f9f02f7..cc4ee151100 100644 --- a/MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf +++ b/MdePkg/Library/UefiRuntimeLib/UefiRuntimeLib.inf @@ -39,8 +39,3 @@ UefiBootServicesTableLib UefiRuntimeServicesTableLib DebugLib - -[Guids] - gEfiEventExitBootServicesGuid ## CONSUMES ## Event - gEfiEventVirtualAddressChangeGuid ## CONSUMES ## Event - From 859046e000beecae6903e3f2143ffbd9944c7ee4 Mon Sep 17 00:00:00 2001 From: Jason Voelz Date: Mon, 23 Dec 2019 14:55:36 +0800 Subject: [PATCH 318/384] MdePkg BaseLib.h: Update IA32_CR4 strut to include all public fields Based on Intel Software Develeper's Manual, add all fields in IA32_CR4. Signed-off-by: Jason Voelz Cc: Liming Gao Cc: Ray Ni Reviewed-by: Ray Ni --- MdePkg/Include/Library/BaseLib.h | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/MdePkg/Include/Library/BaseLib.h b/MdePkg/Include/Library/BaseLib.h index 2a75bc023f5..ecadff8b235 100644 --- a/MdePkg/Include/Library/BaseLib.h +++ b/MdePkg/Include/Library/BaseLib.h @@ -5387,10 +5387,19 @@ typedef union { UINT32 OSXMMEXCPT:1; ///< Operating System Support for ///< Unmasked SIMD Floating Point ///< Exceptions. - UINT32 Reserved_2:1; ///< Reserved. + UINT32 UMIP:1; ///< User-Mode Instruction Prevention. UINT32 LA57:1; ///< Linear Address 57bit. - UINT32 VMXE:1; ///< VMX Enable - UINT32 Reserved_1:18; ///< Reserved. + UINT32 VMXE:1; ///< VMX Enable. + UINT32 SMXE:1; ///< SMX Enable. + UINT32 Reserved_3:1; ///< Reserved. + UINT32 FSGSBASE:1; ///< FSGSBASE Enable. + UINT32 PCIDE:1; ///< PCID Enable. + UINT32 OSXSAVE:1; ///< XSAVE and Processor Extended States Enable. + UINT32 Reserved_4:1; ///< Reserved. + UINT32 SMEP:1; ///< SMEP Enable. + UINT32 SMAP:1; ///< SMAP Enable. + UINT32 PKE:1; ///< Protection-Key Enable. + UINT32 Reserved_5:9; ///< Reserved. } Bits; UINTN UintN; } IA32_CR4; From 1f0d8096291651e6c20dbbc57d108321c1443563 Mon Sep 17 00:00:00 2001 From: Jason Voelz Date: Mon, 23 Dec 2019 14:55:37 +0800 Subject: [PATCH 319/384] UefiCpuPkg/CpuCommonFeaturesLib: SMXE bit of CR4 should set Add code to set SMXE in CR4 in the SmxInitialize flow when SMX is enabled. Signed-off-by: Jason Voelz Cc: Ray Ni Reviewed-by: Ray Ni --- UefiCpuPkg/Library/CpuCommonFeaturesLib/FeatureControl.c | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/UefiCpuPkg/Library/CpuCommonFeaturesLib/FeatureControl.c b/UefiCpuPkg/Library/CpuCommonFeaturesLib/FeatureControl.c index 38d3f53f564..b4474d2fab4 100644 --- a/UefiCpuPkg/Library/CpuCommonFeaturesLib/FeatureControl.c +++ b/UefiCpuPkg/Library/CpuCommonFeaturesLib/FeatureControl.c @@ -240,6 +240,15 @@ SmxInitialize ( Status = RETURN_UNSUPPORTED; } + CPU_REGISTER_TABLE_WRITE_FIELD ( + ProcessorNumber, + ControlRegister, + 4, + IA32_CR4, + Bits.SMXE, + (State) ? 1 : 0 + ) + CPU_REGISTER_TABLE_TEST_THEN_WRITE_FIELD ( ProcessorNumber, Msr, From 8ffa47fb3abd58ded6fe852ee9f518d19f9f9858 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 9 Jan 2020 18:55:43 +0800 Subject: [PATCH 320/384] BaseTools/PatchCheck.py: Extract email check code to EmailAddressCheck As we are going to reuse this code out of the CommitMessageCheck class, extract it in a new class: EmailAddressCheck. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Scripts/PatchCheck.py | 83 +++++++++++++++++++++------------ 1 file changed, 54 insertions(+), 29 deletions(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 9668025798d..3b6d77081e7 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -2,6 +2,7 @@ # Check a patch for various format issues # # Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+# Copyright (C) 2020, Red Hat, Inc.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -22,6 +23,58 @@ class Verbose: SILENT, ONELINE, NORMAL = range(3) level = NORMAL +class EmailAddressCheck: + """Checks an email address.""" + + def __init__(self, email): + self.ok = True + + if email is None: + self.error('Email address is missing!') + return + + self.check_email_address(email) + + def error(self, *err): + if self.ok and Verbose.level > Verbose.ONELINE: + print('The email address is not valid:') + self.ok = False + if Verbose.level < Verbose.NORMAL: + return + count = 0 + for line in err: + prefix = (' *', ' ')[count > 0] + print(prefix, line) + count += 1 + + email_re1 = re.compile(r'(?:\s*)(.*?)(\s*)<(.+)>\s*$', + re.MULTILINE|re.IGNORECASE) + + def check_email_address(self, email): + email = email.strip() + mo = self.email_re1.match(email) + if mo is None: + self.error("Email format is invalid: " + email.strip()) + return + + name = mo.group(1).strip() + if name == '': + self.error("Name is not provided with email address: " + + email) + else: + quoted = len(name) > 2 and name[0] == '"' and name[-1] == '"' + if name.find(',') >= 0 and not quoted: + self.error('Add quotes (") around name with a comma: ' + + name) + + if mo.group(2) == '': + self.error("There should be a space between the name and " + + "email address: " + email) + + if mo.group(3).find(' ') >= 0: + self.error("The email address cannot contain a space: " + + mo.group(3)) + class CommitMessageCheck: """Checks the contents of a git commit message.""" @@ -121,38 +174,10 @@ def find_signatures(self, sig): if s[2] != ' ': self.error("There should be a space after '" + sig + ":'") - self.check_email_address(s[3]) + EmailAddressCheck(s[3]) return sigs - email_re1 = re.compile(r'(?:\s*)(.*?)(\s*)<(.+)>\s*$', - re.MULTILINE|re.IGNORECASE) - - def check_email_address(self, email): - email = email.strip() - mo = self.email_re1.match(email) - if mo is None: - self.error("Email format is invalid: " + email.strip()) - return - - name = mo.group(1).strip() - if name == '': - self.error("Name is not provided with email address: " + - email) - else: - quoted = len(name) > 2 and name[0] == '"' and name[-1] == '"' - if name.find(',') >= 0 and not quoted: - self.error('Add quotes (") around name with a comma: ' + - name) - - if mo.group(2) == '': - self.error("There should be a space between the name and " + - "email address: " + email) - - if mo.group(3).find(' ') >= 0: - self.error("The email address cannot contain a space: " + - mo.group(3)) - def check_signed_off_by(self): sob='Signed-off-by' if self.msg.find(sob) < 0: From 8f38b08b506c0ea602444a09eda2f5ef1099498a Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 9 Jan 2020 18:55:46 +0800 Subject: [PATCH 321/384] BaseTools/PatchCheck.py: Check the committer email address To avoid patches committed with incorrect email address, use the EmailAddressCheck class on the committer email too. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Scripts/PatchCheck.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 3b6d77081e7..174d442aa70 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -552,6 +552,8 @@ def __init__(self, rev_spec, max_count): else: blank_line = True print('Checking git commit:', commit) + email = self.read_committer_email_address_from_git(commit) + self.ok &= EmailAddressCheck(email, 'Committer').ok patch = self.read_patch_from_git(commit) self.ok &= CheckOnePatch(commit, patch).ok if not commits: @@ -570,6 +572,10 @@ def read_patch_from_git(self, commit): # Run git to get the commit patch return self.run_git('show', '--pretty=email', '--no-textconv', commit) + def read_committer_email_address_from_git(self, commit): + # Run git to get the committer email + return self.run_git('show', '--pretty=%cn <%ce>', '--no-patch', commit) + def run_git(self, *args): cmd = [ 'git' ] cmd += args From 8120390aabe6bc6a6ecb5c94a2865a9b55095f9b Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 9 Jan 2020 18:55:44 +0800 Subject: [PATCH 322/384] BaseTools/PatchCheck.py: Let EmailAddressCheck describe email checked We are checking different emails from the signature list. We are going to check more. To be able to differency, add a description field, so the error reported is clearer. Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Scripts/PatchCheck.py | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 174d442aa70..58d0112544c 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -26,18 +26,22 @@ class Verbose: class EmailAddressCheck: """Checks an email address.""" - def __init__(self, email): + def __init__(self, email, description): self.ok = True if email is None: self.error('Email address is missing!') return + if description is None: + self.error('Email description is missing!') + return + self.description = "'" + description + "'" self.check_email_address(email) def error(self, *err): if self.ok and Verbose.level > Verbose.ONELINE: - print('The email address is not valid:') + print('The ' + self.description + ' email address is not valid:') self.ok = False if Verbose.level < Verbose.NORMAL: return @@ -174,7 +178,7 @@ def find_signatures(self, sig): if s[2] != ' ': self.error("There should be a space after '" + sig + ":'") - EmailAddressCheck(s[3]) + EmailAddressCheck(s[3], sig) return sigs From c0328cf3803b215a62f05633024f9dd6e5b805a0 Mon Sep 17 00:00:00 2001 From: Philippe Mathieu-Daude Date: Thu, 9 Jan 2020 18:55:45 +0800 Subject: [PATCH 323/384] BaseTools/PatchCheck.py: Check the patch author email address To avoid patches committed with incorrect email address, use the EmailAddressCheck class on the author email too. Example: $ python BaseTools/Scripts/PatchCheck.py 1a04951309f Checking git commit: 1a04951309f The 'Author' email address is not valid: * The email address cannot contain a space: /o=Intel/ou=External \ (FYDIBOHF25SPDLT)/cn=Recipients/cn=fe425ca7e5f4401abed22b904fe5d964 Cc: Bob Feng Cc: Liming Gao Reviewed-by: Bob Feng Signed-off-by: Philippe Mathieu-Daude --- BaseTools/Scripts/PatchCheck.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index 58d0112544c..fe8e6a64f2b 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -451,6 +451,9 @@ def __init__(self, name, patch): self.patch = patch self.find_patch_pieces() + email_check = EmailAddressCheck(self.author_email, 'Author') + email_ok = email_check.ok + msg_check = CommitMessageCheck(self.commit_subject, self.commit_msg) msg_ok = msg_check.ok @@ -459,7 +462,7 @@ def __init__(self, name, patch): diff_check = GitDiffCheck(self.diff) diff_ok = diff_check.ok - self.ok = msg_ok and diff_ok + self.ok = email_ok and msg_ok and diff_ok if Verbose.level == Verbose.ONELINE: if self.ok: @@ -537,6 +540,8 @@ def find_patch_pieces(self): self.commit_subject = self.commit_subject.replace('\n', '') self.commit_subject = self.subject_prefix_re.sub('', self.commit_subject, 1) + self.author_email = pmail['from'] + class CheckGitCommits: """Reads patches from git based on the specified git revision range. From e3ccf1c737ccfb868daf32b456d5b1ac037fe3d5 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 9 Jan 2020 21:32:29 -0800 Subject: [PATCH 324/384] Add a host-based test DSC for UnitTestFrameworkPkg. --- MdePkg/MdePkg.ci.yaml | 2 +- .../SampleUnitTest/SampleUnitTestHost.inf | 30 +++++++++++++++++++ .../Test/UnitTestFrameworkPkgHostTest.dsc | 24 +++++++++++++++ .../UnitTestFrameworkPkg.ci.yaml | 11 +++++++ 4 files changed, 66 insertions(+), 1 deletion(-) create mode 100644 UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf create mode 100644 UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc diff --git a/MdePkg/MdePkg.ci.yaml b/MdePkg/MdePkg.ci.yaml index d214e5e902f..88e490fcb66 100644 --- a/MdePkg/MdePkg.ci.yaml +++ b/MdePkg/MdePkg.ci.yaml @@ -43,7 +43,7 @@ ## options defined ci/Plugin/HostUnitTestDscCompleteCheck "HostUnitTestDscCompleteCheck": { "IgnoreInf": [""], - "DscPath": "MdePkgTest.dsc" + "DscPath": "Test/MdePkgHostTest.dsc" }, ## options defined ci/Plugin/GuidCheck diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf new file mode 100644 index 00000000000..85dce4c5b61 --- /dev/null +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf @@ -0,0 +1,30 @@ +## @file +# Sample UnitTest built for execution on a Host/Dev machine. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SampleUnitTestHost + FILE_GUID = CC0EA77E-BF2D-4134-B419-0C02E15CE08E + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SampleUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib + UnitTestLib diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc new file mode 100644 index 00000000000..2eb4167ee79 --- /dev/null +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -0,0 +1,24 @@ +## @file +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = UnitTestFrameworkPkgHostTest + PLATFORM_GUID = C7F97D6D-54AC-45A9-8197-CC99B20CC7EC + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[Components] + # + # Build HOST_APPLICATION that tests the SampleUnitTest + # + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 8fc19da3085..370330c2cc0 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -8,6 +8,11 @@ "CompilerPlugin": { "DscPath": "UnitTestFrameworkPkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "Test/UnitTestFrameworkPkgHostTest.dsc" + }, + "CharEncodingCheck": { "IgnoreFiles": [] }, @@ -36,6 +41,12 @@ "UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf", ] }, + ## options defined ci/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "Test/UnitTestFrameworkPkgHostTest.dsc" + }, + "GuidCheck": { "IgnoreGuidName": [], "IgnoreGuidValue": [], From c7c964b10999895685c3bcf844e5b7261af05619 Mon Sep 17 00:00:00 2001 From: Siyuan Fu Date: Wed, 8 Jan 2020 11:14:38 +0800 Subject: [PATCH 325/384] MdePkg: Add header file for Firmware Interface Table specification. This patch add FirmwareInterfaceTable.h for the Firmware Interface Table BIOS specification. This is to remove future edk2 dependency on edk2-platforms repo. The file content comes from edk2-platforms\Silicon\Intel\IntelSiliconPkg\Include\IndustryStandard BZ link: https://tianocore.acgmultimedia.com/show_bug.cgi?id=2449 Cc: Michael D Kinney Cc: Liming Gao Signed-off-by: Siyuan Fu Reviewed-by: Liming Gao --- .../IndustryStandard/FirmwareInterfaceTable.h | 76 +++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 MdePkg/Include/IndustryStandard/FirmwareInterfaceTable.h diff --git a/MdePkg/Include/IndustryStandard/FirmwareInterfaceTable.h b/MdePkg/Include/IndustryStandard/FirmwareInterfaceTable.h new file mode 100644 index 00000000000..be3e34ae1b2 --- /dev/null +++ b/MdePkg/Include/IndustryStandard/FirmwareInterfaceTable.h @@ -0,0 +1,76 @@ +/** @file + Industry Standard Definitions of Firmware Interface Table BIOS Specification 1.0. + + Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#ifndef __FIRMWARE_INTERFACE_TABLE_H__ +#define __FIRMWARE_INTERFACE_TABLE_H__ + +// +// FIT Entry type definitions +// +#define FIT_TYPE_00_HEADER 0x00 +#define FIT_TYPE_01_MICROCODE 0x01 +#define FIT_TYPE_02_STARTUP_ACM 0x02 +#define FIT_TYPE_07_BIOS_STARTUP_MODULE 0x07 +#define FIT_TYPE_08_TPM_POLICY 0x08 +#define FIT_TYPE_09_BIOS_POLICY 0x09 +#define FIT_TYPE_0A_TXT_POLICY 0x0A +#define FIT_TYPE_0B_KEY_MANIFEST 0x0B +#define FIT_TYPE_0C_BOOT_POLICY_MANIFEST 0x0C +#define FIT_TYPE_10_CSE_SECURE_BOOT 0x10 +#define FIT_TYPE_2D_TXTSX_POLICY 0x2D +#define FIT_TYPE_2F_JMP_DEBUG_POLICY 0x2F +#define FIT_TYPE_7F_SKIP 0x7F + +#define FIT_POINTER_ADDRESS 0xFFFFFFC0 ///< Fixed address at 4G - 40h + +#define FIT_TYPE_VERSION 0x0100 + +#define FIT_TYPE_00_SIGNATURE SIGNATURE_64 ('_', 'F', 'I', 'T', '_', ' ', ' ', ' ') + +#pragma pack(1) + +typedef struct { + // + // Address is the base address of the firmware component + // must be aligned on 16 byte boundary + // + UINT64 Address; + // + // Size is the span of the component in multiple of 16 bytes + // + UINT8 Size[3]; + // + // Reserved must be set to 0 + // + UINT8 Reserved; + // + // Component's version number in binary coded decimal (BCD) format. + // For the FIT header entry, the value in this field will indicate the revision + // number of the FIT data structure. The upper byte of the revision field + // indicates the major revision and the lower byte indicates the minor revision. + // + UINT16 Version; + // + // FIT types 0x00 to 0x7F + // + UINT8 Type : 7; + // + // Checksum Valid indicates whether component has valid checksum. + // + UINT8 C_V : 1; + // + // Component's checksum. The modulo sum of all the bytes in the component and + // the value in this field (Chksum) must add up to zero. This field is only + // valid if the C_V flag is non-zero. + // + UINT8 Chksum; +} FIRMWARE_INTERFACE_TABLE_ENTRY; + +#pragma pack() + +#endif From dd01704111c6e85b7bca62968d48abc2c626a3c6 Mon Sep 17 00:00:00 2001 From: Siyuan Fu Date: Wed, 8 Jan 2020 11:22:30 +0800 Subject: [PATCH 326/384] UefiCpuPkg: Shadow microcode patch according to FIT microcode entry. The existing MpInitLib will shadow the microcode update patches from flash to memory and this is done by searching microcode region specified by PCD PcdCpuMicrocodePatchAddress and PcdCpuMicrocodePatchRegionSize. This brings a limition to platform FW that all the microcode patches must be placed in one continuous flash space. This patch shadows microcode update according to FIT microcode entries if it's present, otherwise it will fallback to original logic (by PCD). A new featured PCD gUefiCpuPkgTokenSpaceGuid.PcdCpuShadowMicrocodeByFit is added for enabling/disabling this support. TEST: Tested on FIT enabled platform. BZ: https://tianocore.acgmultimedia.com/show_bug.cgi?id=2449 Cc: Eric Dong Cc: Ray Ni Cc: Laszlo Ersek Signed-off-by: Siyuan Fu Reviewed-by: Eric Dong Reviewed-by: Laszlo Ersek --- UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf | 1 + UefiCpuPkg/Library/MpInitLib/Microcode.c | 262 +++++++++++++----- UefiCpuPkg/Library/MpInitLib/MpLib.c | 4 +- UefiCpuPkg/Library/MpInitLib/MpLib.h | 7 +- UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf | 3 +- UefiCpuPkg/UefiCpuPkg.dec | 6 + UefiCpuPkg/UefiCpuPkg.uni | 6 + 7 files changed, 222 insertions(+), 67 deletions(-) diff --git a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf index cd912ab0c5e..bf5d18d521e 100644 --- a/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/DxeMpInitLib.inf @@ -68,5 +68,6 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuApTargetCstate ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuShadowMicrocodeByFit ## CONSUMES gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard ## CONSUMES diff --git a/UefiCpuPkg/Library/MpInitLib/Microcode.c b/UefiCpuPkg/Library/MpInitLib/Microcode.c index 8f4d4da40c7..9389e52ae51 100644 --- a/UefiCpuPkg/Library/MpInitLib/Microcode.c +++ b/UefiCpuPkg/Library/MpInitLib/Microcode.c @@ -318,7 +318,7 @@ MicrocodeDetect ( } /** - Determine if a microcode patch will be loaded into memory. + Determine if a microcode patch matchs the specific processor signature and flag. @param[in] CpuMpData The pointer to CPU MP Data structure. @param[in] ProcessorSignature The processor signature field value @@ -330,7 +330,7 @@ MicrocodeDetect ( @retval FALSE The specified microcode patch will not be loaded. **/ BOOLEAN -IsMicrocodePatchNeedLoad ( +IsProcessorMatchedMicrocodePatch ( IN CPU_MP_DATA *CpuMpData, IN UINT32 ProcessorSignature, IN UINT32 ProcessorFlags @@ -351,7 +351,77 @@ IsMicrocodePatchNeedLoad ( } /** - Actual worker function that loads the required microcode patches into memory. + Check the 'ProcessorSignature' and 'ProcessorFlags' of the microcode + patch header with the CPUID and PlatformID of the processors within + system to decide if it will be copied into memory. + + @param[in] CpuMpData The pointer to CPU MP Data structure. + @param[in] MicrocodeEntryPoint The pointer to the microcode patch header. + + @retval TRUE The specified microcode patch need to be loaded. + @retval FALSE The specified microcode patch dosen't need to be loaded. +**/ +BOOLEAN +IsMicrocodePatchNeedLoad ( + IN CPU_MP_DATA *CpuMpData, + CPU_MICROCODE_HEADER *MicrocodeEntryPoint + ) +{ + BOOLEAN NeedLoad; + UINTN DataSize; + UINTN TotalSize; + CPU_MICROCODE_EXTENDED_TABLE_HEADER *ExtendedTableHeader; + UINT32 ExtendedTableCount; + CPU_MICROCODE_EXTENDED_TABLE *ExtendedTable; + UINTN Index; + + // + // Check the 'ProcessorSignature' and 'ProcessorFlags' in microcode patch header. + // + NeedLoad = IsProcessorMatchedMicrocodePatch ( + CpuMpData, + MicrocodeEntryPoint->ProcessorSignature.Uint32, + MicrocodeEntryPoint->ProcessorFlags + ); + + // + // If the Extended Signature Table exists, check if the processor is in the + // support list + // + DataSize = MicrocodeEntryPoint->DataSize; + TotalSize = (DataSize == 0) ? 2048 : MicrocodeEntryPoint->TotalSize; + if ((!NeedLoad) && (DataSize != 0) && + (TotalSize - DataSize > sizeof (CPU_MICROCODE_HEADER) + + sizeof (CPU_MICROCODE_EXTENDED_TABLE_HEADER))) { + ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *) ((UINT8 *) (MicrocodeEntryPoint) + + DataSize + sizeof (CPU_MICROCODE_HEADER)); + ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount; + ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *) (ExtendedTableHeader + 1); + + for (Index = 0; Index < ExtendedTableCount; Index ++) { + // + // Check the 'ProcessorSignature' and 'ProcessorFlag' of the Extended + // Signature Table entry with the CPUID and PlatformID of the processors + // within system to decide if it will be copied into memory + // + NeedLoad = IsProcessorMatchedMicrocodePatch ( + CpuMpData, + ExtendedTable->ProcessorSignature.Uint32, + ExtendedTable->ProcessorFlag + ); + if (NeedLoad) { + break; + } + ExtendedTable ++; + } + } + + return NeedLoad; +} + + +/** + Actual worker function that shadows the required microcode patches into memory. @param[in, out] CpuMpData The pointer to CPU MP Data structure. @param[in] Patches The pointer to an array of information on @@ -363,7 +433,7 @@ IsMicrocodePatchNeedLoad ( to be loaded. **/ VOID -LoadMicrocodePatchWorker ( +ShadowMicrocodePatchWorker ( IN OUT CPU_MP_DATA *CpuMpData, IN MICROCODE_PATCH_INFO *Patches, IN UINTN PatchCount, @@ -390,7 +460,6 @@ LoadMicrocodePatchWorker ( (VOID *) Patches[Index].Address, Patches[Index].Size ); - Walker += Patches[Index].Size; } @@ -410,12 +479,13 @@ LoadMicrocodePatchWorker ( } /** - Load the required microcode patches data into memory. + Shadow the required microcode patches data into memory according to PCD + PcdCpuMicrocodePatchAddress and PcdCpuMicrocodePatchRegionSize. @param[in, out] CpuMpData The pointer to CPU MP Data structure. **/ VOID -LoadMicrocodePatch ( +ShadowMicrocodePatchByPcd ( IN OUT CPU_MP_DATA *CpuMpData ) { @@ -423,15 +493,10 @@ LoadMicrocodePatch ( UINTN MicrocodeEnd; UINTN DataSize; UINTN TotalSize; - CPU_MICROCODE_EXTENDED_TABLE_HEADER *ExtendedTableHeader; - UINT32 ExtendedTableCount; - CPU_MICROCODE_EXTENDED_TABLE *ExtendedTable; MICROCODE_PATCH_INFO *PatchInfoBuffer; UINTN MaxPatchNumber; UINTN PatchCount; UINTN TotalLoadSize; - UINTN Index; - BOOLEAN NeedLoad; // // Initialize the microcode patch related fields in CpuMpData as the values @@ -487,55 +552,7 @@ LoadMicrocodePatch ( continue; } - // - // Check the 'ProcessorSignature' and 'ProcessorFlags' of the microcode - // patch header with the CPUID and PlatformID of the processors within - // system to decide if it will be copied into memory - // - NeedLoad = IsMicrocodePatchNeedLoad ( - CpuMpData, - MicrocodeEntryPoint->ProcessorSignature.Uint32, - MicrocodeEntryPoint->ProcessorFlags - ); - - // - // If the Extended Signature Table exists, check if the processor is in the - // support list - // - if ((!NeedLoad) && (DataSize != 0) && - (TotalSize - DataSize > sizeof (CPU_MICROCODE_HEADER) + - sizeof (CPU_MICROCODE_EXTENDED_TABLE_HEADER))) { - ExtendedTableHeader = (CPU_MICROCODE_EXTENDED_TABLE_HEADER *) ((UINT8 *) (MicrocodeEntryPoint) - + DataSize + sizeof (CPU_MICROCODE_HEADER)); - ExtendedTableCount = ExtendedTableHeader->ExtendedSignatureCount; - ExtendedTable = (CPU_MICROCODE_EXTENDED_TABLE *) (ExtendedTableHeader + 1); - - for (Index = 0; Index < ExtendedTableCount; Index ++) { - // - // Avoid access content beyond MicrocodeEnd - // - if ((UINTN) ExtendedTable > MicrocodeEnd - sizeof (CPU_MICROCODE_EXTENDED_TABLE)) { - break; - } - - // - // Check the 'ProcessorSignature' and 'ProcessorFlag' of the Extended - // Signature Table entry with the CPUID and PlatformID of the processors - // within system to decide if it will be copied into memory - // - NeedLoad = IsMicrocodePatchNeedLoad ( - CpuMpData, - ExtendedTable->ProcessorSignature.Uint32, - ExtendedTable->ProcessorFlag - ); - if (NeedLoad) { - break; - } - ExtendedTable ++; - } - } - - if (NeedLoad) { + if (IsMicrocodePatchNeedLoad (CpuMpData, MicrocodeEntryPoint)) { PatchCount++; if (PatchCount > MaxPatchNumber) { // @@ -581,7 +598,7 @@ LoadMicrocodePatch ( __FUNCTION__, PatchCount, TotalLoadSize )); - LoadMicrocodePatchWorker (CpuMpData, PatchInfoBuffer, PatchCount, TotalLoadSize); + ShadowMicrocodePatchWorker (CpuMpData, PatchInfoBuffer, PatchCount, TotalLoadSize); } OnExit: @@ -590,3 +607,124 @@ LoadMicrocodePatch ( } return; } + +/** + Shadow the required microcode patches data into memory according to FIT microcode entry. + + @param[in, out] CpuMpData The pointer to CPU MP Data structure. + + @return EFI_SUCCESS Microcode patch is shadowed into memory. + @return EFI_UNSUPPORTED FIT based microcode shadowing is not supported. + @return EFI_OUT_OF_RESOURCES No enough memory resource. + @return EFI_NOT_FOUND There is something wrong in FIT microcode entry. + +**/ +EFI_STATUS +ShadowMicrocodePatchByFit ( + IN OUT CPU_MP_DATA *CpuMpData + ) +{ + UINT64 FitPointer; + FIRMWARE_INTERFACE_TABLE_ENTRY *FitEntry; + UINT32 EntryNum; + UINT32 Index; + MICROCODE_PATCH_INFO *PatchInfoBuffer; + UINTN MaxPatchNumber; + CPU_MICROCODE_HEADER *MicrocodeEntryPoint; + UINTN PatchCount; + UINTN TotalSize; + UINTN TotalLoadSize; + + if (!FeaturePcdGet (PcdCpuShadowMicrocodeByFit)) { + return EFI_UNSUPPORTED; + } + + FitPointer = *(UINT64 *) (UINTN) FIT_POINTER_ADDRESS; + if ((FitPointer == 0) || + (FitPointer == 0xFFFFFFFFFFFFFFFF) || + (FitPointer == 0xEEEEEEEEEEEEEEEE)) { + // + // No FIT table. + // + ASSERT (FALSE); + return EFI_NOT_FOUND; + } + FitEntry = (FIRMWARE_INTERFACE_TABLE_ENTRY *) (UINTN) FitPointer; + if ((FitEntry[0].Type != FIT_TYPE_00_HEADER) || + (FitEntry[0].Address != FIT_TYPE_00_SIGNATURE)) { + // + // Invalid FIT table, treat it as no FIT table. + // + ASSERT (FALSE); + return EFI_NOT_FOUND; + } + + EntryNum = *(UINT32 *)(&FitEntry[0].Size[0]) & 0xFFFFFF; + + // + // Calculate microcode entry number + // + MaxPatchNumber = 0; + for (Index = 0; Index < EntryNum; Index++) { + if (FitEntry[Index].Type == FIT_TYPE_01_MICROCODE) { + MaxPatchNumber++; + } + } + if (MaxPatchNumber == 0) { + return EFI_NOT_FOUND; + } + + PatchInfoBuffer = AllocatePool (MaxPatchNumber * sizeof (MICROCODE_PATCH_INFO)); + if (PatchInfoBuffer == NULL) { + return EFI_OUT_OF_RESOURCES; + } + + // + // Fill up microcode patch info buffer according to FIT table. + // + PatchCount = 0; + TotalLoadSize = 0; + for (Index = 0; Index < EntryNum; Index++) { + if (FitEntry[Index].Type == FIT_TYPE_01_MICROCODE) { + MicrocodeEntryPoint = (CPU_MICROCODE_HEADER *) (UINTN) FitEntry[Index].Address; + TotalSize = (MicrocodeEntryPoint->DataSize == 0) ? 2048 : MicrocodeEntryPoint->TotalSize; + if (IsMicrocodePatchNeedLoad (CpuMpData, MicrocodeEntryPoint)) { + PatchInfoBuffer[PatchCount].Address = (UINTN) MicrocodeEntryPoint; + PatchInfoBuffer[PatchCount].Size = TotalSize; + TotalLoadSize += TotalSize; + PatchCount++; + } + } + } + + if (PatchCount != 0) { + DEBUG (( + DEBUG_INFO, + "%a: 0x%x microcode patches will be loaded into memory, with size 0x%x.\n", + __FUNCTION__, PatchCount, TotalLoadSize + )); + + ShadowMicrocodePatchWorker (CpuMpData, PatchInfoBuffer, PatchCount, TotalLoadSize); + } + + FreePool (PatchInfoBuffer); + return EFI_SUCCESS; +} + +/** + Shadow the required microcode patches data into memory. + + @param[in, out] CpuMpData The pointer to CPU MP Data structure. +**/ +VOID +ShadowMicrocodeUpdatePatch ( + IN OUT CPU_MP_DATA *CpuMpData + ) +{ + EFI_STATUS Status; + + Status = ShadowMicrocodePatchByFit (CpuMpData); + if (EFI_ERROR (Status)) { + ShadowMicrocodePatchByPcd (CpuMpData); + } +} diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.c b/UefiCpuPkg/Library/MpInitLib/MpLib.c index e611a8ca406..6ec9b172b86 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.c +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.c @@ -1,7 +1,7 @@ /** @file CPU MP Initialize Library common functions. - Copyright (c) 2016 - 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -1744,7 +1744,7 @@ MpInitLibInitialize ( // // Load required microcode patches data into memory // - LoadMicrocodePatch (CpuMpData); + ShadowMicrocodeUpdatePatch (CpuMpData); } else { // // APs have been wakeup before, just get the CPU Information diff --git a/UefiCpuPkg/Library/MpInitLib/MpLib.h b/UefiCpuPkg/Library/MpInitLib/MpLib.h index b6e5a1afab0..7c62d75accf 100644 --- a/UefiCpuPkg/Library/MpInitLib/MpLib.h +++ b/UefiCpuPkg/Library/MpInitLib/MpLib.h @@ -29,6 +29,9 @@ #include #include +#include + + #define WAKEUP_AP_SIGNAL SIGNATURE_32 ('S', 'T', 'A', 'P') #define CPU_INIT_MP_LIB_HOB_GUID \ @@ -587,12 +590,12 @@ MicrocodeDetect ( ); /** - Load the required microcode patches data into memory. + Shadow the required microcode patches data into memory. @param[in, out] CpuMpData The pointer to CPU MP Data structure. **/ VOID -LoadMicrocodePatch ( +ShadowMicrocodeUpdatePatch ( IN OUT CPU_MP_DATA *CpuMpData ); diff --git a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf index 326703cc9ad..555125a7c57 100644 --- a/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf +++ b/UefiCpuPkg/Library/MpInitLib/PeiMpInitLib.inf @@ -1,7 +1,7 @@ ## @file # MP Initialize Library instance for PEI driver. # -# Copyright (c) 2016 - 2017, Intel Corporation. All rights reserved.
+# Copyright (c) 2016 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -60,6 +60,7 @@ gUefiCpuPkgTokenSpaceGuid.PcdCpuMicrocodePatchRegionSize ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuApLoopMode ## CONSUMES gUefiCpuPkgTokenSpaceGuid.PcdCpuApTargetCstate ## SOMETIMES_CONSUMES + gUefiCpuPkgTokenSpaceGuid.PcdCpuShadowMicrocodeByFit ## CONSUMES [Guids] gEdkiiS3SmmInitDoneGuid diff --git a/UefiCpuPkg/UefiCpuPkg.dec b/UefiCpuPkg/UefiCpuPkg.dec index 45b267ac61d..a6ebdde1cfb 100644 --- a/UefiCpuPkg/UefiCpuPkg.dec +++ b/UefiCpuPkg/UefiCpuPkg.dec @@ -139,6 +139,12 @@ # @Prompt Lock SMM Feature Control MSR. gUefiCpuPkgTokenSpaceGuid.PcdCpuSmmFeatureControlMsrLock|TRUE|BOOLEAN|0x3213210B + ## Indicates if FIT based microcode shadowing will be enabled.

+ # TRUE - FIT base microcode shadowing will be enabled.
+ # FALSE - FIT base microcode shadowing will be disabled.
+ # @Prompt FIT based microcode shadowing. + gUefiCpuPkgTokenSpaceGuid.PcdCpuShadowMicrocodeByFit|FALSE|BOOLEAN|0x3213210D + [PcdsFixedAtBuild] ## List of exception vectors which need switching stack. # This PCD will only take into effect if PcdCpuStackGuard is enabled. diff --git a/UefiCpuPkg/UefiCpuPkg.uni b/UefiCpuPkg/UefiCpuPkg.uni index c0d6ed51367..2db49e841b4 100644 --- a/UefiCpuPkg/UefiCpuPkg.uni +++ b/UefiCpuPkg/UefiCpuPkg.uni @@ -100,6 +100,12 @@ "TRUE - locked.
\n" "FALSE - unlocked.
" +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuShadowMicrocodeByFit_PROMPT #language en-US "FIT based microcode shadowing" + +#string STR_gUefiCpuPkgTokenSpaceGuid_PcdCpuShadowMicrocodeByFit_HELP #language en-US "Indicates if FIT based microcode shadowing will be enabled.

\n" + "TRUE - FIT base microcode shadowing will be enabled.
\n" + "FALSE - FIT base microcode shadowing will be disabled.
" + #string STR_gUefiCpuPkgTokenSpaceGuid_PcdPeiTemporaryRamStackSize_PROMPT #language en-US "Stack size in the temporary RAM" #string STR_gUefiCpuPkgTokenSpaceGuid_PcdPeiTemporaryRamStackSize_HELP #language en-US "Specifies stack size in the temporary RAM. 0 means half of TemporaryRamSize." From 7d3d87e4d7b91e300e22e29dcd1e15b09630ffce Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 16:01:20 +0100 Subject: [PATCH 327/384] MdeModulePkg: remove EnterS3WithImmediateWake () from ResetSystemLib EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- MdeModulePkg/Include/Library/ResetSystemLib.h | 11 ----------- .../BaseResetSystemLibNull.c | 14 -------------- .../Library/DxeResetSystemLib/DxeResetSystemLib.c | 13 ------------- .../Library/PeiResetSystemLib/PeiResetSystemLib.c | 13 ------------- .../RuntimeResetSystemLib/RuntimeResetSystemLib.c | 13 ------------- 5 files changed, 64 deletions(-) diff --git a/MdeModulePkg/Include/Library/ResetSystemLib.h b/MdeModulePkg/Include/Library/ResetSystemLib.h index 3b2a098a608..09ee14540c4 100644 --- a/MdeModulePkg/Include/Library/ResetSystemLib.h +++ b/MdeModulePkg/Include/Library/ResetSystemLib.h @@ -51,17 +51,6 @@ ResetShutdown ( VOID ); -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ); - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed diff --git a/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c b/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c index 8d4c1028e60..33a896bee05 100644 --- a/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c +++ b/MdeModulePkg/Library/BaseResetSystemLibNull/BaseResetSystemLibNull.c @@ -58,20 +58,6 @@ ResetShutdown ( ASSERT (FALSE); } -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - ASSERT (FALSE); -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed diff --git a/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c b/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c index a85b6cd9a61..47b814fe8de 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.c @@ -57,19 +57,6 @@ ResetShutdown ( gRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL); } -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed diff --git a/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c b/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c index 50297129b7c..6c8c770ca37 100644 --- a/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c +++ b/MdeModulePkg/Library/PeiResetSystemLib/PeiResetSystemLib.c @@ -57,19 +57,6 @@ ResetShutdown ( PeiServicesResetSystem2 (EfiResetShutdown, EFI_SUCCESS, 0, NULL); } -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed diff --git a/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c b/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c index 29b3f7ebd87..f4490180ccf 100644 --- a/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c +++ b/MdeModulePkg/Library/RuntimeResetSystemLib/RuntimeResetSystemLib.c @@ -62,19 +62,6 @@ ResetShutdown ( mInternalRT->ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL); } -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed From 6eacb857c17b842595c6c6061a46b378af2a9616 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 16:02:26 +0100 Subject: [PATCH 328/384] PcAtChipsetPkg: remove EnterS3WithImmediateWake () from ResetSystemLib EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Signed-off-by: Ard Biesheuvel Reviewed-by: Ray Ni --- .../Library/ResetSystemLib/ResetSystemLib.c | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.c b/PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.c index 7fe1663c97d..e42c41c48e1 100644 --- a/PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.c +++ b/PcAtChipsetPkg/Library/ResetSystemLib/ResetSystemLib.c @@ -65,23 +65,6 @@ ResetShutdown ( } -/** - Calling this function causes the system to enter a power state for capsule - update. - - Reset update should not return, if it returns, it means the system does - not support capsule update. - -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - ASSERT (FALSE); -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed From eaea26b7814bbc08982bfbf087648701a91fe88c Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 16:03:01 +0100 Subject: [PATCH 329/384] UefiPayloadPkg: remove EnterS3WithImmediateWake () from ResetSystemLib EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Signed-off-by: Ard Biesheuvel Reviewed-by: Guo Dong --- .../Library/ResetSystemLib/ResetSystemLib.c | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/UefiPayloadPkg/Library/ResetSystemLib/ResetSystemLib.c b/UefiPayloadPkg/Library/ResetSystemLib/ResetSystemLib.c index 3fe3c805afe..2e4b7fe5926 100644 --- a/UefiPayloadPkg/Library/ResetSystemLib/ResetSystemLib.c +++ b/UefiPayloadPkg/Library/ResetSystemLib/ResetSystemLib.c @@ -131,24 +131,6 @@ ResetShutdown ( ASSERT (FALSE); } -/** - Calling this function causes the system to enter a power state for capsule - update. - - Reset update should not return, if it returns, it means the system does - not support capsule update. - -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - AcpiPmControl (5); - ASSERT (FALSE); -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed From 2d9950a2bff892667510e7a00e3ad8ead295a96f Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 16:03:33 +0100 Subject: [PATCH 330/384] OvmfPkg: remove EnterS3WithImmediateWake () from ResetSystemLib EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Signed-off-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek --- .../Library/ResetSystemLib/ResetSystemLib.c | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/OvmfPkg/Library/ResetSystemLib/ResetSystemLib.c b/OvmfPkg/Library/ResetSystemLib/ResetSystemLib.c index 98dd80e33c0..2f2e1293a3e 100644 --- a/OvmfPkg/Library/ResetSystemLib/ResetSystemLib.c +++ b/OvmfPkg/Library/ResetSystemLib/ResetSystemLib.c @@ -101,24 +101,6 @@ ResetShutdown ( } -/** - Calling this function causes the system to enter a power state for capsule - update. - - Reset update should not return, if it returns, it means the system does - not support capsule update. - -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - AcpiPmControl (1); - ASSERT (FALSE); -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed From 9d1c9d0379d065ca11bc3354faee2c742e89c005 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 16:04:36 +0100 Subject: [PATCH 331/384] ArmVirtPkg: remove EnterS3WithImmediateWake () from ResetSystemLib EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Signed-off-by: Ard Biesheuvel Reviewed-by: Laszlo Ersek --- .../ArmVirtPsciResetSystemLib.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c b/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c index fdf49e1d9c7..9e5b70e2c54 100644 --- a/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c +++ b/ArmVirtPkg/Library/ArmVirtPsciResetSystemLib/ArmVirtPsciResetSystemLib.c @@ -145,20 +145,6 @@ ResetShutdown ( } } -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - // not implemented -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed From 953260bd5037e21fcd226f18f8e62f71e7e85142 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 10 Jan 2020 15:37:12 -0800 Subject: [PATCH 332/384] Fix compat between teardown functions and Cmocka. --- MdePkg/Include/Library/UnitTestLib.h | 6 +++++- .../Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 8151cab8c87..ddec45dd792 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -15,6 +15,7 @@ typedef UINT32 UNIT_TEST_STATUS; #define UNIT_TEST_PASSED (0) #define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) #define UNIT_TEST_ERROR_TEST_FAILED (2) +#define UNIT_TEST_ERROR_CLEANUP_FAILED (3) #define UNIT_TEST_SKIPPED (0xFFFFFFFD) #define UNIT_TEST_RUNNING (0xFFFFFFFE) #define UNIT_TEST_PENDING (0xFFFFFFFF) @@ -81,9 +82,12 @@ UNIT_TEST_STATUS @param[in] Framework Identical to UNIT_TEST_FUNCTION. @param[in] Context Identical to UNIT_TEST_FUNCTION. + @retval UNIT_TEST_PASSED Test case cleanup succeeded. + @retval UNIT_TEST_ERROR_CLEANUP_FAILED Test case cleanup failed. + **/ typedef -VOID +UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_CLEANUP)( UNIT_TEST_FRAMEWORK_HANDLE Framework, UNIT_TEST_CONTEXT Context diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 300e04ad454..6dc6375f90f 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -46,7 +46,7 @@ MakeSureThatPointerIsNull ( } // ListsShouldHaveTheSameDescriptorSize() -VOID +UNIT_TEST_STATUS EFIAPI ClearThePointer ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, @@ -54,7 +54,7 @@ ClearThePointer ( ) { mSampleGlobalTestPointer = NULL; - return; + return (mSampleGlobalTestPointer == NULL) ? UNIT_TEST_PASSED : UNIT_TEST_ERROR_CLEANUP_FAILED; } // ClearThePointer() From 269de47a141e824d5cb8f83e5e7e0a805e3e9998 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 10 Jan 2020 16:23:47 -0800 Subject: [PATCH 333/384] Standardize the AssertCmocka calls. --- .../Library/UnitTestLib/AssertCmocka.c | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c index 3fb2050e18d..f05bf8ea602 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -33,7 +33,7 @@ UnitTestAssertTrue ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_TRUE(%s:%x)", Description, Expression); - _assert_true (Expression, Description, FileName, (INT32)LineNumber); + _assert_true (Expression, TempStr, FileName, (INT32)LineNumber); return Expression; } @@ -52,7 +52,7 @@ UnitTestAssertFalse ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_FALSE(%s:%x)", Description, Expression); - _assert_true (!Expression, Description, FileName, (INT32)LineNumber); + _assert_true (!Expression, TempStr, FileName, (INT32)LineNumber); return !Expression; } @@ -71,7 +71,7 @@ UnitTestAssertNotEfiError ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EFI_ERROR(%s:%p)", Description, (void *)Status); - _assert_true (!EFI_ERROR (Status), Description, FileName, (INT32)LineNumber); + _assert_true (!EFI_ERROR (Status), TempStr, FileName, (INT32)LineNumber); return !EFI_ERROR (Status); } @@ -92,7 +92,7 @@ UnitTestAssertEqual ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + _assert_true ((ValueA == ValueB), TempStr, FileName, (INT32)LineNumber); return (ValueA == ValueB); } @@ -138,7 +138,7 @@ UnitTestAssertNotEqual ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_EQUAL(%s:%llx, %s:%llx)", DescriptionA, ValueA, DescriptionB, ValueB); - _assert_int_not_equal (ValueA, ValueB, FileName, (INT32)LineNumber); + _assert_true ((ValueA != ValueB), TempStr, FileName, (INT32)LineNumber); return (ValueA != ValueB); } @@ -158,7 +158,7 @@ UnitTestAssertStatusEqual ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_STATUS_EQUAL(%s:%p)", Description, (VOID *)Status); - _assert_int_equal (Status, Status, FileName, (INT32)LineNumber); + _assert_true ((Status == Expected), TempStr, FileName, (INT32)LineNumber); return (Status == Expected); } @@ -177,7 +177,7 @@ UnitTestAssertNotNull ( CHAR8 TempStr[MAX_STRING_SIZE]; snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_NOT_NULL(%s:%p)", PointerName, Pointer); - _assert_true (Pointer != NULL, TempStr, FileName, (INT32)LineNumber); + _assert_true ((Pointer != NULL), TempStr, FileName, (INT32)LineNumber); return (Pointer != NULL); } From 38c56a391f7ccf6900d0dbb09811903b9552a03c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 11 Jan 2020 14:55:19 -0800 Subject: [PATCH 334/384] MdePkg/Include/Library: Rollback UnitTestLib change Signed-off-by: Michael D Kinney --- MdePkg/Include/Library/UnitTestLib.h | 2 +- .../Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c | 3 +-- 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index ddec45dd792..07c7897461b 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -87,7 +87,7 @@ UNIT_TEST_STATUS **/ typedef -UNIT_TEST_STATUS +VOID (EFIAPI *UNIT_TEST_CLEANUP)( UNIT_TEST_FRAMEWORK_HANDLE Framework, UNIT_TEST_CONTEXT Context diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 6dc6375f90f..7c30596d03d 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -46,7 +46,7 @@ MakeSureThatPointerIsNull ( } // ListsShouldHaveTheSameDescriptorSize() -UNIT_TEST_STATUS +VOID EFIAPI ClearThePointer ( IN UNIT_TEST_FRAMEWORK_HANDLE Framework, @@ -54,7 +54,6 @@ ClearThePointer ( ) { mSampleGlobalTestPointer = NULL; - return (mSampleGlobalTestPointer == NULL) ? UNIT_TEST_PASSED : UNIT_TEST_ERROR_CLEANUP_FAILED; } // ClearThePointer() From 05c517fc2ca63f3564b255e4fc2ffc891b616102 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 11 Jan 2020 14:54:50 -0800 Subject: [PATCH 335/384] UnitTestFrameworkPkg/UnitTestLib: Add cmocka gasket Add gasket between UnitTestLib unit tests APIs and the cmocka unit test APIs. Signed-off-by: Michael D Kinney --- .../Library/UnitTestLib/RunTestsCmocka.c | 135 ++++++++++++++++-- 1 file changed, 125 insertions(+), 10 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 911dda49d4c..8ca77fec65d 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -21,6 +21,123 @@ #include #include +// +// The currently active test suite +// +UNIT_TEST_SUITE *mActiveUnitTestSuite = NULL; + +void +CmockaUnitTestFunctionRunner ( + void **state + ) +{ + UNIT_TEST *UnitTest; + UNIT_TEST_SUITE *Suite; + UNIT_TEST_FRAMEWORK *Framework; + + UnitTest = (UNIT_TEST *)(*state); + Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); + Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); + + if (UnitTest->RunTest == NULL) { + UnitTest->Result = UNIT_TEST_SKIPPED; + } else { + UnitTest->Result = UNIT_TEST_RUNNING; + UnitTest->Result = UnitTest->RunTest (Framework, UnitTest->Context); + } +} + +int +CmockaUnitTestSetupFunctionRunner ( + void **state + ) +{ + UNIT_TEST *UnitTest; + UNIT_TEST_SUITE *Suite; + UNIT_TEST_FRAMEWORK *Framework; + UNIT_TEST_STATUS Result; + + UnitTest = (UNIT_TEST *)(*state); + Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); + Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); + + if (UnitTest->PreReq == NULL) { + return 0; + } + Result = UnitTest->PreReq (Framework, UnitTest->Context); + // + // Return 0 for success. Non-zero for error. + // + return (int)Result; +} + +int +CmockaUnitTestTeardownFunctionRunner ( + void **state + ) +{ + UNIT_TEST *UnitTest; + UNIT_TEST_SUITE *Suite; + UNIT_TEST_FRAMEWORK *Framework; + + UnitTest = (UNIT_TEST *)(*state); + Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); + Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); + + if (UnitTest->CleanUp == NULL) { + return 0; + } + UnitTest->CleanUp (Framework, UnitTest->Context); + // + // Return 0 for success. Non-zero for error. + // + return 0; +} + +int +CmockaUnitTestSuiteSetupFunctionRunner ( + void **state + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + + if (mActiveUnitTestSuite == NULL) { + return -1; + } + if (mActiveUnitTestSuite->Setup == NULL) { + return 0; + } + + Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); + mActiveUnitTestSuite->Setup (Framework); + // + // Always succeed + // + return 0; +} + +int +CmockaUnitTestSuiteTeardownFunctionRunner ( + void **state + ) +{ + UNIT_TEST_FRAMEWORK *Framework; + + if (mActiveUnitTestSuite == NULL) { + return -1; + } + if (mActiveUnitTestSuite->Teardown == NULL) { + return 0; + } + + Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); + mActiveUnitTestSuite->Teardown (Framework); + // + // Always succeed + // + return 0; +} + STATIC EFI_STATUS RunTestSuite ( @@ -42,10 +159,6 @@ RunTestSuite ( DEBUG ((DEBUG_VERBOSE, "RUNNING TEST SUITE: %a\n", Suite->Title)); DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - if (Suite->Setup != NULL) { - Suite->Setup (Suite->ParentFramework); - } - // // Alocate buffer of CMUnitTest entries // @@ -61,10 +174,10 @@ RunTestSuite ( TestEntry = (UNIT_TEST_LIST_ENTRY *)GetNextNode (&(Suite->TestCaseList), (LIST_ENTRY *)TestEntry)) { UnitTest = &TestEntry->UT; Tests[Index].name = UnitTest->Description; - Tests[Index].test_func = (CMUnitTestFunction)(UnitTest->RunTest); - Tests[Index].setup_func = (CMFixtureFunction)(UnitTest->PreReq); - Tests[Index].teardown_func = (CMFixtureFunction)(UnitTest->CleanUp); - Tests[Index].initial_state = NULL; + Tests[Index].test_func = CmockaUnitTestFunctionRunner; + Tests[Index].setup_func = CmockaUnitTestSetupFunctionRunner; + Tests[Index].teardown_func = CmockaUnitTestTeardownFunctionRunner; + Tests[Index].initial_state = UnitTest; Index++; } ASSERT (Index == Suite->NumTests); @@ -72,13 +185,15 @@ RunTestSuite ( // // Run all unit tests in a test suite // + mActiveUnitTestSuite = Suite; _cmocka_run_group_tests ( Suite->Title, Tests, Suite->NumTests, - (CMFixtureFunction)(Suite->Setup), - (CMFixtureFunction)(Suite->Teardown) + CmockaUnitTestSuiteSetupFunctionRunner, + CmockaUnitTestSuiteTeardownFunctionRunner ); + mActiveUnitTestSuite = NULL; FreePool (Tests); return EFI_SUCCESS; From 27f44ea1fb72beffbef0ef851d361a7550189d1b Mon Sep 17 00:00:00 2001 From: "Albecki, Mateusz" Date: Fri, 10 Jan 2020 18:26:11 +0800 Subject: [PATCH 336/384] MdeModulePkg/SdMmcPciHcDxe: Fix unknown doxygen tag error Changed @rtval to @retval in SdMmcHcStartSdClock function description. Signed-off-by: Mateusz Albecki Reviewed-by: Hao A Wu --- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c | 2 +- MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c index e7f2fac69b6..d1e60938f96 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.c @@ -765,7 +765,7 @@ SdMmcHcStopClock ( @param[in] Slot The slot number. @retval EFI_SUCCESS Succeeded to start the SD clock. - @rtval Others Failed to start the SD clock. + @retval Others Failed to start the SD clock. **/ EFI_STATUS SdMmcHcStartSdClock ( diff --git a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h index 4753bb68643..16229a846cc 100644 --- a/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h +++ b/MdeModulePkg/Bus/Pci/SdMmcPciHcDxe/SdMmcPciHci.h @@ -485,7 +485,7 @@ SdMmcHcStopClock ( @param[in] Slot The slot number. @retval EFI_SUCCESS Succeeded to start the SD clock. - @rtval Others Failed to start the SD clock. + @retval Others Failed to start the SD clock. **/ EFI_STATUS SdMmcHcStartSdClock ( From 072b9c28393d191733187e701307cdab166a4c4d Mon Sep 17 00:00:00 2001 From: "Fan, ZhijuX" Date: Fri, 10 Jan 2020 16:37:46 +0800 Subject: [PATCH 337/384] BaseTools:Change the case rules for ECC check pointer names BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2087 In CryptHkdf.c line 42 EVP_PKEY_CTX *pHkdfCtx; Variable pHkdfCtx begins with lower case 'p', which should be acceptable because it it is a pointer. (Refer to CCS_2_1_Draft, 4.3.3.3) So ECC tool should be improved to handle issues like this. Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng Signed-off-by: Zhiju.Fan --- BaseTools/Source/Python/Ecc/Check.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/BaseTools/Source/Python/Ecc/Check.py b/BaseTools/Source/Python/Ecc/Check.py index b68cecddfd4..0fdc7e35c18 100644 --- a/BaseTools/Source/Python/Ecc/Check.py +++ b/BaseTools/Source/Python/Ecc/Check.py @@ -1,7 +1,7 @@ ## @file # This file is used to define checkpoints used by ECC tool # -# Copyright (c) 2008 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2008 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # from __future__ import absolute_import @@ -1469,13 +1469,14 @@ def NamingConventionCheckVariableName(self, FileTable): EdkLogger.quiet("Checking naming convention of variable name ...") Pattern = re.compile(r'^[A-Zgm]+\S*[a-z]\S*$') - SqlCommand = """select ID, Name from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_VARIABLE) + SqlCommand = """select ID, Name, Modifier from %s where Model = %s""" % (FileTable, MODEL_IDENTIFIER_VARIABLE) RecordSet = EccGlobalData.gDb.TblFile.Exec(SqlCommand) for Record in RecordSet: Var = Record[1] + Modifier = Record[2] if Var.startswith('CONST'): Var = Var[5:].lstrip() - if not Pattern.match(Var): + if not Pattern.match(Var) and not (Modifier.endswith('*') and Var.startswith('p')): if not EccGlobalData.gException.IsException(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, Record[1]): EccGlobalData.gDb.TblReport.Insert(ERROR_NAMING_CONVENTION_CHECK_VARIABLE_NAME, OtherMsg="The variable name [%s] does not follow the rules" % (Record[1]), BelongsToTable=FileTable, BelongsToItem=Record[0]) From 4465cd124fbcf5490faad6a1a834299b30b5d009 Mon Sep 17 00:00:00 2001 From: "Fan, ZhijuX" Date: Fri, 10 Jan 2020 16:29:45 +0800 Subject: [PATCH 338/384] BaseTools:Fix GenFds issue for BuildOption replace GenFdsOption BZ:https://bugzilla.tianocore.org/show_bug.cgi?id=2455 BuildOption is used by TargetTxtClassObj.py GenFdsOption is used by GenFds.py When the GenFds tool is used alone (e.g. python3 -m GenFds.GenFds -h) With the OptionParser function, the first detected function prints the help message import TargetTxtClassObj to GenFds, The BuildOption will be executed and replace GenFdsOption We removed all objects associated with this problem that were created directly during the import process (e.g. BuildOption, BuildTarget = MyOptionParser(), TargetTxt = TargetTxtDict()) The Patch is going to fix this issue Signed-off-by: Zhiju.Fan Cc: Liming Gao Cc: Bob Feng Reviewed-by: Bob Feng --- .../Source/Python/AutoGen/BuildEngine.py | 56 ++++++---- BaseTools/Source/Python/Common/GlobalData.py | 2 +- .../Python/Common/TargetTxtClassObject.py | 64 +++++++---- .../Python/Common/ToolDefClassObject.py | 48 +++++--- .../Source/Python/Common/buildoptions.py | 93 ---------------- BaseTools/Source/Python/GenFds/GenFds.py | 4 +- .../Python/GenFds/GenFdsGlobalVariable.py | 17 ++- .../Source/Python/Workspace/DscBuildData.py | 9 +- BaseTools/Source/Python/build/build.py | 32 ++++-- BaseTools/Source/Python/build/buildoptions.py | 105 ++++++++++++++++++ 10 files changed, 261 insertions(+), 169 deletions(-) delete mode 100644 BaseTools/Source/Python/Common/buildoptions.py create mode 100644 BaseTools/Source/Python/build/buildoptions.py diff --git a/BaseTools/Source/Python/AutoGen/BuildEngine.py b/BaseTools/Source/Python/AutoGen/BuildEngine.py index 069a3a1c9db..d602414ca41 100644 --- a/BaseTools/Source/Python/AutoGen/BuildEngine.py +++ b/BaseTools/Source/Python/AutoGen/BuildEngine.py @@ -20,7 +20,7 @@ from Common.Misc import tdict, PathClass from Common.StringUtils import NormPath from Common.DataType import * -from Common.TargetTxtClassObject import TargetTxt +from Common.TargetTxtClassObject import TargetTxtDict gDefaultBuildRuleFile = 'build_rule.txt' AutoGenReqBuildRuleVerNum = '0.1' @@ -588,24 +588,42 @@ def __getitem__(self, Key): _UnknownSection : SkipSection, } -def GetBuildRule(): - BuildRuleFile = None - if TAB_TAT_DEFINES_BUILD_RULE_CONF in TargetTxt.TargetTxtDictionary: - BuildRuleFile = TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF] - if not BuildRuleFile: - BuildRuleFile = gDefaultBuildRuleFile - RetVal = BuildRule(BuildRuleFile) - if RetVal._FileVersion == "": - RetVal._FileVersion = AutoGenReqBuildRuleVerNum - else: - if RetVal._FileVersion < AutoGenReqBuildRuleVerNum : - # If Build Rule's version is less than the version number required by the tools, halting the build. - EdkLogger.error("build", AUTOGEN_ERROR, - ExtraData="The version number [%s] of build_rule.txt is less than the version number required by the AutoGen.(the minimum required version number is [%s])"\ - % (RetVal._FileVersion, AutoGenReqBuildRuleVerNum)) - return RetVal - -BuildRuleObj = GetBuildRule() +class ToolBuildRule(): + + def __new__(cls, *args, **kw): + if not hasattr(cls, '_instance'): + orig = super(ToolBuildRule, cls) + cls._instance = orig.__new__(cls, *args, **kw) + return cls._instance + + def __init__(self): + if not hasattr(self, 'ToolBuildRule'): + self._ToolBuildRule = None + + @property + def ToolBuildRule(self): + if not self._ToolBuildRule: + self._GetBuildRule() + return self._ToolBuildRule + + def _GetBuildRule(self): + BuildRuleFile = None + TargetObj = TargetTxtDict() + TargetTxt = TargetObj.Target + if TAB_TAT_DEFINES_BUILD_RULE_CONF in TargetTxt.TargetTxtDictionary: + BuildRuleFile = TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_BUILD_RULE_CONF] + if not BuildRuleFile: + BuildRuleFile = gDefaultBuildRuleFile + RetVal = BuildRule(BuildRuleFile) + if RetVal._FileVersion == "": + RetVal._FileVersion = AutoGenReqBuildRuleVerNum + else: + if RetVal._FileVersion < AutoGenReqBuildRuleVerNum : + # If Build Rule's version is less than the version number required by the tools, halting the build. + EdkLogger.error("build", AUTOGEN_ERROR, + ExtraData="The version number [%s] of build_rule.txt is less than the version number required by the AutoGen.(the minimum required version number is [%s])"\ + % (RetVal._FileVersion, AutoGenReqBuildRuleVerNum)) + self._ToolBuildRule = RetVal # This acts like the main() function for the script, unless it is 'import'ed into another # script. diff --git a/BaseTools/Source/Python/Common/GlobalData.py b/BaseTools/Source/Python/Common/GlobalData.py index 0b3ebe035d1..8ac29eb7a6f 100755 --- a/BaseTools/Source/Python/Common/GlobalData.py +++ b/BaseTools/Source/Python/Common/GlobalData.py @@ -70,7 +70,7 @@ # The Conf dir outside the workspace dir # gConfDirectory = '' - +gCmdConfDir = '' gBuildDirectory = '' # # The relative default database file path diff --git a/BaseTools/Source/Python/Common/TargetTxtClassObject.py b/BaseTools/Source/Python/Common/TargetTxtClassObject.py index 723b9405bf8..363c38302b8 100644 --- a/BaseTools/Source/Python/Common/TargetTxtClassObject.py +++ b/BaseTools/Source/Python/Common/TargetTxtClassObject.py @@ -10,7 +10,7 @@ # from __future__ import print_function from __future__ import absolute_import -from Common.buildoptions import BuildOption,BuildTarget + import Common.GlobalData as GlobalData import Common.LongFilePathOs as os from . import EdkLogger @@ -144,29 +144,47 @@ def ConvertTextFileToDict(self, FileName, CommentCharacter, KeySplitCharacter): # # @retval Target An instance of TargetTxtClassObject() with loaded target.txt # -def TargetTxtDict(): - Target = TargetTxtClassObject() - if BuildOption.ConfDirectory: - # Get alternate Conf location, if it is absolute, then just use the absolute directory name - ConfDirectoryPath = os.path.normpath(BuildOption.ConfDirectory) - - if not os.path.isabs(ConfDirectoryPath): - # Since alternate directory name is not absolute, the alternate directory is located within the WORKSPACE - # This also handles someone specifying the Conf directory in the workspace. Using --conf=Conf - ConfDirectoryPath = mws.join(os.environ["WORKSPACE"], ConfDirectoryPath) - else: - if "CONF_PATH" in os.environ: - ConfDirectoryPath = os.path.normcase(os.path.normpath(os.environ["CONF_PATH"])) + +class TargetTxtDict(): + + def __new__(cls, *args, **kw): + if not hasattr(cls, '_instance'): + orig = super(TargetTxtDict, cls) + cls._instance = orig.__new__(cls, *args, **kw) + return cls._instance + + def __init__(self): + if not hasattr(self, 'Target'): + self.TxtTarget = None + + @property + def Target(self): + if not self.TxtTarget: + self._GetTarget() + return self.TxtTarget + + def _GetTarget(self): + Target = TargetTxtClassObject() + ConfDirectory = GlobalData.gCmdConfDir + if ConfDirectory: + # Get alternate Conf location, if it is absolute, then just use the absolute directory name + ConfDirectoryPath = os.path.normpath(ConfDirectory) + + if not os.path.isabs(ConfDirectoryPath): + # Since alternate directory name is not absolute, the alternate directory is located within the WORKSPACE + # This also handles someone specifying the Conf directory in the workspace. Using --conf=Conf + ConfDirectoryPath = mws.join(os.environ["WORKSPACE"], ConfDirectoryPath) else: - # Get standard WORKSPACE/Conf use the absolute path to the WORKSPACE/Conf - ConfDirectoryPath = mws.join(os.environ["WORKSPACE"], 'Conf') - GlobalData.gConfDirectory = ConfDirectoryPath - targettxt = os.path.normpath(os.path.join(ConfDirectoryPath, gDefaultTargetTxtFile)) - if os.path.exists(targettxt): - Target.LoadTargetTxtFile(targettxt) - return Target - -TargetTxt = TargetTxtDict() + if "CONF_PATH" in os.environ: + ConfDirectoryPath = os.path.normcase(os.path.normpath(os.environ["CONF_PATH"])) + else: + # Get standard WORKSPACE/Conf use the absolute path to the WORKSPACE/Conf + ConfDirectoryPath = mws.join(os.environ["WORKSPACE"], 'Conf') + GlobalData.gConfDirectory = ConfDirectoryPath + targettxt = os.path.normpath(os.path.join(ConfDirectoryPath, gDefaultTargetTxtFile)) + if os.path.exists(targettxt): + Target.LoadTargetTxtFile(targettxt) + self.TxtTarget = Target ## # diff --git a/BaseTools/Source/Python/Common/ToolDefClassObject.py b/BaseTools/Source/Python/Common/ToolDefClassObject.py index 063fa005840..8e70407cb9e 100644 --- a/BaseTools/Source/Python/Common/ToolDefClassObject.py +++ b/BaseTools/Source/Python/Common/ToolDefClassObject.py @@ -14,7 +14,7 @@ from . import EdkLogger from .BuildToolError import * -from Common.TargetTxtClassObject import TargetTxt +from Common.TargetTxtClassObject import TargetTxtDict from Common.LongFilePathSupport import OpenLongFilePath as open from Common.Misc import PathClass from Common.StringUtils import NormPath @@ -262,20 +262,40 @@ def ExpandMacros(self, Value): # # @retval ToolDef An instance of ToolDefClassObject() with loaded tools_def.txt # -def ToolDefDict(ConfDir): - Target = TargetTxt - ToolDef = ToolDefClassObject() - if TAB_TAT_DEFINES_TOOL_CHAIN_CONF in Target.TargetTxtDictionary: - ToolsDefFile = Target.TargetTxtDictionary[TAB_TAT_DEFINES_TOOL_CHAIN_CONF] - if ToolsDefFile: - ToolDef.LoadToolDefFile(os.path.normpath(ToolsDefFile)) - else: - ToolDef.LoadToolDefFile(os.path.normpath(os.path.join(ConfDir, gDefaultToolsDefFile))) - else: - ToolDef.LoadToolDefFile(os.path.normpath(os.path.join(ConfDir, gDefaultToolsDefFile))) - return ToolDef -ToolDef = ToolDefDict((os.path.join(os.getenv("WORKSPACE"),"Conf"))) + +class ToolDefDict(): + + def __new__(cls, ConfDir, *args, **kw): + if not hasattr(cls, '_instance'): + orig = super(ToolDefDict, cls) + cls._instance = orig.__new__(cls, *args, **kw) + return cls._instance + + def __init__(self, ConfDir): + self.ConfDir = ConfDir + if not hasattr(self, 'ToolDef'): + self._ToolDef = None + + @property + def ToolDef(self): + if not self._ToolDef: + self._GetToolDef() + return self._ToolDef + + def _GetToolDef(self): + TargetObj = TargetTxtDict() + Target = TargetObj.Target + ToolDef = ToolDefClassObject() + if TAB_TAT_DEFINES_TOOL_CHAIN_CONF in Target.TargetTxtDictionary: + ToolsDefFile = Target.TargetTxtDictionary[TAB_TAT_DEFINES_TOOL_CHAIN_CONF] + if ToolsDefFile: + ToolDef.LoadToolDefFile(os.path.normpath(ToolsDefFile)) + else: + ToolDef.LoadToolDefFile(os.path.normpath(os.path.join(self.ConfDir, gDefaultToolsDefFile))) + else: + ToolDef.LoadToolDefFile(os.path.normpath(os.path.join(self.ConfDir, gDefaultToolsDefFile))) + self._ToolDef = ToolDef ## # diff --git a/BaseTools/Source/Python/Common/buildoptions.py b/BaseTools/Source/Python/Common/buildoptions.py deleted file mode 100644 index a717c58d8c9..00000000000 --- a/BaseTools/Source/Python/Common/buildoptions.py +++ /dev/null @@ -1,93 +0,0 @@ -## @file -# build a platform or a module -# -# Copyright (c) 2014, Hewlett-Packard Development Company, L.P.
-# Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
-# Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.
-# -# SPDX-License-Identifier: BSD-2-Clause-Patent -# - -# Version and Copyright -from Common.BuildVersion import gBUILD_VERSION -from optparse import OptionParser -VersionNumber = "0.60" + ' ' + gBUILD_VERSION -__version__ = "%prog Version " + VersionNumber -__copyright__ = "Copyright (c) 2007 - 2018, Intel Corporation All rights reserved." - -gParamCheck = [] -def SingleCheckCallback(option, opt_str, value, parser): - if option not in gParamCheck: - setattr(parser.values, option.dest, value) - gParamCheck.append(option) - else: - parser.error("Option %s only allows one instance in command line!" % option) - -def MyOptionParser(): - Parser = OptionParser(description=__copyright__, version=__version__, prog="build.exe", usage="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]") - Parser.add_option("-a", "--arch", action="append", type="choice", choices=['IA32', 'X64', 'EBC', 'ARM', 'AARCH64'], dest="TargetArch", - help="ARCHS is one of list: IA32, X64, ARM, AARCH64 or EBC, which overrides target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option.") - Parser.add_option("-p", "--platform", action="callback", type="string", dest="PlatformFile", callback=SingleCheckCallback, - help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.") - Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback, - help="Build the module specified by the INF file name argument.") - Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.", - action="append") - Parser.add_option("-t", "--tagname", action="append", type="string", dest="ToolChain", - help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.") - Parser.add_option("-x", "--sku-id", action="callback", type="string", dest="SkuId", callback=SingleCheckCallback, - help="Using this name of SKU ID to build the platform, overriding SKUID_IDENTIFIER in DSC file.") - - Parser.add_option("-n", action="callback", type="int", dest="ThreadNumber", callback=SingleCheckCallback, - help="Build the platform using multi-threaded compiler. The value overrides target.txt's MAX_CONCURRENT_THREAD_NUMBER. When value is set to 0, tool automatically detect number of "\ - "processor threads, set value to 1 means disable multi-thread build, and set value to more than 1 means user specify the threads number to build.") - - Parser.add_option("-f", "--fdf", action="callback", type="string", dest="FdfFile", callback=SingleCheckCallback, - help="The name of the FDF file to use, which overrides the setting in the DSC file.") - Parser.add_option("-r", "--rom-image", action="append", type="string", dest="RomImage", default=[], - help="The name of FD to be generated. The name must be from [FD] section in FDF file.") - Parser.add_option("-i", "--fv-image", action="append", type="string", dest="FvImage", default=[], - help="The name of FV to be generated. The name must be from [FV] section in FDF file.") - Parser.add_option("-C", "--capsule-image", action="append", type="string", dest="CapName", default=[], - help="The name of Capsule to be generated. The name must be from [Capsule] section in FDF file.") - Parser.add_option("-u", "--skip-autogen", action="store_true", dest="SkipAutoGen", help="Skip AutoGen step.") - Parser.add_option("-e", "--re-parse", action="store_true", dest="Reparse", help="Re-parse all meta-data files.") - - Parser.add_option("-c", "--case-insensitive", action="store_true", dest="CaseInsensitive", default=False, help="Don't check case of file name.") - - Parser.add_option("-w", "--warning-as-error", action="store_true", dest="WarningAsError", help="Treat warning in tools as error.") - Parser.add_option("-j", "--log", action="store", dest="LogFile", help="Put log in specified file as well as on console.") - - Parser.add_option("-s", "--silent", action="store_true", type=None, dest="SilentMode", - help="Make use of silent mode of (n)make.") - Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.") - Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\ - "including library instances selected, final dependency expression, "\ - "and warning messages, etc.") - Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.") - Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".") - - Parser.add_option("-y", "--report-file", action="store", dest="ReportFile", help="Create/overwrite the report to the specified filename.") - Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD', 'LIBRARY', 'FLASH', 'DEPEX', 'BUILD_FLAGS', 'FIXED_ADDRESS', 'HASH', 'EXECUTION_ORDER'], dest="ReportType", default=[], - help="Flags that control the type of build report to generate. Must be one of: [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS, HASH, EXECUTION_ORDER]. "\ - "To specify more than one flag, repeat this option on the command line and the default flag set is [PCD, LIBRARY, FLASH, DEPEX, HASH, BUILD_FLAGS, FIXED_ADDRESS]") - Parser.add_option("-F", "--flag", action="store", type="string", dest="Flag", - help="Specify the specific option to parse EDK UNI file. Must be one of: [-c, -s]. -c is for EDK framework UNI file, and -s is for EDK UEFI UNI file. "\ - "This option can also be specified by setting *_*_*_BUILD_FLAGS in [BuildOptions] section of platform DSC. If they are both specified, this value "\ - "will override the setting in [BuildOptions] section of platform DSC.") - Parser.add_option("-N", "--no-cache", action="store_true", dest="DisableCache", default=False, help="Disable build cache mechanism") - Parser.add_option("--conf", action="store", type="string", dest="ConfDirectory", help="Specify the customized Conf directory.") - Parser.add_option("--check-usage", action="store_true", dest="CheckUsage", default=False, help="Check usage content of entries listed in INF file.") - Parser.add_option("--ignore-sources", action="store_true", dest="IgnoreSources", default=False, help="Focus to a binary build and ignore all source files") - Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ") - Parser.add_option("-l", "--cmd-len", action="store", type="int", dest="CommandLength", help="Specify the maximum line length of build command. Default is 4096.") - Parser.add_option("--hash", action="store_true", dest="UseHashCache", default=False, help="Enable hash-based caching during build process.") - Parser.add_option("--binary-destination", action="store", type="string", dest="BinCacheDest", help="Generate a cache of binary files in the specified directory.") - Parser.add_option("--binary-source", action="store", type="string", dest="BinCacheSource", help="Consume a cache of binary files from the specified directory.") - Parser.add_option("--genfds-multi-thread", action="store_true", dest="GenfdsMultiThread", default=True, help="Enable GenFds multi thread to generate ffs file.") - Parser.add_option("--no-genfds-multi-thread", action="store_true", dest="NoGenfdsMultiThread", default=False, help="Disable GenFds multi thread to generate ffs file.") - Parser.add_option("--disable-include-path-check", action="store_true", dest="DisableIncludePathCheck", default=False, help="Disable the include path check for outside of package.") - (Opt, Args) = Parser.parse_args() - return (Opt, Args) - -BuildOption, BuildTarget = MyOptionParser() diff --git a/BaseTools/Source/Python/GenFds/GenFds.py b/BaseTools/Source/Python/GenFds/GenFds.py index d8bc28e4d0f..d5511f4c40e 100644 --- a/BaseTools/Source/Python/GenFds/GenFds.py +++ b/BaseTools/Source/Python/GenFds/GenFds.py @@ -20,7 +20,7 @@ from io import BytesIO import Common.LongFilePathOs as os -from Common.TargetTxtClassObject import TargetTxt +from Common.TargetTxtClassObject import TargetTxtDict from Common.DataType import * import Common.GlobalData as GlobalData from Common import EdkLogger @@ -210,6 +210,8 @@ def GenFdsApi(FdsCommandDict, WorkSpaceDataBase=None): BuildConfigurationFile = os.path.normpath(os.path.join(ConfDirectoryPath, "target.txt")) if os.path.isfile(BuildConfigurationFile) == True: # if no build target given in command line, get it from target.txt + TargetObj = TargetTxtDict() + TargetTxt = TargetObj.Target if not GenFdsGlobalVariable.TargetName: BuildTargetList = TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_TARGET] if len(BuildTargetList) != 1: diff --git a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py index 6e1ff7fe04b..dc1727c4666 100644 --- a/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py +++ b/BaseTools/Source/Python/GenFds/GenFdsGlobalVariable.py @@ -23,9 +23,9 @@ from Common import EdkLogger from Common.Misc import SaveFileOnChange -from Common.TargetTxtClassObject import TargetTxt -from Common.ToolDefClassObject import ToolDef -from AutoGen.BuildEngine import BuildRuleObj +from Common.TargetTxtClassObject import TargetTxtDict +from Common.ToolDefClassObject import ToolDefDict +from AutoGen.BuildEngine import ToolBuildRule import Common.DataType as DataType from Common.Misc import PathClass from Common.LongFilePathSupport import OpenLongFilePath as open @@ -96,12 +96,15 @@ class GenFdsGlobalVariable: def _LoadBuildRule(): if GenFdsGlobalVariable.__BuildRuleDatabase: return GenFdsGlobalVariable.__BuildRuleDatabase - GenFdsGlobalVariable.__BuildRuleDatabase = BuildRuleObj - ToolDefinitionFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF] + BuildRule = ToolBuildRule() + GenFdsGlobalVariable.__BuildRuleDatabase = BuildRule.ToolBuildRule + TargetObj = TargetTxtDict() + ToolDefinitionFile = TargetObj.Target.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF] if ToolDefinitionFile == '': ToolDefinitionFile = "Conf/tools_def.txt" if os.path.isfile(ToolDefinitionFile): - ToolDefinition = ToolDef.ToolsDefTxtDatabase + ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf"))) + ToolDefinition = ToolDefObj.ToolDef.ToolsDefTxtDatabase if DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY in ToolDefinition \ and GenFdsGlobalVariable.ToolChainTag in ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY] \ and ToolDefinition[DataType.TAB_TOD_DEFINES_BUILDRULEFAMILY][GenFdsGlobalVariable.ToolChainTag]: @@ -830,6 +833,8 @@ def GetPcdValue (PcdPattern): # @param NameGuid The Guid name # def FindExtendTool(KeyStringList, CurrentArchList, NameGuid): + ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf"))) + ToolDef = ToolDefObj.ToolDef ToolDb = ToolDef.ToolsDefTxtDatabase # if user not specify filter, try to deduce it from global data. if KeyStringList is None or KeyStringList == []: diff --git a/BaseTools/Source/Python/Workspace/DscBuildData.py b/BaseTools/Source/Python/Workspace/DscBuildData.py index 03a15bbf3e1..c65a0dd346e 100644 --- a/BaseTools/Source/Python/Workspace/DscBuildData.py +++ b/BaseTools/Source/Python/Workspace/DscBuildData.py @@ -19,8 +19,8 @@ from types import * from Common.Expression import * from CommonDataClass.CommonClass import SkuInfoClass -from Common.TargetTxtClassObject import TargetTxt -from Common.ToolDefClassObject import ToolDef +from Common.TargetTxtClassObject import TargetTxtDict +from Common.ToolDefClassObject import ToolDefDict from .MetaDataTable import * from .MetaFileTable import * from .MetaFileParser import * @@ -3296,6 +3296,8 @@ def AddModule(self, FilePath): @property def ToolChainFamily(self): self._ToolChainFamily = TAB_COMPILER_MSFT + TargetObj = TargetTxtDict() + TargetTxt = TargetObj.Target BuildConfigurationFile = os.path.normpath(os.path.join(GlobalData.gConfDirectory, "target.txt")) if os.path.isfile(BuildConfigurationFile) == True: ToolDefinitionFile = TargetTxt.TargetTxtDictionary[DataType.TAB_TAT_DEFINES_TOOL_CHAIN_CONF] @@ -3303,7 +3305,8 @@ def ToolChainFamily(self): ToolDefinitionFile = "tools_def.txt" ToolDefinitionFile = os.path.normpath(mws.join(self.WorkspaceDir, 'Conf', ToolDefinitionFile)) if os.path.isfile(ToolDefinitionFile) == True: - ToolDefinition = ToolDef.ToolsDefTxtDatabase + ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf"))) + ToolDefinition = ToolDefObj.ToolDef.ToolsDefTxtDatabase if TAB_TOD_DEFINES_FAMILY not in ToolDefinition \ or self._Toolchain not in ToolDefinition[TAB_TOD_DEFINES_FAMILY] \ or not ToolDefinition[TAB_TOD_DEFINES_FAMILY][self._Toolchain]: diff --git a/BaseTools/Source/Python/build/build.py b/BaseTools/Source/Python/build/build.py index 3cc4220e2ff..34acdccbdbd 100755 --- a/BaseTools/Source/Python/build/build.py +++ b/BaseTools/Source/Python/build/build.py @@ -26,7 +26,7 @@ import threading from subprocess import Popen,PIPE, STDOUT from collections import OrderedDict, defaultdict -from Common.buildoptions import BuildOption,BuildTarget + from AutoGen.PlatformAutoGen import PlatformAutoGen from AutoGen.ModuleAutoGen import ModuleAutoGen from AutoGen.WorkspaceAutoGen import WorkspaceAutoGen @@ -35,8 +35,9 @@ from AutoGen import GenMake from Common import Misc as Utils -from Common.TargetTxtClassObject import TargetTxt -from Common.ToolDefClassObject import ToolDef +from Common.TargetTxtClassObject import TargetTxtDict +from Common.ToolDefClassObject import ToolDefDict +from buildoptions import MyOptionParser from Common.Misc import PathClass,SaveFileOnChange,RemoveDirectory from Common.StringUtils import NormPath from Common.MultipleWorkspace import MultipleWorkspace as mws @@ -731,11 +732,13 @@ def __init__(self, Target, WorkspaceDir, BuildOptions,log_q): self.ConfDirectory = BuildOptions.ConfDirectory self.SpawnMode = True self.BuildReport = BuildReport(BuildOptions.ReportFile, BuildOptions.ReportType) - self.TargetTxt = TargetTxt - self.ToolDef = ToolDef self.AutoGenTime = 0 self.MakeTime = 0 self.GenFdsTime = 0 + TargetObj = TargetTxtDict() + ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"),"Conf"))) + self.TargetTxt = TargetObj.Target + self.ToolDef = ToolDefObj.ToolDef GlobalData.BuildOptionPcd = BuildOptions.OptionPcd if BuildOptions.OptionPcd else [] #Set global flag for build mode GlobalData.gIgnoreSource = BuildOptions.IgnoreSources @@ -816,8 +819,10 @@ def __init__(self, Target, WorkspaceDir, BuildOptions,log_q): EdkLogger.quiet("%-16s = %s" % ("POSTBUILD", self.Postbuild)) if self.Prebuild: self.LaunchPrebuild() - self.TargetTxt = TargetTxt - self.ToolDef = ToolDef + TargetObj = TargetTxtDict() + ToolDefObj = ToolDefDict((os.path.join(os.getenv("WORKSPACE"), "Conf"))) + self.TargetTxt = TargetObj.Target + self.ToolDef = ToolDefObj.ToolDef if not (self.LaunchPrebuildFlag and os.path.exists(self.PlatformBuildPath)): self.InitBuild() @@ -2438,9 +2443,15 @@ def LogBuildTime(Time): else: return None def ThreadNum(): + OptionParser = MyOptionParser() + if not OptionParser.BuildOption and not OptionParser.BuildTarget: + OptionParser.GetOption() + BuildOption, BuildTarget = OptionParser.BuildOption, OptionParser.BuildTarget ThreadNumber = BuildOption.ThreadNumber + GlobalData.gCmdConfDir = BuildOption.ConfDirectory if ThreadNumber is None: - ThreadNumber = TargetTxt.TargetTxtDictionary[TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER] + TargetObj = TargetTxtDict() + ThreadNumber = TargetObj.Target.TargetTxtDictionary[TAB_TAT_DEFINES_MAX_CONCURRENT_THREAD_NUMBER] if ThreadNumber == '': ThreadNumber = 0 else: @@ -2475,7 +2486,10 @@ def Main(): # # Parse the options and args # - Option, Target = BuildOption, BuildTarget + OptionParser = MyOptionParser() + if not OptionParser.BuildOption and not OptionParser.BuildTarget: + OptionParser.GetOption() + Option, Target = OptionParser.BuildOption, OptionParser.BuildTarget GlobalData.gOptions = Option GlobalData.gCaseInsensitive = Option.CaseInsensitive diff --git a/BaseTools/Source/Python/build/buildoptions.py b/BaseTools/Source/Python/build/buildoptions.py new file mode 100644 index 00000000000..61ab2db9a4c --- /dev/null +++ b/BaseTools/Source/Python/build/buildoptions.py @@ -0,0 +1,105 @@ +## @file +# build a platform or a module +# +# Copyright (c) 2014, Hewlett-Packard Development Company, L.P.
+# Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2018, Hewlett Packard Enterprise Development, L.P.
+# +# SPDX-License-Identifier: BSD-2-Clause-Patent +# + +# Version and Copyright +from Common.BuildVersion import gBUILD_VERSION +from optparse import OptionParser +VersionNumber = "0.60" + ' ' + gBUILD_VERSION +__version__ = "%prog Version " + VersionNumber +__copyright__ = "Copyright (c) 2007 - 2018, Intel Corporation All rights reserved." + +gParamCheck = [] +def SingleCheckCallback(option, opt_str, value, parser): + if option not in gParamCheck: + setattr(parser.values, option.dest, value) + gParamCheck.append(option) + else: + parser.error("Option %s only allows one instance in command line!" % option) + + +class MyOptionParser(): + + def __new__(cls, *args, **kw): + if not hasattr(cls, '_instance'): + orig = super(MyOptionParser, cls) + cls._instance = orig.__new__(cls, *args, **kw) + return cls._instance + + def __init__(self): + if not hasattr(self, 'BuildOption'): + self.BuildOption = None + if not hasattr(self, 'BuildTarget'): + self.BuildTarget = None + + def GetOption(self): + Parser = OptionParser(description=__copyright__, version=__version__, prog="build.exe", usage="%prog [options] [all|fds|genc|genmake|clean|cleanall|cleanlib|modules|libraries|run]") + Parser.add_option("-a", "--arch", action="append", type="choice", choices=['IA32', 'X64', 'EBC', 'ARM', 'AARCH64'], dest="TargetArch", + help="ARCHS is one of list: IA32, X64, ARM, AARCH64 or EBC, which overrides target.txt's TARGET_ARCH definition. To specify more archs, please repeat this option.") + Parser.add_option("-p", "--platform", action="callback", type="string", dest="PlatformFile", callback=SingleCheckCallback, + help="Build the platform specified by the DSC file name argument, overriding target.txt's ACTIVE_PLATFORM definition.") + Parser.add_option("-m", "--module", action="callback", type="string", dest="ModuleFile", callback=SingleCheckCallback, + help="Build the module specified by the INF file name argument.") + Parser.add_option("-b", "--buildtarget", type="string", dest="BuildTarget", help="Using the TARGET to build the platform, overriding target.txt's TARGET definition.", + action="append") + Parser.add_option("-t", "--tagname", action="append", type="string", dest="ToolChain", + help="Using the Tool Chain Tagname to build the platform, overriding target.txt's TOOL_CHAIN_TAG definition.") + Parser.add_option("-x", "--sku-id", action="callback", type="string", dest="SkuId", callback=SingleCheckCallback, + help="Using this name of SKU ID to build the platform, overriding SKUID_IDENTIFIER in DSC file.") + + Parser.add_option("-n", action="callback", type="int", dest="ThreadNumber", callback=SingleCheckCallback, + help="Build the platform using multi-threaded compiler. The value overrides target.txt's MAX_CONCURRENT_THREAD_NUMBER. When value is set to 0, tool automatically detect number of "\ + "processor threads, set value to 1 means disable multi-thread build, and set value to more than 1 means user specify the threads number to build.") + + Parser.add_option("-f", "--fdf", action="callback", type="string", dest="FdfFile", callback=SingleCheckCallback, + help="The name of the FDF file to use, which overrides the setting in the DSC file.") + Parser.add_option("-r", "--rom-image", action="append", type="string", dest="RomImage", default=[], + help="The name of FD to be generated. The name must be from [FD] section in FDF file.") + Parser.add_option("-i", "--fv-image", action="append", type="string", dest="FvImage", default=[], + help="The name of FV to be generated. The name must be from [FV] section in FDF file.") + Parser.add_option("-C", "--capsule-image", action="append", type="string", dest="CapName", default=[], + help="The name of Capsule to be generated. The name must be from [Capsule] section in FDF file.") + Parser.add_option("-u", "--skip-autogen", action="store_true", dest="SkipAutoGen", help="Skip AutoGen step.") + Parser.add_option("-e", "--re-parse", action="store_true", dest="Reparse", help="Re-parse all meta-data files.") + + Parser.add_option("-c", "--case-insensitive", action="store_true", dest="CaseInsensitive", default=False, help="Don't check case of file name.") + + Parser.add_option("-w", "--warning-as-error", action="store_true", dest="WarningAsError", help="Treat warning in tools as error.") + Parser.add_option("-j", "--log", action="store", dest="LogFile", help="Put log in specified file as well as on console.") + + Parser.add_option("-s", "--silent", action="store_true", type=None, dest="SilentMode", + help="Make use of silent mode of (n)make.") + Parser.add_option("-q", "--quiet", action="store_true", type=None, help="Disable all messages except FATAL ERRORS.") + Parser.add_option("-v", "--verbose", action="store_true", type=None, help="Turn on verbose output with informational messages printed, "\ + "including library instances selected, final dependency expression, "\ + "and warning messages, etc.") + Parser.add_option("-d", "--debug", action="store", type="int", help="Enable debug messages at specified level.") + Parser.add_option("-D", "--define", action="append", type="string", dest="Macros", help="Macro: \"Name [= Value]\".") + + Parser.add_option("-y", "--report-file", action="store", dest="ReportFile", help="Create/overwrite the report to the specified filename.") + Parser.add_option("-Y", "--report-type", action="append", type="choice", choices=['PCD', 'LIBRARY', 'FLASH', 'DEPEX', 'BUILD_FLAGS', 'FIXED_ADDRESS', 'HASH', 'EXECUTION_ORDER'], dest="ReportType", default=[], + help="Flags that control the type of build report to generate. Must be one of: [PCD, LIBRARY, FLASH, DEPEX, BUILD_FLAGS, FIXED_ADDRESS, HASH, EXECUTION_ORDER]. "\ + "To specify more than one flag, repeat this option on the command line and the default flag set is [PCD, LIBRARY, FLASH, DEPEX, HASH, BUILD_FLAGS, FIXED_ADDRESS]") + Parser.add_option("-F", "--flag", action="store", type="string", dest="Flag", + help="Specify the specific option to parse EDK UNI file. Must be one of: [-c, -s]. -c is for EDK framework UNI file, and -s is for EDK UEFI UNI file. "\ + "This option can also be specified by setting *_*_*_BUILD_FLAGS in [BuildOptions] section of platform DSC. If they are both specified, this value "\ + "will override the setting in [BuildOptions] section of platform DSC.") + Parser.add_option("-N", "--no-cache", action="store_true", dest="DisableCache", default=False, help="Disable build cache mechanism") + Parser.add_option("--conf", action="store", type="string", dest="ConfDirectory", help="Specify the customized Conf directory.") + Parser.add_option("--check-usage", action="store_true", dest="CheckUsage", default=False, help="Check usage content of entries listed in INF file.") + Parser.add_option("--ignore-sources", action="store_true", dest="IgnoreSources", default=False, help="Focus to a binary build and ignore all source files") + Parser.add_option("--pcd", action="append", dest="OptionPcd", help="Set PCD value by command line. Format: \"PcdName=Value\" ") + Parser.add_option("-l", "--cmd-len", action="store", type="int", dest="CommandLength", help="Specify the maximum line length of build command. Default is 4096.") + Parser.add_option("--hash", action="store_true", dest="UseHashCache", default=False, help="Enable hash-based caching during build process.") + Parser.add_option("--binary-destination", action="store", type="string", dest="BinCacheDest", help="Generate a cache of binary files in the specified directory.") + Parser.add_option("--binary-source", action="store", type="string", dest="BinCacheSource", help="Consume a cache of binary files from the specified directory.") + Parser.add_option("--genfds-multi-thread", action="store_true", dest="GenfdsMultiThread", default=True, help="Enable GenFds multi thread to generate ffs file.") + Parser.add_option("--no-genfds-multi-thread", action="store_true", dest="NoGenfdsMultiThread", default=False, help="Disable GenFds multi thread to generate ffs file.") + Parser.add_option("--disable-include-path-check", action="store_true", dest="DisableIncludePathCheck", default=False, help="Disable the include path check for outside of package.") + self.BuildOption, self.BuildTarget = Parser.parse_args() From e8a1d85dfeb0796292097ee0568ecbee707dc86b Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Sun, 12 Jan 2020 19:48:02 -0800 Subject: [PATCH 339/384] Update Cmocka gasket to set the CurrentTest in the Framework so that Logs will work correctly. --- .../Library/UnitTestLib/RunTestsCmocka.c | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 8ca77fec65d..c208cd12151 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -39,11 +39,15 @@ CmockaUnitTestFunctionRunner ( Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); + if (UnitTest->RunTest == NULL) { UnitTest->Result = UNIT_TEST_SKIPPED; } else { UnitTest->Result = UNIT_TEST_RUNNING; + + Framework->CurrentTest = UnitTest; UnitTest->Result = UnitTest->RunTest (Framework, UnitTest->Context); + Framework->CurrentTest = NULL; } } @@ -64,7 +68,11 @@ CmockaUnitTestSetupFunctionRunner ( if (UnitTest->PreReq == NULL) { return 0; } + + Framework->CurrentTest = UnitTest; Result = UnitTest->PreReq (Framework, UnitTest->Context); + Framework->CurrentTest = NULL; + // // Return 0 for success. Non-zero for error. // @@ -84,10 +92,14 @@ CmockaUnitTestTeardownFunctionRunner ( Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); + if (UnitTest->CleanUp == NULL) { return 0; } + + Framework->CurrentTest = UnitTest; UnitTest->CleanUp (Framework, UnitTest->Context); + Framework->CurrentTest = NULL; // // Return 0 for success. Non-zero for error. // From 46ad45e6954228deedc18dacefde1cfca09c26a4 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Sun, 12 Jan 2020 19:48:14 -0800 Subject: [PATCH 340/384] Add a log message to the SampleUnitTest. --- .../Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 7c30596d03d..6d2ccdec686 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -109,6 +109,9 @@ GlobalPointerShouldBeChangeable ( IN UNIT_TEST_CONTEXT Context ) { + // Example of logging. + UT_LOG_WARNING("About to change a global pointer! Current value is 0x%X\n", mSampleGlobalTestPointer); + mSampleGlobalTestPointer = (VOID*)-1; UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); return UNIT_TEST_PASSED; From b112ec225f1c5f85b7b7db4110b4d4f1a0626d6b Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Thu, 9 Jan 2020 14:31:28 -0800 Subject: [PATCH 341/384] BaseTools/Scripts/PatchCheck: Address false error conditions https://bugzilla.tianocore.org/show_bug.cgi?id=2406 * Always print subject line after the git commit id to make it easier to know the context of warnings or errors. * Allow UTF-8 characters in subject line * Error if subject line length > 75 without CVE-xxx-xxxxx present * Error if subject line length > 92 with CVE-xxxx-xxxxx present * If body line length is > 75, then print warning instead of error. Cc: Bob Feng Cc: Liming Gao Cc: Laszlo Ersek Cc: Jordan Justen Signed-off-by: Michael D Kinney Reviewed-by: Bob Feng Tested-by: Laszlo Ersek --- BaseTools/Scripts/PatchCheck.py | 57 +++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/BaseTools/Scripts/PatchCheck.py b/BaseTools/Scripts/PatchCheck.py index fe8e6a64f2b..173d4517e0a 100755 --- a/BaseTools/Scripts/PatchCheck.py +++ b/BaseTools/Scripts/PatchCheck.py @@ -1,7 +1,7 @@ ## @file # Check a patch for various format issues # -# Copyright (c) 2015 - 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2015 - 2020, Intel Corporation. All rights reserved.
# Copyright (C) 2020, Red Hat, Inc.
# # SPDX-License-Identifier: BSD-2-Clause-Patent @@ -92,6 +92,8 @@ def __init__(self, subject, message): self.subject = subject self.msg = message + print (subject) + self.check_contributed_under() self.check_signed_off_by() self.check_misc_signatures() @@ -208,6 +210,8 @@ def check_misc_signatures(self): for sig in self.sig_types: self.find_signatures(sig) + cve_re = re.compile('CVE-[0-9]{4}-[0-9]{5}[^0-9]') + def check_overall_format(self): lines = self.msg.splitlines() @@ -225,9 +229,26 @@ def check_overall_format(self): self.error('Empty commit message!') return - if count >= 1 and len(lines[0].rstrip()) >= 72: - self.error('First line of commit message (subject line) ' + - 'is too long.') + if count >= 1 and re.search(self.cve_re, lines[0]): + # + # If CVE-xxxx-xxxxx is present in subject line, then limit length of + # subject line to 92 characters + # + if len(lines[0].rstrip()) >= 93: + self.error( + 'First line of commit message (subject line) is too long (%d >= 93).' % + (len(lines[0].rstrip())) + ) + else: + # + # If CVE-xxxx-xxxxx is not present in subject line, then limit + # length of subject line to 75 characters + # + if len(lines[0].rstrip()) >= 76: + self.error( + 'First line of commit message (subject line) is too long (%d >= 76).' % + (len(lines[0].rstrip())) + ) if count >= 1 and len(lines[0].strip()) == 0: self.error('First line of commit message (subject line) ' + @@ -241,7 +262,14 @@ def check_overall_format(self): if (len(lines[i]) >= 76 and len(lines[i].split()) > 1 and not lines[i].startswith('git-svn-id:')): - self.error('Line %d of commit message is too long.' % (i + 1)) + # + # Print a warning if body line is longer than 75 characters + # + print( + 'WARNING - Line %d of commit message is too long (%d >= 76).' % + (i + 1, len(lines[i])) + ) + print(lines[i]) last_sig_line = None for i in range(count - 1, 0, -1): @@ -535,8 +563,25 @@ def find_patch_pieces(self): else: self.stat = mo.group('stat') self.commit_msg = mo.group('commit_message') + # + # Parse subject line from email header. The subject line may be + # composed of multiple parts with different encodings. Decode and + # combine all the parts to produce a single string with the contents of + # the decoded subject line. + # + parts = email.header.decode_header(pmail.get('subject')) + subject = '' + for (part, encoding) in parts: + if encoding: + part = part.decode(encoding) + else: + try: + part = part.decode() + except: + pass + subject = subject + part - self.commit_subject = pmail['subject'].replace('\r\n', '') + self.commit_subject = subject.replace('\r\n', '') self.commit_subject = self.commit_subject.replace('\n', '') self.commit_subject = self.subject_prefix_re.sub('', self.commit_subject, 1) From 64c91e8ea433427e3311d6821e29b33d0ace887a Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Mon, 13 Jan 2020 10:32:40 -0800 Subject: [PATCH 342/384] Resolve Python 3.8 warnings. --- .pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py | 2 +- .pytool/Plugin/DependencyCheck/DependencyCheck.py | 2 +- .pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py | 2 +- .pytool/Plugin/GuidCheck/GuidCheck.py | 2 +- .../HostUnitTestDscCompleteCheck.py | 4 ++-- .pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) diff --git a/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py index 02f25ab19fd..1496e1f2493 100644 --- a/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py +++ b/.pytool/Plugin/CharEncodingCheck/CharEncodingCheck.py @@ -100,7 +100,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, overall_status += 1 tc.LogStdOut("Tested Encoding on {0} files".format(files_tested)) - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("CharEncoding {0} Failed. Errors {1}".format(packagename, overall_status), "CHAR_ENCODING_CHECK_FAILED") else: tc.SetSuccess() diff --git a/.pytool/Plugin/DependencyCheck/DependencyCheck.py b/.pytool/Plugin/DependencyCheck/DependencyCheck.py index 2c3d8baf698..db154d769a3 100644 --- a/.pytool/Plugin/DependencyCheck/DependencyCheck.py +++ b/.pytool/Plugin/DependencyCheck/DependencyCheck.py @@ -113,7 +113,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, overall_status += 1 # If XML object exists, add results - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("Failed with {0} errors".format(overall_status), "DEPENDENCYCHECK_FAILED") else: tc.SetSuccess() diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py index 9af4f72c8de..83f6221845f 100644 --- a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py @@ -111,7 +111,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, overall_status = overall_status + 1 # If XML object exists, add result - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("DscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") else: tc.SetSuccess() diff --git a/.pytool/Plugin/GuidCheck/GuidCheck.py b/.pytool/Plugin/GuidCheck/GuidCheck.py index f0b10beb1e8..61fdc779112 100644 --- a/.pytool/Plugin/GuidCheck/GuidCheck.py +++ b/.pytool/Plugin/GuidCheck/GuidCheck.py @@ -221,7 +221,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # add result to test case overall_status = len(Errors) - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("GuidCheck {0} Failed. Errors {1}".format( packagename, overall_status), "CHECK_FAILED") else: diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py index a0c7c269ef9..9dc9786a3ea 100644 --- a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py @@ -64,7 +64,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) - if abs_dsc_path is None or wsr_dsc_path is "" or not os.path.isfile(abs_dsc_path): + if abs_dsc_path is None or wsr_dsc_path == "" or not os.path.isfile(abs_dsc_path): tc.SetSkipped() tc.LogStdError("Package Host Unit Test Dsc not found") return 0 @@ -115,7 +115,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, overall_status = overall_status + 1 # If XML object exists, add result - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("HostUnitTestDscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") else: tc.SetSuccess() diff --git a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py index a62a7e912b1..20d87f13f52 100644 --- a/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py +++ b/.pytool/Plugin/LibraryClassCheck/LibraryClassCheck.py @@ -146,7 +146,7 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # If XML object exists, add result - if overall_status is not 0: + if overall_status != 0: tc.SetFailed("LibraryClassCheck {0} Failed. Errors {1}".format(wsr_dec_path, overall_status), "CHECK_FAILED") else: tc.SetSuccess() From a56af23f066e2816c67b7c6e64de7ddefcd70780 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Wed, 8 Jan 2020 21:19:35 +0100 Subject: [PATCH 343/384] MdeModulePkg/UefiBootManagerLib: log reserved mem allocation failure The LoadFile protocol can report such a large buffer size that we cannot allocate enough reserved pages for. This particularly affects HTTP(S) Boot, if the remote file is very large (for example, an ISO image). While the TianoCore wiki mentions this at : > The maximum RAM disk image size depends on how much continuous reserved > memory block the platform could provide. it's hard to remember; so log a DEBUG_ERROR message when the allocation fails. This patch produces error messages such as: > UiApp:BmExpandLoadFile: failed to allocate reserved pages: > BufferSize=4501536768 > LoadFile="PciRoot(0x0)/Pci(0x3,0x0)/MAC(5254001B103E,0x1)/ > IPv4(0.0.0.0,TCP,DHCP,192.168.124.106,192.168.124.1,255.255.255.0)/ > Dns(192.168.124.1)/ > Uri(https://ipv4-server/RHEL-7.7-20190723.1-Server-x86_64-dvd1.iso)" > FilePath="" (Manually rewrapped here for keeping PatchCheck.py happy.) Cc: Hao A Wu Cc: Jian J Wang Cc: Ray Ni Cc: Zhichao Gao Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Siyuan Fu Acked-by: Hao A Wu --- .../Library/UefiBootManagerLib/BmBoot.c | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c index 62c5b2dc94a..540d169ec1a 100644 --- a/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c +++ b/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c @@ -1387,6 +1387,37 @@ BmExpandLoadFile ( // FileBuffer = AllocateReservedPages (EFI_SIZE_TO_PAGES (BufferSize)); if (FileBuffer == NULL) { + DEBUG_CODE ( + EFI_DEVICE_PATH *LoadFilePath; + CHAR16 *LoadFileText; + CHAR16 *FileText; + + LoadFilePath = DevicePathFromHandle (LoadFileHandle); + if (LoadFilePath == NULL) { + LoadFileText = NULL; + } else { + LoadFileText = ConvertDevicePathToText (LoadFilePath, FALSE, FALSE); + } + FileText = ConvertDevicePathToText (FilePath, FALSE, FALSE); + + DEBUG (( + DEBUG_ERROR, + "%a:%a: failed to allocate reserved pages: " + "BufferSize=%Lu LoadFile=\"%s\" FilePath=\"%s\"\n", + gEfiCallerBaseName, + __FUNCTION__, + (UINT64)BufferSize, + LoadFileText, + FileText + )); + + if (FileText != NULL) { + FreePool (FileText); + } + if (LoadFileText != NULL) { + FreePool (LoadFileText); + } + ); return NULL; } From 4cca7923992a13f6b753782f469ee944da2db796 Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Wed, 8 Jan 2020 23:24:02 +0100 Subject: [PATCH 344/384] NetworkPkg/HttpDxe: fix 32-bit truncation in HTTPS download When downloading over TLS, each TLS message ("APP packet") is returned as a (decrypted) fragment table by EFI_TLS_PROTOCOL.ProcessPacket(). The TlsProcessMessage() function in "NetworkPkg/HttpDxe/HttpsSupport.c" linearizes the fragment table into a single contiguous data block. The resultant flat data block contains both TLS headers and data. The HttpsReceive() function parses the actual application data -- in this case: decrypted HTTP data -- out of the flattened TLS data block, peeling off the TLS headers. The HttpResponseWorker() function in "NetworkPkg/HttpDxe/HttpImpl.c" propagates this HTTP data outwards, implementing the EFI_HTTP_PROTOCOL.Response() function. Now consider the following documentation for EFI_HTTP_PROTOCOL.Response(), quoted from "MdePkg/Include/Protocol/Http.h": > It is the responsibility of the caller to allocate a buffer for Body and > specify the size in BodyLength. If the remote host provides a response > that contains a content body, up to BodyLength bytes will be copied from > the receive buffer into Body and BodyLength will be updated with the > amount of bytes received and copied to Body. This allows the client to > download a large file in chunks instead of into one contiguous block of > memory. Note that, if the caller-allocated buffer is larger than the server-provided chunk, then the transfer length is limited by the latter. This is in fact the dominant case when downloading a huge file (for which UefiBootManagerLib allocated a huge contiguous RAM Disk buffer) in small TLS messages. For adjusting BodyLength as described above -- i.e., to the application data chunk that has been extracted from the TLS message --, the HttpResponseWorker() function employs the following assignment: HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg->BodyLength); The (UINT32) cast is motivated by the MIN() requirement -- in "MdePkg/Include/Base.h" -- that both arguments be of the same type. "Fragment.Len" (NET_FRAGMENT.Len) has type UINT32, and "HttpMsg->BodyLength" (EFI_HTTP_MESSAGE.BodyLength) has type UINTN. Therefore a cast is indeed necessary. Unfortunately, the cast is done in the wrong direction. Consider the following circumstances: - "Fragment.Len" happens to be consistently 16KiB, dictated by the HTTPS Server's TLS stack, - the size of the file to download is 4GiB + N*16KiB, where N is a positive integer. As the download progresses, each received 16KiB application data chunk brings the *next* input value of BodyLength closer down to 4GiB. The cast in MIN() always masks off the high-order bits from the input value of BodyLength, but this is no problem because the low-order bits are nonzero, therefore the MIN() always permits progress. However, once BodyLength reaches 4GiB exactly on input, the MIN() invocation produces a zero value. HttpResponseWorker() adjusts the output value of BodyLength to zero, and then passes it to HttpParseMessageBody(). HttpParseMessageBody() (in "NetworkPkg/Library/DxeHttpLib/DxeHttpLib.c") rejects the zero BodyLength with EFI_INVALID_PARAMETER, which is fully propagated outwards, and aborts the HTTPS download. HttpBootDxe writes the message "Error: Unexpected network error" to the UEFI console. For example, a file with size (4GiB + 197MiB) terminates after downloading just 197MiB. Invert the direction of the cast: widen "Fragment.Len" to UINTN. Cc: Jiaxin Wu Cc: Maciej Rabeda Cc: Siyuan Fu Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Siyuan Fu Reviewed-by: Maciej Rabeda --- NetworkPkg/HttpDxe/HttpImpl.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/NetworkPkg/HttpDxe/HttpImpl.c b/NetworkPkg/HttpDxe/HttpImpl.c index 6b877314bd5..1acbb60d101 100644 --- a/NetworkPkg/HttpDxe/HttpImpl.c +++ b/NetworkPkg/HttpDxe/HttpImpl.c @@ -1348,7 +1348,7 @@ HttpResponseWorker ( // // Process the received the body packet. // - HttpMsg->BodyLength = MIN (Fragment.Len, (UINT32) HttpMsg->BodyLength); + HttpMsg->BodyLength = MIN ((UINTN) Fragment.Len, HttpMsg->BodyLength); CopyMem (HttpMsg->Body, Fragment.Bulk, HttpMsg->BodyLength); From f550dacf22772d79d091786ac151f521646d5e79 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 14 Jan 2020 13:42:15 -0800 Subject: [PATCH 345/384] Update DSC check and Host Dsc Check to align --- .../DscCompleteCheck/DscCompleteCheck.py | 33 +++++++++---- .pytool/Plugin/DscCompleteCheck/Readme.md | 7 ++- .../HostUnitTestDscCompleteCheck.py | 46 +++++++++++++------ .../HostUnitTestDscCompleteCheck/Readme.md | 32 +++++++++++++ 4 files changed, 94 insertions(+), 24 deletions(-) create mode 100644 .pytool/Plugin/HostUnitTestDscCompleteCheck/Readme.md diff --git a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py index 83f6221845f..c613cd52334 100644 --- a/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py +++ b/.pytool/Plugin/DscCompleteCheck/DscCompleteCheck.py @@ -54,12 +54,15 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Parse the config for required DscPath element if "DscPath" not in pkgconfig: tc.SetSkipped() - tc.LogStdError("DscPath not found in config file. Nothing to check.") + tc.LogStdError( + "DscPath not found in config file. Nothing to check.") return -1 - abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath( + packagename) abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) - wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) + wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath( + abs_dsc_path) if abs_dsc_path is None or wsr_dsc_path == "" or not os.path.isfile(abs_dsc_path): tc.SetSkipped() @@ -68,7 +71,8 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Get INF Files INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) - INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] # make edk2relative path so can compare with DSC + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath( + x) for x in INFFiles] # make edk2relative path so can compare with DSC # remove ignores @@ -79,8 +83,10 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, tc.LogStdOut("Ignoring INF {0}".format(a)) INFFiles.remove(a) except: - tc.LogStdError("DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) - logging.info("DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + tc.LogStdError( + "DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + logging.info( + "DscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) # DSC Parser dp = DscParser() @@ -99,11 +105,19 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, infp.SetPackagePaths(Edk2pathObj.PackagePathList) infp.ParseFile(INF) if("MODULE_TYPE" not in infp.Dict): - tc.LogStdOut("Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) + tc.LogStdOut( + "Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) continue if(infp.Dict["MODULE_TYPE"] == "HOST_APPLICATION"): - tc.LogStdOut("Ignoring INF. Module type is HOST_APPLICATION {0}".format(INF)) + tc.LogStdOut( + "Ignoring INF. Module type is HOST_APPLICATION {0}".format(INF)) + continue + + if len(infp.SupportedPhases) == 1 and \ + "HOST_APPLICATION" in infp.SupportedPhases: + tc.LogStdOut( + "Ignoring Library INF due to only supporting type HOST_APPLICATION {0}".format(INF)) continue logging.critical(INF + " not in " + wsr_dsc_path) @@ -112,7 +126,8 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # If XML object exists, add result if overall_status != 0: - tc.SetFailed("DscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") + tc.SetFailed("DscCompleteCheck {0} Failed. Errors {1}".format( + wsr_dsc_path, overall_status), "CHECK_FAILED") else: tc.SetSuccess() return overall_status diff --git a/.pytool/Plugin/DscCompleteCheck/Readme.md b/.pytool/Plugin/DscCompleteCheck/Readme.md index eefbb9894d5..8aaa4f76ee0 100644 --- a/.pytool/Plugin/DscCompleteCheck/Readme.md +++ b/.pytool/Plugin/DscCompleteCheck/Readme.md @@ -7,6 +7,11 @@ that it would not be built if the package were built). This is critical because much of the CI infrastructure assumes that all modules will be listed in the DSC and compiled. +This test will ignore INFs in the following cases: + +1. When MODULE_TYPE = HOST_APPLICATION +2. When a Library instance **only** supports the HOST_APPLICATION environment + ## Configuration The plugin has a few configuration options to support the UEFI codebase. @@ -14,7 +19,7 @@ The plugin has a few configuration options to support the UEFI codebase. ``` yaml "DscCompleteCheck": { "DscPath": "", # Path to dsc from root of package - "IgnoreInf": [] # Ignore INF if found in filesystem by not dsc + "IgnoreInf": [] # Ignore INF if found in filesystem but not dsc } ``` diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py index 9dc9786a3ea..79dffe8f7de 100644 --- a/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/HostUnitTestDscCompleteCheck.py @@ -21,8 +21,8 @@ class HostUnitTestDscCompleteCheck(ICiBuildPlugin): Configuration options: "HostUnitTestDscCompleteCheck": { - "DscPath": "" - "IgnoreInf": [] # Ignore INF if found in filesystem by not dsc + "DscPath": "", # Path to Host based unit test DSC file + "IgnoreInf": [] # Ignore INF if found in filesystem but not dsc } """ @@ -33,7 +33,7 @@ def GetTestName(self, packagename: str, environment: VarDict) -> tuple: packagename: string containing name of package to build environment: The VarDict for the test to run in Returns: - a tuple containing the testcase name and the classname + a tuple containing the testcase name and the classname (testcasename, classname) testclassname: a descriptive string for the testcase can include whitespace classname: should be patterned .. @@ -57,12 +57,15 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Parse the config for required DscPath element if "DscPath" not in pkgconfig: tc.SetSkipped() - tc.LogStdError("DscPath not found in config file. Nothing to check.") + tc.LogStdError( + "DscPath not found in config file. Nothing to check.") return -1 - abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath(packagename) + abs_pkg_path = Edk2pathObj.GetAbsolutePathOnThisSytemFromEdk2RelativePath( + packagename) abs_dsc_path = os.path.join(abs_pkg_path, pkgconfig["DscPath"].strip()) - wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(abs_dsc_path) + wsr_dsc_path = Edk2pathObj.GetEdk2RelativePathFromAbsolutePath( + abs_dsc_path) if abs_dsc_path is None or wsr_dsc_path == "" or not os.path.isfile(abs_dsc_path): tc.SetSkipped() @@ -71,7 +74,8 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # Get INF Files INFFiles = self.WalkDirectoryForExtension([".inf"], abs_pkg_path) - INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath(x) for x in INFFiles] # make edk2relative path so can compare with DSC + INFFiles = [Edk2pathObj.GetEdk2RelativePathFromAbsolutePath( + x) for x in INFFiles] # make edk2relative path so can compare with DSC # remove ignores @@ -82,8 +86,10 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, tc.LogStdOut("Ignoring INF {0}".format(a)) INFFiles.remove(a) except: - tc.LogStdError("HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) - logging.info("HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + tc.LogStdError( + "HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) + logging.info( + "HostUnitTestDscCompleteCheck.IgnoreInf -> {0} not found in filesystem. Invalid ignore file".format(a)) # DSC Parser dp = DscParser() @@ -102,13 +108,24 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, infp.SetPackagePaths(Edk2pathObj.PackagePathList) infp.ParseFile(INF) if("MODULE_TYPE" not in infp.Dict): - tc.LogStdOut("Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) + tc.LogStdOut( + "Ignoring INF. Missing key for MODULE_TYPE {0}".format(INF)) continue - if(infp.Dict["MODULE_TYPE"] != "HOST_APPLICATION"): - tc.LogStdOut("Ignoring INF. MODULE_TYPE is not HOST_APPLICATION {0}".format(INF)) - continue + if(infp.Dict["MODULE_TYPE"] == "HOST_APPLICATION"): + # should compile test a library that is declared type HOST_APPLICATION + pass + + elif len(infp.SupportedPhases) > 0 and \ + "HOST_APPLICATION" in infp.SupportedPhases: + # should compile test a library that supports HOST_APPLICATION but + # require it to be an explicit opt-in + pass + else: + tc.LogStdOut( + "Ignoring INF. MODULE_TYPE or suppored phases not HOST_APPLICATION {0}".format(INF)) + continue logging.critical(INF + " not in " + wsr_dsc_path) tc.LogStdError("{0} not in {1}".format(INF, wsr_dsc_path)) @@ -116,7 +133,8 @@ def RunBuildPlugin(self, packagename, Edk2pathObj, pkgconfig, environment, PLM, # If XML object exists, add result if overall_status != 0: - tc.SetFailed("HostUnitTestDscCompleteCheck {0} Failed. Errors {1}".format(wsr_dsc_path, overall_status), "CHECK_FAILED") + tc.SetFailed("HostUnitTestDscCompleteCheck {0} Failed. Errors {1}".format( + wsr_dsc_path, overall_status), "CHECK_FAILED") else: tc.SetSuccess() return overall_status diff --git a/.pytool/Plugin/HostUnitTestDscCompleteCheck/Readme.md b/.pytool/Plugin/HostUnitTestDscCompleteCheck/Readme.md new file mode 100644 index 00000000000..d77a1f2af18 --- /dev/null +++ b/.pytool/Plugin/HostUnitTestDscCompleteCheck/Readme.md @@ -0,0 +1,32 @@ +# Host Unit Test Dsc Complete Check Plugin + +This CiBuildPlugin scans all INF files from a package for those related to host +based unit tests confirms they are listed in the unit test DSC file for the package. +The test considers it an error if any INF meeting the requirements does not appear +in the `Components` section of the unit test DSC. This is critical because +much of the CI infrastructure assumes that modules will be listed in the DSC +and compiled. + +This test will only require INFs in the following cases: + +1. When MODULE_TYPE = HOST_APPLICATION +2. When a Library instance supports the HOST_APPLICATION environment + +## Configuration + +The plugin has a few configuration options to support the UEFI codebase. + +``` yaml +"HostUnitTestDscCompleteCheck": { + "DscPath": "", # Path to Host based unit test DSC file + "IgnoreInf": [] # Ignore INF if found in filesystem but not dsc +} +``` + +### DscPath + +Path to DSC to consider platform dsc + +### IgnoreInf + +Ignore error if Inf file is not listed in DSC file From c0d545c42d229537efbd1d869a3328b1b1c15936 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 14 Jan 2020 13:45:30 -0800 Subject: [PATCH 346/384] Fix spelling errors in UnitTestFrameworkPkg and fix other typos --- .../Posix/DebugLibPosix/DebugLibPosix.c | 28 ++++++------ .../MemoryAllocationLibPosix.c | 2 +- .../UnitTestBootLibNull/UnitTestBootLibNull.c | 4 +- .../UnitTestBootLibUsbClass.c | 6 +-- .../Library/UnitTestLib/RunTestsCmocka.c | 2 +- .../Library/UnitTestLib/UnitTestLib.c | 2 +- .../UnitTestResultReportLib.c | 4 +- .../PrivateInclude/Library/UnitTestBootLib.h | 2 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 2 +- UnitTestFrameworkPkg/ReadMe.md | 2 +- .../Test/UnitTestFrameworkPkgHostTest.dsc | 8 ++++ .../UnitTestFrameworkPkg.ci.yaml | 44 +++++++++++-------- 12 files changed, 61 insertions(+), 45 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c index 12115731998..acff80a05b5 100644 --- a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c @@ -114,8 +114,8 @@ DebugBPrint ( Print a message of the form "ASSERT (): \n" to the debug output device. If DEBUG_PROPERTY_ASSERT_BREAKPOINT_ENABLED bit of - PcdDebugProperyMask is set then CpuBreakpoint() is called. Otherwise, if - DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED bit of PcdDebugProperyMask is set then + PcdDebugPropertyMask is set then CpuBreakpoint() is called. Otherwise, if + DEBUG_PROPERTY_ASSERT_DEADLOOP_ENABLED bit of PcdDebugPropertyMask is set then CpuDeadLoop() is called. If neither of these bits are set, then this function returns immediately after the message is printed to the debug output device. DebugAssert() must actively prevent recursion. If DebugAssert() is called while @@ -186,10 +186,10 @@ DebugClearMemory ( Returns TRUE if ASSERT() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of - PcdDebugProperyMask is set. Otherwise FALSE is returned. + PcdDebugPropertyMask is set. Otherwise FALSE is returned. - @retval TRUE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is set. - @retval FALSE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugProperyMask is clear. + @retval TRUE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugPropertyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_ASSERT_ENABLED bit of PcdDebugPropertyMask is clear. **/ BOOLEAN @@ -205,10 +205,10 @@ DebugAssertEnabled ( Returns TRUE if DEBUG() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of - PcdDebugProperyMask is set. Otherwise FALSE is returned. + PcdDebugPropertyMask is set. Otherwise FALSE is returned. - @retval TRUE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is set. - @retval FALSE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugProperyMask is clear. + @retval TRUE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugPropertyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_PRINT_ENABLED bit of PcdDebugPropertyMask is clear. **/ BOOLEAN @@ -224,10 +224,10 @@ DebugPrintEnabled ( Returns TRUE if DEBUG_CODE() macros are enabled. This function returns TRUE if the DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of - PcdDebugProperyMask is set. Otherwise FALSE is returned. + PcdDebugPropertyMask is set. Otherwise FALSE is returned. - @retval TRUE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is set. - @retval FALSE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugProperyMask is clear. + @retval TRUE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugPropertyMask is set. + @retval FALSE The DEBUG_PROPERTY_DEBUG_CODE_ENABLED bit of PcdDebugPropertyMask is clear. **/ BOOLEAN @@ -243,10 +243,10 @@ DebugCodeEnabled ( Returns TRUE if DEBUG_CLEAR_MEMORY() macro is enabled. This function returns TRUE if the DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of - PcdDebugProperyMask is set. Otherwise FALSE is returned. + PcdDebugPropertyMask is set. Otherwise FALSE is returned. - @retval TRUE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is set. - @retval FALSE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugProperyMask is clear. + @retval TRUE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugPropertyMask is set. + @retval FALSE The DEBUG_PROPERTY_CLEAR_MEMORY_ENABLED bit of PcdDebugPropertyMask is clear. **/ BOOLEAN diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c index bb4700163c0..ec7b4e06e43 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c @@ -24,7 +24,7 @@ /// /// Structure placed immediately before an aligned allocation to store the /// information required to free the entire buffer allocated to support then -/// aligned alocation. +/// aligned allocation. /// typedef struct { UINT32 Signature; diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c index d457c9223dc..c5a5162c58f 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibNull/UnitTestBootLibNull.c @@ -1,5 +1,5 @@ /** - NULL implementation for UnitTestBootLib to allow simple compliation + NULL implementation for UnitTestBootLib to allow simple compilation Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -14,7 +14,7 @@ @retval EFI_SUCCESS Boot device for next boot was set. @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not supportted. - @retval Other Boot devide for next boot can not be set. + @retval Other Boot device for next boot can not be set. **/ EFI_STATUS EFIAPI diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c index f070d1bd551..95ad22c7ca9 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -21,7 +21,7 @@ @retval EFI_SUCCESS Boot device for next boot was set. @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not supportted. - @retval Other Boot devide for next boot can not be set. + @retval Other Boot device for next boot can not be set. **/ EFI_STATUS EFIAPI @@ -66,9 +66,9 @@ SetBootNextDevice ( goto CLEANUP; } - //@MRT --- Is this memory leak becasue we lose the old Dp memory + //@MRT --- Is this memory leak because we lose the old Dp memory Dp = AppendDevicePathNode ( - DpEnd, + DpEnd, (EFI_DEVICE_PATH_PROTOCOL *)&UsbDp ); if (Dp == NULL) { diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index c208cd12151..867995970d6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -172,7 +172,7 @@ RunTestSuite ( DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); // - // Alocate buffer of CMUnitTest entries + // Allocate buffer of CMUnitTest entries // Tests = AllocateZeroPool (Suite->NumTests * sizeof (struct CMUnitTest)); ASSERT (Tests != NULL); diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 8c507155dbb..2292e637aec 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -668,7 +668,7 @@ SerializeState ( // // Update the size once the structure is complete. - // NOTE: Should thise be a straight cast without validation? + // NOTE: Should this be a straight cast without validation? // TestSaveData->Size = (UINT32)(FloatingPointer - (UINT8 *)TestSaveData); } diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c index 2ee89bdf36a..30d4eb2dcc5 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -179,7 +179,7 @@ OutputUnitTestFrameworkReport ( switch (Test->UT.Result) { case UNIT_TEST_PASSED: - SPassed++; + SPassed++; break; case UNIT_TEST_ERROR_TEST_FAILED: SFailed++; @@ -204,7 +204,7 @@ OutputUnitTestFrameworkReport ( Passed += SPassed; //add to global counters Failed += SFailed; //add to global counters - NotRun += SNotRun; //add to global coutners + NotRun += SNotRun; //add to global counters }//End Suite iteration ReportPrint ("=========================================================\n"); diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h index 5f7b97d908d..d6819708156 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h @@ -20,7 +20,7 @@ @retval EFI_SUCCESS Boot device for next boot was set. @retval EFI_UNSUPPORTED Setting the boot device for the next boot is not supportted. - @retval Other Boot devide for next boot can not be set. + @retval Other Boot device for next boot can not be set. **/ EFI_STATUS EFIAPI diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 4d510347b43..49e38fedb34 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -82,7 +82,7 @@ typedef struct { typedef struct { CHAR8 *Title; - CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename charatecters. Is used in reporting and serialization. + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename characters. Is used in reporting and serialization. CHAR8 *VersionString; CHAR8 *Log; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index c4244c5f89d..9aa89ba2f3d 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -145,7 +145,7 @@ Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Samp This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and will be used when adding test cases. -Alrighty! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test +Great! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; a `CHAR16` string for the description and class name; a function pointer for the test case itself; additional, optional function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 2eb4167ee79..2bb8ff80120 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -22,3 +22,11 @@ # Build HOST_APPLICATION that tests the SampleUnitTest # UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf + + # + # Build Libraries + # + UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml index 370330c2cc0..01648595055 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.ci.yaml @@ -1,21 +1,24 @@ ## @file -# CI configuration for UnitTestPkg +# CI configuration for UnitTestFrameworkPkg # # Copyright (c) Microsoft Corporation # SPDX-License-Identifier: BSD-2-Clause-Patent ## { + ## options defined .pytool/Plugin/CompilerPlugin "CompilerPlugin": { "DscPath": "UnitTestFrameworkPkg.dsc" }, - ## options defined ci/Plugin/HostUnitTestCompilerPlugin + ## options defined .pytool/Plugin/HostUnitTestCompilerPlugin "HostUnitTestCompilerPlugin": { "DscPath": "Test/UnitTestFrameworkPkgHostTest.dsc" }, - + ## options defined .pytool/Plugin/CharEncodingCheck "CharEncodingCheck": { "IgnoreFiles": [] }, + + ## options defined .pytool/Plugin/DependencyCheck "DependencyCheck": { "AcceptableDependencies": [ "MdePkg/MdePkg.dec", @@ -30,38 +33,43 @@ ], "IgnoreInf": [] }, + ## options defined .pytool/Plugin/DscCompleteCheck "DscCompleteCheck": { "DscPath": "UnitTestFrameworkPkg.dsc", - "IgnoreInf": [ - # Don't need to build these. - # These are host-based only. - "UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf", - "UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf", - "UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf", - "UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf", - ] + "IgnoreInf": [] }, - ## options defined ci/Plugin/HostUnitTestDscCompleteCheck + ## options defined .pytool/Plugin/HostUnitTestDscCompleteCheck "HostUnitTestDscCompleteCheck": { - "IgnoreInf": [""], + "IgnoreInf": [], "DscPath": "Test/UnitTestFrameworkPkgHostTest.dsc" }, - + ## options defined .pytool/Plugin/GuidCheck "GuidCheck": { "IgnoreGuidName": [], "IgnoreGuidValue": [], "IgnoreFoldersAndFiles": [], "IgnoreDuplicates": [] }, + ## options defined .pytool/Plugin/LibraryClassCheck "LibraryClassCheck": { "IgnoreHeaderFile": [] }, - ## options defined ci/Plugin/SpellCheck + ## options defined .pytool/Plugin/SpellCheck "SpellCheck": { - "AuditOnly": True, # Fails test but run in AuditOnly mode to collect log - "IgnoreFiles": [], # use gitignore syntax to ignore errors in matching files - "ExtendWords": [], # words to extend to the dictionary for this package + "AuditOnly": False, # Fails test but run in AuditOnly mode to collect log + "IgnoreFiles": [ # use gitignore syntax to ignore errors in matching files + "/Library/CmockaLib/cmocka/**/*.*" # not going to spell check a submodule + ], + "ExtendWords": [ # words to extend to the dictionary for this package + "cmocka", + "buildmodule", + "criterium", + "pytool", + "pytools", + "NOFAILURE", + "DHAVE" # build flag for cmocka in the INF + ], "IgnoreStandardPaths": [], # Standard Plugin defined paths that should be ignore "AdditionalIncludePaths": [] # Additional paths to spell check (wildcards supported) } From e3756ba90a35af6e75c0bc7754524582554041a6 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 18:16:14 +0100 Subject: [PATCH 347/384] ArmPkg/ArmSmcPsciResetSystemLib: remove EnterS3WithImmediateWake () EnterS3WithImmediateWake () no longer has any callers, so remove it from ResetSystemLib. Note that this means the hack to support warm reboot by jumping to the SEC entry point with the MMU and caches off is also no longer used, and can be removed as well, along with the PCD PcdArmReenterPeiForCapsuleWarmReboot that was introduced for this purpose. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPkg/ArmPkg.dec | 4 - .../ArmSmcPsciResetSystemLib/AArch64/Reset.S | 24 ------ .../AArch64/Reset.asm | 29 ------- .../ArmSmcPsciResetSystemLib/Arm/Reset.S | 23 ------ .../ArmSmcPsciResetSystemLib/Arm/Reset.asm | 28 ------- .../ArmSmcPsciResetSystemLib.c | 76 ------------------- .../ArmSmcPsciResetSystemLib.inf | 17 ----- 7 files changed, 201 deletions(-) delete mode 100644 ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.S delete mode 100644 ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.asm delete mode 100644 ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.S delete mode 100644 ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.asm diff --git a/ArmPkg/ArmPkg.dec b/ArmPkg/ArmPkg.dec index 39ff339c956..eaf1072d9ef 100644 --- a/ArmPkg/ArmPkg.dec +++ b/ArmPkg/ArmPkg.dec @@ -78,10 +78,6 @@ # Define if the GICv3 controller should use the GICv2 legacy gArmTokenSpaceGuid.PcdArmGicV3WithV2Legacy|FALSE|BOOLEAN|0x00000042 - # Whether to implement warm reboot for capsule update using a jump back to the - # PEI entry point with caches and interrupts disabled. - gArmTokenSpaceGuid.PcdArmReenterPeiForCapsuleWarmReboot|FALSE|BOOLEAN|0x0000001F - [PcdsFeatureFlag.ARM] # Whether to map normal memory as non-shareable. FALSE is the safe choice, but # TRUE may be appropriate to fix performance problems if you don't care about diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.S b/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.S deleted file mode 100644 index d0d908b7d70..00000000000 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.S +++ /dev/null @@ -1,24 +0,0 @@ -/** @file - ResetSystemLib implementation using PSCI calls - - Copyright (c) 2018, Linaro Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -ASM_FUNC(DisableMmuAndReenterPei) - stp x29, x30, [sp, #-16]! - mov x29, sp - - bl ArmDisableMmu - - // no memory accesses after MMU and caches have been disabled - - MOV64 (x0, FixedPcdGet64 (PcdFvBaseAddress)) - blr x0 - - // never returns - nop diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.asm b/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.asm deleted file mode 100644 index 752df072511..00000000000 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/AArch64/Reset.asm +++ /dev/null @@ -1,29 +0,0 @@ -;/** @file -; ResetSystemLib implementation using PSCI calls -; -; Copyright (c) 2018, Linaro Ltd. All rights reserved.
-; -; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;**/ - - AREA Reset, CODE, READONLY - - EXPORT DisableMmuAndReenterPei - IMPORT ArmDisableMmu - -DisableMmuAndReenterPei - stp x29, x30, [sp, #-16]! - mov x29, sp - - bl ArmDisableMmu - - ; no memory accesses after MMU and caches have been disabled - - movl x0, FixedPcdGet64 (PcdFvBaseAddress) - blr x0 - - ; never returns - nop - - END diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.S b/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.S deleted file mode 100644 index c0c5bcf1972..00000000000 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.S +++ /dev/null @@ -1,23 +0,0 @@ -/** @file - ResetSystemLib implementation using PSCI calls - - Copyright (c) 2018, Linaro Ltd. All rights reserved.
- - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -ASM_FUNC(DisableMmuAndReenterPei) - push {lr} - - bl ArmDisableMmu - - // no memory accesses after MMU and caches have been disabled - - MOV32 (r0, FixedPcdGet64 (PcdFvBaseAddress)) - blx r0 - - // never returns - nop diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.asm b/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.asm deleted file mode 100644 index ab7519a5a92..00000000000 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/Arm/Reset.asm +++ /dev/null @@ -1,28 +0,0 @@ -;/** @file -; ResetSystemLib implementation using PSCI calls -; -; Copyright (c) 2018, Linaro Ltd. All rights reserved.
-; -; SPDX-License-Identifier: BSD-2-Clause-Patent -; -;**/ - - INCLUDE AsmMacroExport.inc - PRESERVE8 - - IMPORT ArmDisableMmu - -RVCT_ASM_EXPORT DisableMmuAndReenterPei - push {lr} - - bl ArmDisableMmu - - ; no memory accesses after MMU and caches have been disabled - - mov32 r0, FixedPcdGet64 (PcdFvBaseAddress) - blx r0 - - ; never returns - nop - - END diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.c b/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.c index b2dde9bfc13..8b5ff5c27e4 100644 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.c +++ b/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.c @@ -10,13 +10,10 @@ #include -#include #include #include #include #include -#include -#include #include @@ -76,79 +73,6 @@ ResetShutdown ( ArmCallSmc (&ArmSmcArgs); } -VOID DisableMmuAndReenterPei (VOID); - -/** - This function causes the system to enter S3 and then wake up immediately. - - If this function returns, it means that the system does not support S3 feature. -**/ -VOID -EFIAPI -EnterS3WithImmediateWake ( - VOID - ) -{ - EFI_PHYSICAL_ADDRESS Alloc; - EFI_MEMORY_DESCRIPTOR *MemMap; - UINTN MemMapSize; - UINTN MapKey, DescriptorSize; - UINT32 DescriptorVersion; - EFI_STATUS Status; - - if (FeaturePcdGet (PcdArmReenterPeiForCapsuleWarmReboot) && - !EfiAtRuntime ()) { - // - // At boot time, we are the only core running, so we can implement the - // immediate wake (which is used by capsule update) by disabling the MMU - // and interrupts, and jumping to the PEI entry point. - // - - // - // Obtain the size of the memory map - // - MemMapSize = 0; - MemMap = NULL; - Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, - &DescriptorVersion); - ASSERT (Status == EFI_BUFFER_TOO_SMALL); - - // - // Add some slack to the allocation to cater for changes in the memory - // map if ExitBootServices () fails the first time around. - // - MemMapSize += SIZE_4KB; - Status = gBS->AllocatePages (AllocateAnyPages, EfiBootServicesData, - EFI_SIZE_TO_PAGES (MemMapSize), &Alloc); - ASSERT_EFI_ERROR (Status); - - MemMap = (EFI_MEMORY_DESCRIPTOR *)(UINTN)Alloc; - - Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, - &DescriptorVersion); - ASSERT_EFI_ERROR (Status); - - Status = gBS->ExitBootServices (gImageHandle, MapKey); - if (EFI_ERROR (Status)) { - // - // ExitBootServices () may fail the first time around if an event fired - // right after the call to GetMemoryMap() which allocated or freed memory. - // Since that first call to ExitBootServices () will disarm the timer, - // this is guaranteed not to happen again, so one additional attempt - // should suffice. - // - Status = gBS->GetMemoryMap (&MemMapSize, MemMap, &MapKey, &DescriptorSize, - &DescriptorVersion); - ASSERT_EFI_ERROR (Status); - - Status = gBS->ExitBootServices (gImageHandle, MapKey); - ASSERT_EFI_ERROR (Status); - } - - DisableMmuAndReenterPei (); - } -} - /** This function causes a systemwide reset. The exact type of the reset is defined by the EFI_GUID that follows the Null-terminated Unicode string passed diff --git a/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf b/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf index fa19bf64913..c17b28cfac7 100644 --- a/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf +++ b/ArmPkg/Library/ArmSmcPsciResetSystemLib/ArmSmcPsciResetSystemLib.inf @@ -15,14 +15,6 @@ VERSION_STRING = 1.0 LIBRARY_CLASS = ResetSystemLib -[Sources.AARCH64] - AArch64/Reset.S | GCC - AArch64/Reset.asm | MSFT - -[Sources.ARM] - Arm/Reset.S | GCC - Arm/Reset.asm | RVCT - [Sources] ArmSmcPsciResetSystemLib.c @@ -32,15 +24,6 @@ MdePkg/MdePkg.dec [LibraryClasses] - ArmMmuLib ArmSmcLib BaseLib DebugLib - UefiBootServicesTableLib - UefiRuntimeLib - -[FeaturePcd] - gArmTokenSpaceGuid.PcdArmReenterPeiForCapsuleWarmReboot - -[FixedPcd] - gArmTokenSpaceGuid.PcdFvBaseAddress From a6a835bdb1f263fd696f02fc1773d1fedbdd93f6 Mon Sep 17 00:00:00 2001 From: Ard Biesheuvel Date: Mon, 6 Jan 2020 12:38:29 +0100 Subject: [PATCH 348/384] ArmPlatformPkg/PrePeiCore: enable VFP at startup While the alternative PEI-less SEC implementation in PrePi already takes the EnableVFP PCD into account, the PrePeiCore code does not, and so we may end up triggering synchronous exception when code attempts to use FP or SIMD registers, which is permitted on AARCH64 by the spec. So enable the VFP as early as feasible if the associated PCD is set. Signed-off-by: Ard Biesheuvel Reviewed-by: Leif Lindholm --- ArmPlatformPkg/PrePeiCore/PrePeiCore.c | 5 +++++ ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf | 1 + ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf | 1 + 3 files changed, 7 insertions(+) diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c index 4911f67577a..4f691d62cf3 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCore.c +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCore.c @@ -77,6 +77,11 @@ CEntryPoint ( ASSERT (((UINTN)PeiVectorTable & ARM_VECTOR_TABLE_ALIGNMENT) == 0); ArmWriteVBar ((UINTN)PeiVectorTable); + // Enable Floating Point + if (FixedPcdGet32 (PcdVFPEnabled)) { + ArmEnableVFP (); + } + //Note: The MMU will be enabled by MemoryPeim. Only the primary core will have the MMU on. // If not primary Jump to Secondary Main diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf b/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf index f2ac45d171b..104c7da5331 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCoreMPCore.inf @@ -62,6 +62,7 @@ [FixedPcd] gArmTokenSpaceGuid.PcdFvBaseAddress gArmTokenSpaceGuid.PcdFvSize + gArmTokenSpaceGuid.PcdVFPEnabled gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize diff --git a/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf b/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf index 84c319c3679..ceb173d34f5 100644 --- a/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf +++ b/ArmPlatformPkg/PrePeiCore/PrePeiCoreUniCore.inf @@ -60,6 +60,7 @@ [FixedPcd] gArmTokenSpaceGuid.PcdFvBaseAddress gArmTokenSpaceGuid.PcdFvSize + gArmTokenSpaceGuid.PcdVFPEnabled gArmPlatformTokenSpaceGuid.PcdCPUCoresStackBase gArmPlatformTokenSpaceGuid.PcdCPUCorePrimaryStackSize From 94057f740267eb39cc9b3975f3971dd6d1d68182 Mon Sep 17 00:00:00 2001 From: Brian R Haug Date: Tue, 14 Jan 2020 16:56:47 +0800 Subject: [PATCH 349/384] MdeModulePkg/Setup: Update opcode number variable type to UINTN Update data type of variables which save the opcode numbers to UINTN, in case some configuration module has lots of configuration items. Cc: Liming Gao Cc: Eric Dong Signed-off-by: Brian R Haug Reviewed-by: Dandan Bi Reviewed-by: Liming Gao Reviewed-by: Laszlo Ersek Reviewed-by: Eric Dong --- .../Universal/SetupBrowserDxe/IfrParse.c | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/MdeModulePkg/Universal/SetupBrowserDxe/IfrParse.c b/MdeModulePkg/Universal/SetupBrowserDxe/IfrParse.c index 891b95cf9fb..edb6a0fc4ce 100644 --- a/MdeModulePkg/Universal/SetupBrowserDxe/IfrParse.c +++ b/MdeModulePkg/Universal/SetupBrowserDxe/IfrParse.c @@ -1,15 +1,15 @@ /** @file Parser for IFR binary encoding. -Copyright (c) 2007 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2007 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include "Setup.h" -UINT16 mStatementIndex; -UINT16 mExpressionOpCodeIndex; +UINTN mStatementIndex; +UINTN mExpressionOpCodeIndex; EFI_QUESTION_ID mUsedQuestionId; extern LIST_ENTRY gBrowserStorageList; /** @@ -1106,12 +1106,12 @@ IsUnKnownOpCode ( VOID CountOpCodes ( IN FORM_BROWSER_FORMSET *FormSet, - IN OUT UINT16 *NumberOfStatement, - IN OUT UINT16 *NumberOfExpression + OUT UINTN *NumberOfStatement, + OUT UINTN *NumberOfExpression ) { - UINT16 StatementCount; - UINT16 ExpressionCount; + UINTN StatementCount; + UINTN ExpressionCount; UINT8 *OpCodeData; UINTN Offset; UINTN OpCodeLen; @@ -1169,8 +1169,8 @@ ParseOpCodes ( QUESTION_DEFAULT *CurrentDefault; QUESTION_OPTION *CurrentOption; UINT8 Width; - UINT16 NumberOfStatement; - UINT16 NumberOfExpression; + UINTN NumberOfStatement; + UINTN NumberOfExpression; EFI_IMAGE_ID *ImageId; BOOLEAN SuppressForQuestion; BOOLEAN SuppressForOption; From 07352d7eeb949cd9999212b6cb44a73216702058 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Tue, 14 Jan 2020 17:21:37 -0800 Subject: [PATCH 350/384] Print message so that it shows up in log --- UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 867995970d6..c05c8d8968c 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -48,6 +48,14 @@ CmockaUnitTestFunctionRunner ( Framework->CurrentTest = UnitTest; UnitTest->Result = UnitTest->RunTest (Framework, UnitTest->Context); Framework->CurrentTest = NULL; + + // Print out the log messages - This is a partial solution as it + // does not get the log into the XML. Need cmocka changes to support + // stdout and stderr in their xml format + // + if (UnitTest->Log != NULL) { + print_message("%s", UnitTest->Log); + } } } From f6f66e0c301bb2b75774060ba0a76246fbe8d924 Mon Sep 17 00:00:00 2001 From: "Li, Aaron" Date: Fri, 10 Jan 2020 09:57:35 +0800 Subject: [PATCH 351/384] BaseTools/Capsule: Add capsule dependency support REF: https://bugzilla.tianocore.org/show_bug.cgi?id=2412 Capsule generate tool support encode capsule dependencies through '-j' command with a JSON file. To enable dependency feature, "Dependencies" field for each payload in JSON file is required. The value of "Dependencies" field is C style infix notation expression. For example: "Dependencies":"72E2945A-00DA-448E-9AA7-075AD840F9D4 > 0x00000001" The relation of Dependency Expression Opcode in UEFI2.8 chap 23.2 and infix notation expression value is as follows: +-----------------------------+--------------------------+ | OPCODE | INFIX EXPRESSION VALUE | +-----------------------------+--------------------------+ | 0x00 (PUSH_GUID) | {GUID} | | 0x01 (PUSH_VERSION) | {UINT32} | | 0x02 (DECLEAR_VERSION_NAME} | DECLEAR "{VERSION_NAME}" | | 0x03 (AND) | && | | 0x04 (OR) | || | | 0x05 (NOT) | ~ | | 0x06 (TRUE) | TRUE | | 0x07 (FALSE) | FALSE | | 0x08 (EQ) | == | | 0x09 (GT) | > | | 0x0A (GTE) | >= | | 0x0B (LT) | < | | 0x0C (LTE) | <= | +-----------------------------+--------------------------+ Cc: Bob Feng Cc: Liming Gao Signed-off-by: Aaron Li Reviewed-by: Bob Feng --- .../Source/Python/Capsule/GenerateCapsule.py | 62 ++- .../Common/Uefi/Capsule/CapsuleDependency.py | 409 ++++++++++++++++++ 2 files changed, 464 insertions(+), 7 deletions(-) create mode 100644 BaseTools/Source/Python/Common/Uefi/Capsule/CapsuleDependency.py diff --git a/BaseTools/Source/Python/Capsule/GenerateCapsule.py b/BaseTools/Source/Python/Capsule/GenerateCapsule.py index 6838beb6820..a8de988253c 100644 --- a/BaseTools/Source/Python/Capsule/GenerateCapsule.py +++ b/BaseTools/Source/Python/Capsule/GenerateCapsule.py @@ -31,6 +31,7 @@ from Common.Uefi.Capsule.UefiCapsuleHeader import UefiCapsuleHeaderClass from Common.Uefi.Capsule.FmpCapsuleHeader import FmpCapsuleHeaderClass from Common.Uefi.Capsule.FmpAuthHeader import FmpAuthHeaderClass +from Common.Uefi.Capsule.CapsuleDependency import CapsuleDependencyClass from Common.Edk2.Capsule.FmpPayloadHeader import FmpPayloadHeaderClass # @@ -306,6 +307,7 @@ def EncodeJsonFileParse (Json): OpenSslOtherPublicCertFile = ConvertJsonValue (Config, 'OpenSslOtherPublicCertFile', os.path.expandvars, Required = False, Default = None, Open = True) OpenSslTrustedPublicCertFile = ConvertJsonValue (Config, 'OpenSslTrustedPublicCertFile', os.path.expandvars, Required = False, Default = None, Open = True) SigningToolPath = ConvertJsonValue (Config, 'SigningToolPath', os.path.expandvars, Required = False, Default = None) + DepexExp = ConvertJsonValue (Config, 'Dependencies', str, Required = False, Default = None) # # Read binary input file @@ -330,7 +332,8 @@ def EncodeJsonFileParse (Json): OpenSslSignerPrivateCertFile, OpenSslOtherPublicCertFile, OpenSslTrustedPublicCertFile, - SigningToolPath + SigningToolPath, + DepexExp )) def GenerateOutputJson (PayloadJsonDescriptorList): @@ -348,7 +351,8 @@ def GenerateOutputJson (PayloadJsonDescriptorList): "OpenSslSignerPrivateCertFile": str(PayloadDescriptor.OpenSslSignerPrivateCertFile), "OpenSslOtherPublicCertFile": str(PayloadDescriptor.OpenSslOtherPublicCertFile), "OpenSslTrustedPublicCertFile": str(PayloadDescriptor.OpenSslTrustedPublicCertFile), - "SigningToolPath": str(PayloadDescriptor.SigningToolPath) + "SigningToolPath": str(PayloadDescriptor.SigningToolPath), + "Dependencies" : str(PayloadDescriptor.DepexExp) }for PayloadDescriptor in PayloadJsonDescriptorList ] } @@ -424,7 +428,8 @@ def __init__(self, OpenSslSignerPrivateCertFile = None, OpenSslOtherPublicCertFile = None, OpenSslTrustedPublicCertFile = None, - SigningToolPath = None + SigningToolPath = None, + DepexExp = None ): self.Payload = Payload self.Guid = Guid @@ -438,6 +443,7 @@ def __init__(self, self.OpenSslOtherPublicCertFile = OpenSslOtherPublicCertFile self.OpenSslTrustedPublicCertFile = OpenSslTrustedPublicCertFile self.SigningToolPath = SigningToolPath + self.DepexExp = DepexExp self.UseSignTool = self.SignToolPfxFile is not None self.UseOpenSsl = (self.OpenSslSignerPrivateCertFile is not None and @@ -446,6 +452,7 @@ def __init__(self, self.AnyOpenSsl = (self.OpenSslSignerPrivateCertFile is not None or self.OpenSslOtherPublicCertFile is not None or self.OpenSslTrustedPublicCertFile is not None) + self.UseDependency = self.DepexExp is not None def Validate(self, args): if self.UseSignTool and self.AnyOpenSsl: @@ -544,7 +551,8 @@ def Encode (PayloadDescriptorList, EmbeddedDriverDescriptorList, Buffer): args.OpenSslSignerPrivateCertFile, args.OpenSslOtherPublicCertFile, args.OpenSslTrustedPublicCertFile, - args.SigningToolPath + args.SigningToolPath, + None )) for SinglePayloadDescriptor in PayloadDescriptorList: try: @@ -564,6 +572,12 @@ def Encode (PayloadDescriptorList, EmbeddedDriverDescriptorList, Buffer): except: print ('GenerateCapsule: error: can not encode FMP Payload Header') sys.exit (1) + if SinglePayloadDescriptor.UseDependency: + CapsuleDependency.Payload = Result + CapsuleDependency.DepexExp = SinglePayloadDescriptor.DepexExp + Result = CapsuleDependency.Encode () + if args.Verbose: + CapsuleDependency.DumpInfo () if SinglePayloadDescriptor.UseOpenSsl or SinglePayloadDescriptor.UseSignTool: # # Sign image with 64-bit MonotonicCount appended to end of image @@ -657,7 +671,8 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): args.OpenSslSignerPrivateCertFile, args.OpenSslOtherPublicCertFile, args.OpenSslTrustedPublicCertFile, - args.SigningToolPath + args.SigningToolPath, + None )) # # Perform additional verification on payload descriptors @@ -700,7 +715,8 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): PayloadDescriptorList[Index].OpenSslSignerPrivateCertFile, PayloadDescriptorList[Index].OpenSslOtherPublicCertFile, PayloadDescriptorList[Index].OpenSslTrustedPublicCertFile, - PayloadDescriptorList[Index].SigningToolPath + PayloadDescriptorList[Index].SigningToolPath, + None )) else: PayloadDescriptorList[0].Payload = FmpCapsuleHeader.GetFmpCapsuleImageHeader (0).Payload @@ -718,6 +734,7 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): None, None, None, + None, None )) GUID = FmpCapsuleHeader.GetFmpCapsuleImageHeader (Index).UpdateImageTypeId @@ -736,7 +753,8 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): PayloadDescriptorList[Index].OpenSslSignerPrivateCertFile, PayloadDescriptorList[Index].OpenSslOtherPublicCertFile, PayloadDescriptorList[Index].OpenSslTrustedPublicCertFile, - PayloadDescriptorList[Index].SigningToolPath + PayloadDescriptorList[Index].SigningToolPath, + None )) JsonIndex = 0 for SinglePayloadDescriptor in PayloadDescriptorList: @@ -782,6 +800,23 @@ def Decode (PayloadDescriptorList, PayloadJsonDescriptorList, Buffer): if args.Verbose: print ('--------') print ('No EFI_FIRMWARE_IMAGE_AUTHENTICATION') + + PayloadSignature = struct.unpack (' +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +import struct +import json +import sys +import uuid +import re + +''' +CapsuleDependency +''' + +class OpConvert (object): + def __init__ (self): + # Opcode: (OperandSize, PackSize, PackFmt, EncodeConvert, DecodeConvert) + self._DepexOperations = {0x00: (16, 16, 's', self.Str2Guid, self.Guid2Str), + 0x01: (4, 1, 'I', self.Str2Uint, self.Uint2Str), + 0x02: (1, 0, 's', self.Str2Utf8, self.Byte2Str), + } + + def Str2Uint (self, Data): + try: + Value = int (Data, 16) + except: + Message = '{Data} is not a valid integer value.'.format (Data = Data) + raise ValueError (Message) + if Value < 0 or Value > 0xFFFFFFFF: + Message = '{Data} is not an UINT32.'.format (Data = Data) + raise ValueError (Message) + return Value + + def Uint2Str (self, Data): + if Data < 0 or Data > 0xFFFFFFFF: + Message = '{Data} is not an UINT32.'.format (Data = Data) + raise ValueError (Message) + return "0x{Data:08x}".format (Data = Data) + + def Str2Guid (self, Data): + try: + Guid = uuid.UUID (Data) + except: + Message = '{Data} is not a valid registry format GUID value.'.format (Data = Data) + raise ValueError (Message) + return Guid.bytes_le + + def Guid2Str (self, Data): + try: + Guid = uuid.UUID (bytes_le = Data) + except: + Message = '{Data} is not a valid binary format GUID value.'.format (Data = Data) + raise ValueError (Message) + return str (Guid).upper () + + def Str2Utf8 (self, Data): + if isinstance (Data, str): + return Data.encode ('utf-8') + else: + Message = '{Data} is not a valid string.'.format (Data = Data) + raise ValueError (Message) + + def Byte2Str (self, Data): + if isinstance (Data, bytes): + if Data[-1:] == b'\x00': + return str (Data[:-1], 'utf-8') + else: + return str (Data, 'utf-8') + else: + Message = '{Data} is not a valid binary string.'.format (Data = Data) + raise ValueError (Message) + + def OpEncode (self, Opcode, Operand = None): + BinTemp = struct.pack ('': [4, 0x09, 2], + '>=': [4, 0x0A, 2], + '<': [4, 0x0B, 2], + '<=': [4, 0x0C, 2], + } + + def __init__ (self): + self.Payload = b'' + self._DepexExp = None + self._DepexList = [] + self._DepexDump = [] + self.Depex = b'' + self._Valid = False + self._DepexSize = 0 + self._opReferenceReverse = {v[1] : k for k, v in self._opReference.items ()} + self.OpConverter = OpConvert () + + @property + def DepexExp (self): + return self._DepexExp + + @DepexExp.setter + def DepexExp (self, DepexExp = ''): + if isinstance (DepexExp, str): + DepexExp = re.sub (r'\n',r' ',DepexExp) + DepexExp = re.sub (r'\(',r' ( ',DepexExp) + DepexExp = re.sub (r'\)',r' ) ',DepexExp) + DepexExp = re.sub (r'~',r' ~ ',DepexExp) + self._DepexList = re.findall(r"[^\s\"\']+|\"[^\"]*\"|\'[^\']*\'",DepexExp) + self._DepexExp = " ".join(self._DepexList) + + else: + Msg = 'Input Depex Expression is not valid string.' + raise ValueError (Msg) + + def IsValidOperator (self, op): + return op in self._opReference.keys () + + def IsValidUnaryOperator (self, op): + return op in self._opReference.keys () and self._opReference[op][2] == 1 + + def IsValidBinocularOperator (self, op): + return op in self._opReference.keys () and self._opReference[op][2] == 2 + + def IsValidGuid (self, operand): + try: + uuid.UUID (operand) + except: + return False + return True + + def IsValidVersion (self, operand): + try: + Value = int (operand, 16) + if Value < 0 or Value > 0xFFFFFFFF: + return False + except: + return False + return True + + def IsValidBoolean (self, operand): + try: + return operand.upper () in ['TRUE', 'FALSE'] + except: + return False + + def IsValidOperand (self, operand): + return self.IsValidVersion (operand) or self.IsValidGuid (operand) or self.IsValidBoolean (operand) + + def IsValidString (self, operand): + return operand[0] == "\"" and operand[-1] == "\"" and len(operand) >= 2 + + # Check if priority of current operater is greater than pervious op + def PriorityNotGreater (self, prevOp, currOp): + return self._opReference[currOp][0] <= self._opReference[prevOp][0] + + def ValidateDepex (self): + OpList = self._DepexList + + i = 0 + while i < len (OpList): + Op = OpList[i] + + if Op == 'DECLARE': + i += 1 + if i >= len (OpList): + Msg = 'No more Operand after {Op}.'.format (Op = OpList[i-1]) + raise IndexError (Msg) + # Check valid string + if not self.IsValidString(OpList[i]): + Msg = '{Operand} after {Op} is not a valid expression input.'.format (Operand = OpList[i], Op = OpList[i-1]) + raise ValueError (Msg) + + elif Op == '(': + # Expression cannot end with ( + if i == len (OpList) - 1: + Msg = 'Expression cannot end with \'(\'' + raise ValueError (Msg) + # The previous op after '(' cannot be a binocular operator + if self.IsValidBinocularOperator (OpList[i+1]) : + Msg = '{Op} after \'(\' is not a valid expression input.'.format (Op = OpList[i+1]) + raise ValueError (Msg) + + elif Op == ')': + # Expression cannot start with ) + if i == 0: + Msg = 'Expression cannot start with \')\'' + raise ValueError (Msg) + # The previous op before ')' cannot be an operator + if self.IsValidOperator (OpList[i-1]): + Msg = '{Op} before \')\' is not a valid expression input.'.format (Op = OpList[i-1]) + raise ValueError (Msg) + # The next op after ')' cannot be operand or unary operator + if (i + 1) < len (OpList) and (self.IsValidOperand (OpList[i+1]) or self.IsValidUnaryOperator (OpList[i+1])): + Msg = '{Op} after \')\' is not a valid expression input.'.format (Op = OpList[i+1]) + raise ValueError (Msg) + + elif self.IsValidOperand (Op): + # The next expression of operand cannot be operand or unary operator + if (i + 1) < len (OpList) and (self.IsValidOperand (OpList[i+1]) or self.IsValidUnaryOperator (OpList[i+1])): + Msg = '{Op} after {PrevOp} is not a valid expression input.'.format (Op = OpList[i+1], PrevOp = Op) + raise ValueError (Msg) + + elif self.IsValidOperator (Op): + # The next op of operator cannot binocular operator + if (i + 1) < len (OpList) and self.IsValidBinocularOperator (OpList[i+1]): + Msg = '{Op} after {PrevOp} is not a valid expression input.'.format (Op = OpList[i+1], PrevOp = Op) + raise ValueError (Msg) + # The first op can not be binocular operator + if i == 0 and self.IsValidBinocularOperator (Op): + Msg = 'Expression cannot start with an operator {Op}.'.format (Op = Op) + raise ValueError (Msg) + # The last op can not be operator + if i == len (OpList) - 1: + Msg = 'Expression cannot ended with an operator {Op}.'.format (Op = Op) + raise ValueError (Msg) + # The next op of unary operator cannot be guid / version + if self.IsValidUnaryOperator (Op) and (self.IsValidGuid (OpList[i+1]) or self.IsValidVersion (OpList[i+1])): + Msg = '{Op} after {PrevOp} is not a valid expression input.'.format (Op = OpList[i+1], PrevOp = Op) + raise ValueError (Msg) + + else: + Msg = '{Op} is not a valid expression input.'.format (Op = Op) + raise ValueError (Msg) + i += 1 + + def Encode (self): + # initialize + self.Depex = b'' + self._DepexDump = [] + OperandStack = [] + OpeartorStack = [] + OpList = self._DepexList + + self.ValidateDepex () + + # convert + i = 0 + while i < len (OpList): + Op = OpList[i] + if Op == 'DECLARE': + # This declare next expression value is a VERSION_STRING + i += 1 + self.Depex += self.OpConverter.OpEncode (0x02, OpList[i][1:-1]) + + elif Op == '(': + OpeartorStack.append (Op) + + elif Op == ')': + while (OpeartorStack and OpeartorStack[-1] != '('): + Operator = OpeartorStack.pop () + self.Depex += self.OpConverter.OpEncode (self._opReference[Operator][1]) + try: + OpeartorStack.pop () # pop out '(' + except: + Msg = 'Pop out \'(\' failed, too many \')\'' + raise ValueError (Msg) + + elif self.IsValidGuid (Op): + if not OperandStack: + OperandStack.append (self.OpConverter.OpEncode (0x00, Op)) + else: + # accroding to uefi spec 2.8, the guid/version operands is a reversed order in firmware comparison. + self.Depex += self.OpConverter.OpEncode (0x00, Op) + self.Depex += OperandStack.pop () + + elif self.IsValidVersion (Op): + if not OperandStack: + OperandStack.append (self.OpConverter.OpEncode (0x01, Op)) + else: + # accroding to uefi spec 2.8, the guid/version operands is a reversed order in firmware comparison. + self.Depex += self.OpConverter.OpEncode (0x01, Op) + self.Depex += OperandStack.pop () + + elif self.IsValidBoolean (Op): + if Op.upper () == 'FALSE': + self.Depex += self.OpConverter.OpEncode (0x07) + elif Op.upper () == 'TRUE': + self.Depex += self.OpConverter.OpEncode (0x06) + + elif self.IsValidOperator (Op): + while (OpeartorStack and OpeartorStack[-1] != '(' and self.PriorityNotGreater (OpeartorStack[-1], Op)): + Operator = OpeartorStack.pop () + self.Depex += self.OpConverter.OpEncode (self._opReference[Operator][1]) + OpeartorStack.append (Op) + + i += 1 + + while OpeartorStack: + Operator = OpeartorStack.pop () + if Operator == '(': + Msg = 'Too many \'(\'.' + raise ValueError (Msg) + self.Depex += self.OpConverter.OpEncode (self._opReference[Operator][1]) + self.Depex += self.OpConverter.OpEncode (0x0D) + + self._Valid = True + self._DepexSize = len (self.Depex) + return self.Depex + self.Payload + + def Decode (self, Buffer): + # initialize + self.Depex = Buffer + OperandStack = [] + DepexLen = 0 + + while True: + Opcode, Operand, OperandSize = self.OpConverter.OpDecode (Buffer[DepexLen:]) + DepexLen += OperandSize + 1 + + if Opcode == 0x0D: + break + + elif Opcode == 0x02: + if not OperandStack: + OperandStack.append ('DECLARE \"{String}\"'.format (String = Operand)) + else: + PrevOperand = OperandStack.pop () + OperandStack.append ('{Operand} DECLARE \"{String}\"'.format (Operand = PrevOperand, String = Operand)) + + elif Opcode in [0x00, 0x01]: + OperandStack.append (Operand) + + elif Opcode == 0x06: + OperandStack.append ('TRUE') + + elif Opcode == 0x07: + OperandStack.append ('FALSE') + + elif self.IsValidOperator (self._opReferenceReverse[Opcode]): + Operator = self._opReferenceReverse[Opcode] + if self.IsValidUnaryOperator (self._opReferenceReverse[Opcode]) and len (OperandStack) >= 1: + Oprand = OperandStack.pop () + OperandStack.append (' ( {Operator} {Oprand} )'.format (Operator = Operator, Oprand = Oprand)) + elif self.IsValidBinocularOperator (self._opReferenceReverse[Opcode]) and len (OperandStack) >= 2: + Oprand1 = OperandStack.pop () + Oprand2 = OperandStack.pop () + OperandStack.append (' ( {Oprand1} {Operator} {Oprand2} )'.format (Operator = Operator, Oprand1 = Oprand1, Oprand2 = Oprand2)) + else: + Msg = 'No enough Operands for {Opcode:02X}.'.format (Opcode = Opcode) + raise ValueError (Msg) + + else: + Msg = '{Opcode:02X} is not a valid OpCode.'.format (Opcode = Opcode) + raise ValueError (Msg) + + self.DepexExp = OperandStack[0].strip (' ') + self.Payload = Buffer[DepexLen:] + self._Valid = True + self._DepexSize = DepexLen + return self.Payload + + + def DumpInfo (self): + DepexLen = 0 + Opcode = None + Buffer = self.Depex + + if self._Valid == True: + print ('EFI_FIRMWARE_IMAGE_DEP.Dependencies = {') + while Opcode != 0x0D: + Opcode, Operand, OperandSize = self.OpConverter.OpDecode (Buffer[DepexLen:]) + DepexLen += OperandSize + 1 + if Operand: + print (' {Opcode:02X}, {Operand},'.format (Opcode = Opcode, Operand = Operand)) + else: + print (' {Opcode:02X},'.format (Opcode = Opcode)) + print ('}') + + print ('sizeof (EFI_FIRMWARE_IMAGE_DEP.Dependencies) = {Size:08X}'.format (Size = self._DepexSize)) + print ('sizeof (Payload) = {Size:08X}'.format (Size = len (self.Payload))) From 710ff7490ad897383eb35d1becadabd21a733f24 Mon Sep 17 00:00:00 2001 From: Krzysztof Koch Date: Thu, 9 Jan 2020 01:11:44 +0800 Subject: [PATCH 352/384] ShellPkg: acpiview: Update SRAT parser to ACPI 6.3 Add support for revision 3 of System Resource Affinity Table (SRAT). Decode and dump the new Generic Initiator Affinity Structure. Validate the Device Handle Type field inside the Generic Initiator Affinity Structure. Reviewed-by: Alexei Fedorov Reviewed-by: Jaben Carsey Reviewed-by: Sami Mujawar Reviewed-by: Zhichao Gao Tested-by: Sudipto Paul Signed-off-by: Krzysztof Koch --- .../UefiShellAcpiViewCommandLib/AcpiParser.c | 33 +++ .../UefiShellAcpiViewCommandLib/AcpiParser.h | 16 ++ .../Parsers/Srat/SratParser.c | 209 +++++++++++++++++- 3 files changed, 252 insertions(+), 6 deletions(-) diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.c index a569c3c5540..2b2ecb93cef 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.c @@ -405,6 +405,39 @@ Dump8Chars ( ); } +/** + This function traces 12 characters which can be optionally + formated using the format string if specified. + + If no format string is specified the Format must be NULL. + + @param [in] Format Optional format string for tracing the data. + @param [in] Ptr Pointer to the start of the buffer. +**/ +VOID +EFIAPI +Dump12Chars ( + IN CONST CHAR16* Format OPTIONAL, + IN UINT8* Ptr + ) +{ + Print ( + (Format != NULL) ? Format : L"%c%c%c%c%c%c%c%c%c%c%c%c", + Ptr[0], + Ptr[1], + Ptr[2], + Ptr[3], + Ptr[4], + Ptr[5], + Ptr[6], + Ptr[7], + Ptr[8], + Ptr[9], + Ptr[10], + Ptr[11] + ); +} + /** This function indents and prints the ACPI table Field Name. diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h index f374f8ebfe3..6deee3542e0 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/AcpiParser.h @@ -184,6 +184,22 @@ Dump8Chars ( IN UINT8* Ptr ); +/** + This function traces 12 characters which can be optionally + formated using the format string if specified. + + If no format string is specified the Format must be NULL. + + @param [in] Format Optional format string for tracing the data. + @param [in] Ptr Pointer to the start of the buffer. +**/ +VOID +EFIAPI +Dump12Chars ( + IN CONST CHAR16* Format OPTIONAL, + IN UINT8* Ptr + ); + /** This function indents and prints the ACPI table Field Name. diff --git a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Srat/SratParser.c b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Srat/SratParser.c index a8aa420487b..6fe7bf68113 100644 --- a/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Srat/SratParser.c +++ b/ShellPkg/Library/UefiShellAcpiViewCommandLib/Parsers/Srat/SratParser.c @@ -5,7 +5,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent @par Reference(s): - - ACPI 6.2 Specification - Errata A, September 2017 + - ACPI 6.3 Specification - January 2019 **/ #include @@ -17,6 +17,7 @@ // Local Variables STATIC CONST UINT8* SratRAType; STATIC CONST UINT8* SratRALength; +STATIC CONST UINT8* SratDeviceHandleType; STATIC ACPI_DESCRIPTION_HEADER_INFO AcpiHdrInfo; /** @@ -40,6 +41,167 @@ ValidateSratReserved ( } } +/** + This function validates the Device Handle Type field in the Generic Initiator + Affinity Structure. + + @param [in] Ptr Pointer to the start of the field data. + @param [in] Context Pointer to context specific information e.g. this + could be a pointer to the ACPI table header. +**/ +STATIC +VOID +EFIAPI +ValidateSratDeviceHandleType ( + IN UINT8* Ptr, + IN VOID* Context + ) +{ + UINT8 DeviceHandleType; + + DeviceHandleType = *Ptr; + + if (DeviceHandleType > EFI_ACPI_6_3_PCI_DEVICE_HANDLE) { + IncrementErrorCount (); + Print ( + L"\nERROR: Invalid Device Handle Type: %d. Must be between 0 and %d.", + DeviceHandleType, + EFI_ACPI_6_3_PCI_DEVICE_HANDLE + ); + } +} + +/** + This function traces the PCI BDF Number field inside Device Handle - PCI + + @param [in] Format Format string for tracing the data. + @param [in] Ptr Pointer to the start of the buffer. +**/ +STATIC +VOID +EFIAPI +DumpSratPciBdfNumber ( + IN CONST CHAR16* Format, + IN UINT8* Ptr + ) +{ + CHAR16 Buffer[OUTPUT_FIELD_COLUMN_WIDTH]; + + Print (L"\n"); + + /* + The PCI BDF Number subfields are printed in the order specified in the ACPI + specification. The format of the 16-bit PCI BDF Number field is as follows: + + +-----+------+------+ + |DEV | FUNC | BUS | + +-----+------+------+ + |15:11| 10:8 | 7:0 | + +-----+------+------+ + */ + + // Print PCI Bus Number (Bits 7:0 of Byte 2) + UnicodeSPrint ( + Buffer, + sizeof (Buffer), + L"PCI Bus Number" + ); + PrintFieldName (4, Buffer); + Print ( + L"0x%x\n", + *Ptr + ); + + Ptr++; + + // Print PCI Device Number (Bits 7:3 of Byte 3) + UnicodeSPrint ( + Buffer, + sizeof (Buffer), + L"PCI Device Number" + ); + PrintFieldName (4, Buffer); + Print ( + L"0x%x\n", + (*Ptr & (BIT7 | BIT6 | BIT5 | BIT4 | BIT3)) >> 3 + ); + + // PCI Function Number (Bits 2:0 of Byte 3) + UnicodeSPrint ( + Buffer, + sizeof (Buffer), + L"PCI Function Number" + ); + PrintFieldName (4, Buffer); + Print ( + L"0x%x\n", + *Ptr & (BIT2 | BIT1 | BIT0) + ); +} + +/** + An ACPI_PARSER array describing the Device Handle - ACPI +**/ +STATIC CONST ACPI_PARSER SratDeviceHandleAcpiParser[] = { + {L"ACPI_HID", 8, 0, L"0x%lx", NULL, NULL, NULL, NULL}, + {L"ACPI_UID", 4, 8, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Reserved", 4, 12, L"0x%x", NULL, NULL, NULL, NULL} +}; + +/** + An ACPI_PARSER array describing the Device Handle - PCI +**/ +STATIC CONST ACPI_PARSER SratDeviceHandlePciParser[] = { + {L"PCI Segment", 2, 0, L"0x%x", NULL, NULL, NULL, NULL}, + {L"PCI BDF Number", 2, 2, NULL, DumpSratPciBdfNumber, NULL, NULL, NULL}, + {L"Reserved", 12, 4, L"%x %x %x %x - %x %x %x %x - %x %x %x %x", Dump12Chars, + NULL, NULL, NULL} +}; + +/** + This function traces the Device Handle field inside Generic Initiator + Affinity Structure. + + @param [in] Format Format string for tracing the data. + @param [in] Ptr Pointer to the start of the buffer. +**/ +STATIC +VOID +EFIAPI +DumpSratDeviceHandle ( + IN CONST CHAR16* Format, + IN UINT8* Ptr + ) +{ + if (SratDeviceHandleType == NULL) { + IncrementErrorCount (); + Print (L"\nERROR: Device Handle Type read incorrectly.\n"); + return; + } + + Print (L"\n"); + + if (*SratDeviceHandleType == EFI_ACPI_6_3_ACPI_DEVICE_HANDLE) { + ParseAcpi ( + TRUE, + 2, + NULL, + Ptr, + sizeof (EFI_ACPI_6_3_DEVICE_HANDLE_ACPI), + PARSER_PARAMS (SratDeviceHandleAcpiParser) + ); + } else if (*SratDeviceHandleType == EFI_ACPI_6_3_PCI_DEVICE_HANDLE) { + ParseAcpi ( + TRUE, + 2, + NULL, + Ptr, + sizeof (EFI_ACPI_6_3_DEVICE_HANDLE_PCI), + PARSER_PARAMS (SratDeviceHandlePciParser) + ); + } +} + /** This function traces the APIC Proximity Domain field. @@ -103,6 +265,22 @@ STATIC CONST ACPI_PARSER SratGicITSAffinityParser[] = { {L"ITS Id", 4, 8, L"0x%x", NULL, NULL, NULL, NULL}, }; +/** + An ACPI_PARSER array describing the Generic Initiator Affinity Structure +**/ +STATIC CONST ACPI_PARSER SratGenericInitiatorAffinityParser[] = { + {L"Type", 1, 0, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Length", 1, 1, L"0x%x", NULL, NULL, NULL, NULL}, + + {L"Reserved", 1, 2, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Device Handle Type", 1, 3, L"%d", NULL, (VOID**)&SratDeviceHandleType, + ValidateSratDeviceHandleType, NULL}, + {L"Proximity Domain", 4, 4, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Device Handle", 16, 8, L"%s", DumpSratDeviceHandle, NULL, NULL, NULL}, + {L"Flags", 4, 24, L"0x%x", NULL, NULL, NULL, NULL}, + {L"Reserved", 4, 28, L"0x%x", NULL, NULL, NULL, NULL} +}; + /** An ACPI_PARSER array describing the Memory Affinity structure. **/ @@ -183,6 +361,7 @@ ParseAcpiSrat ( UINT8* ResourcePtr; UINT32 GicCAffinityIndex; UINT32 GicITSAffinityIndex; + UINT32 GenericInitiatorAffinityIndex; UINT32 MemoryAffinityIndex; UINT32 ApicSapicAffinityIndex; UINT32 X2ApicAffinityIndex; @@ -190,6 +369,7 @@ ParseAcpiSrat ( GicCAffinityIndex = 0; GicITSAffinityIndex = 0; + GenericInitiatorAffinityIndex = 0; MemoryAffinityIndex = 0; ApicSapicAffinityIndex = 0; X2ApicAffinityIndex = 0; @@ -232,7 +412,7 @@ ParseAcpiSrat ( } switch (*SratRAType) { - case EFI_ACPI_6_2_GICC_AFFINITY: + case EFI_ACPI_6_3_GICC_AFFINITY: AsciiSPrint ( Buffer, sizeof (Buffer), @@ -249,7 +429,7 @@ ParseAcpiSrat ( ); break; - case EFI_ACPI_6_2_GIC_ITS_AFFINITY: + case EFI_ACPI_6_3_GIC_ITS_AFFINITY: AsciiSPrint ( Buffer, sizeof (Buffer), @@ -266,7 +446,24 @@ ParseAcpiSrat ( ); break; - case EFI_ACPI_6_2_MEMORY_AFFINITY: + case EFI_ACPI_6_3_GENERIC_INITIATOR_AFFINITY: + AsciiSPrint ( + Buffer, + sizeof (Buffer), + "Generic Initiator Affinity Structure [%d]", + GenericInitiatorAffinityIndex++ + ); + ParseAcpi ( + TRUE, + 2, + Buffer, + ResourcePtr, + *SratRALength, + PARSER_PARAMS (SratGenericInitiatorAffinityParser) + ); + break; + + case EFI_ACPI_6_3_MEMORY_AFFINITY: AsciiSPrint ( Buffer, sizeof (Buffer), @@ -283,7 +480,7 @@ ParseAcpiSrat ( ); break; - case EFI_ACPI_6_2_PROCESSOR_LOCAL_APIC_SAPIC_AFFINITY: + case EFI_ACPI_6_3_PROCESSOR_LOCAL_APIC_SAPIC_AFFINITY: AsciiSPrint ( Buffer, sizeof (Buffer), @@ -300,7 +497,7 @@ ParseAcpiSrat ( ); break; - case EFI_ACPI_6_2_PROCESSOR_LOCAL_X2APIC_AFFINITY: + case EFI_ACPI_6_3_PROCESSOR_LOCAL_X2APIC_AFFINITY: AsciiSPrint ( Buffer, sizeof (Buffer), From 7d180f9125182a42fed1d3717a6f037304baffd0 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 14 Jan 2020 22:47:26 -0800 Subject: [PATCH 353/384] Tweak the documentation to align with new state of code. --- UnitTestFrameworkPkg/ReadMe.md | 78 ++++++++++++++-------------------- 1 file changed, 33 insertions(+), 45 deletions(-) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 9aa89ba2f3d..42503d5e2b4 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -8,27 +8,18 @@ on the tests and leave error logging, result formatting, context persistance, an The unit test framework works well for low level unit tests as well as system level tests and fits easily in automation frameworks. -The code is designed for a unit test application to leverage the framework which is made -up of a number of libraries which allow for easy customization of the different elements. -A few different instances are created to both show how easy some behaviors can be customized as -well as provide different implementations that support different use cases. - ### UnitTestLib -The main "framework" library. This provides the framework init, suite init, and add test case -functionality. It also supports the running of the suites and logging/reporting of results. - -### UnitTestAssetLib +The main "framework" library. The core of the framework is the Framework object, which can have any number +of test cases and test suites registered with it. The Framework object is also what drives test execution. -The UnitTestAssetLib provides helper macros and functions for checking test conditions and +The Framework also provides helper macros and functions for checking test conditions and reporting errors. Status and error info will be logged into the test context. There are a number of Assert macros that make the unit test code friendly to view and easy to understand. -### UnitTestLogLib - -Library to support logging information during the test execution. This data is logged to the test -context and will be available in the test reporting phase. This should be used for logging test -details and helpful messages to resolve test failures. +Finally, the Framework also supports logging strings during the test execution. This data is logged +to the test context and will be available in the test reporting phase. This should be used for +logging test details and helpful messages to resolve test failures. ### UnitTestPersistenceLib @@ -43,17 +34,14 @@ This is a common customization point and allows the unit test framework to fit i other test infrastructure. In this package a simple library instances has been supplied to output test results to the console as plain text. -### UnitTestTerminationLib - -Sometimes a given test case will need to exit the test in progress to allow system state to change and -will check for that state change on re-entry. This is most common when a Dxe- or Shell-based test wants to -reboot the system and check for a different system state after reboot. Since the method of exiting rebooting -may vary depending on context (PEI, SMM, DXE, Shell, etc.), this functionality is abstracted. - ## Samples There is a sample unit test provided as both an example of how to write a unit test and leverage -many of the features of the framework. This sample can be found in the SampleUnitTestApp directory. +many of the features of the framework. This sample can be found in the `Test/UnitTest/Sample/SampleUnitTest` +directory. + +The sample is provided in PEI, SMM, DXE, and UEFI App flavors. It also has a flavor for the HOST_APPLICATION +build type, which can be run on a host system without needing a target. ## Usage @@ -61,32 +49,32 @@ This section is built a lot like a "Getting Started". We'll go through some of t when constructing a unit test and some of the decisions that are made by the test writer. We'll also describe how to check for expected conditions in test cases and a bit of the logging characteristics. -Most of these examples will refer to the SampleUnitTestApp found in this package. +Most of these examples will refer to the SampleUnitTestUefiShell app found in this package. ### Requirements - INF -In our INF file, we'll need to bring in some libraries. At a bare minimum, we'll need an instance of `UnitTestLib`, -however, since Test Assertions are implemented in their own lib in order to allow for framework flexibility, we -will also have to bring in `UnitTestAssertLib` as well. +In our INF file, we'll need to bring in the `UnitTestLib` library. Conveniently, the interface +header for the `UnitTestLib` is located in `MdePkg`, so you shouldn't need to depend on any other +packages. As long as your DSC file knows where to find the lib implmentation that you want to use, +you should be good to go. See this example in 'SampleUnitTestApp.inf'... ``` +[Packages] + MdePkg/MdePkg.dec + [LibraryClasses] - BaseLib UefiApplicationEntryPoint + BaseLib DebugLib UnitTestLib - UnitTestAssertLib PrintLib ``` -And in order to bring in the headers we'll need, go ahead and add 'UnitTestPkg/UnitTestPkg.dec' to your -`Packages` list as well. - ### Requirements - Code -Not to state the obvious, but let's make sure we have the following includes before getting too far along... +Not to state the obvious, but let's make sure we have the following include before getting too far along... ```c #include @@ -101,12 +89,12 @@ This Framework object will contain all the information about our test, the test with it, the current location within the test pass, and any results that have been recorded so far. To get started with a test, we must first create a Framework instance. The function for this is -`InitUnitTestFramework`. It takes in `CHAR16` strings for the long name, short name, and test version. +`InitUnitTestFramework`. It takes in `CHAR8` strings for the long name, short name, and test version. The long name and version strings are just for user presentation and relatively flexible. The short name will be used to name any cache files and/or test results, so should be a name that makes sense in that context. These strings are copied internally to the Framework, so using stack-allocated or literal strings is fine. -In the 'SampleUnitTestApp', the module name is used as the short name, so the init looks like this. +In the 'SampleUnitTestUefiShell' app, the module name is used as the short name, so the init looks like this. ```c DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); @@ -114,17 +102,17 @@ DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); // // Start setting up the test framework for running the tests. // -Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); +Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); ``` -The `&Fw` returned here is the handle to the Framework. If it's successfully returned, we can start adding +The `&Framework` returned here is the handle to the Framework. If it's successfully returned, we can start adding test suites and test cases. Test suites exist purely to help organize test cases and to differentiate the results in reports. If you're writing a small unit test, you can conceivably put all test cases into a single suite. However, if you end up with 20+ test cases, it may be beneficial to organize them according to purpose. You _must_ have at least one test suite, even if it's just a catch-all. The function to create a test suite is `CreateUnitTestSuite`. It takes in a handle to -the Framework object, a `CHAR16` string for the suite title and package name, and optional function pointers for +the Framework object, a `CHAR8` string for the suite title and package name, and optional function pointers for a setup function and a teardown function. The suite title is for user presentation. The package name is for xUnit type reporting and uses a '.'-separated @@ -133,13 +121,13 @@ called once at the start of the suite (before _any_ tests have run) and once at tests have run), respectively. If either or both of these are unneeded, pass `NULL`. The function prototypes are `UNIT_TEST_SUITE_SETUP` and `UNIT_TEST_SUITE_TEARDOWN`. -Looking at 'SampleUnitTestApp', you can see that the first test suite is created as below... +Looking at 'SampleUnitTestUefiShell' app, you can see that the first test suite is created as below... ```c // // Populate the SimpleMathTests Unit Test Suite. // -Status = CreateUnitTestSuite( &SimpleMathTests, Fw, L"Simple Math Tests", L"Sample.Math", NULL, NULL ); +Status = CreateUnitTestSuite( &SimpleMathTests, Fw, "Simple Math Tests", "Sample.Math", NULL, NULL ); ``` This test suite has no setup or teardown functions. The `&SimpleMathTests` returned here is a handle to the suite and @@ -147,7 +135,7 @@ will be used when adding test cases. Great! Now we've finished some of the cruft, red tape, and busy work. We're ready to add some tests. Adding a test to a test suite is accomplished with the -- you guessed it -- `AddTestCase` function. It takes in the suite handle; -a `CHAR16` string for the description and class name; a function pointer for the test case itself; additional, optional +a `CHAR8` string for the description and class name; a function pointer for the test case itself; additional, optional function pointers for prerequisite check and cleanup routines; and and optional pointer to a context structure. Okay, that's a lot. Let's take it one piece at a time. The description and class name strings are very similar in @@ -167,10 +155,10 @@ of the context pointer is to allow test case reuse with different input data. (A around a system reboot, but that's beyond the scope of this guide.) The test case must know how to interpret the context pointer, so it could be a simple value, or it could be a complex structure. If unneeded, pass `NULL`. -In 'SampleUnitTestApp', the first test case is added using the code below... +In 'SampleUnitTestUefiShell' app, the first test case is added using the code below... ```c -AddTestCase( SimpleMathTests, L"Adding 1 to 1 should produce 2", L"Sample.Math.Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); +AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); ``` This test case calls the function `OnePlusOneShouldEqualTwo` and has no prerequisite, cleanup, or context. @@ -181,7 +169,7 @@ Once all the suites and cases are added, it's time to run the Framework. // // Execute the tests. // -Status = RunAllTestSuites( Fw ); +Status = RunAllTestSuites( Framework ); ``` ### A Simple Test Case @@ -228,7 +216,7 @@ When using the EDK2 Pytools for CI testing, the host-based unit tests will be bu If you are trying to iterate on a single test, a convenient pattern is to build only that test module. For example, the following command will build only the SafeIntLib host-based test from the MdePkg... ```bash -stuart_ci_build -c .\.pytool\CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf +stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf ``` ## Copyright From 63653ff8c83e732d8bb3087db09ca8e7ca11a57a Mon Sep 17 00:00:00 2001 From: Liming Gao Date: Thu, 16 Jan 2020 11:48:05 +0800 Subject: [PATCH 354/384] MdePkg Base.h: Use correct style to check the defined macro #if MACRO is not good style. It should be changed to #ifdef MACRO style or #if defined (MACRO) style. Signed-off-by: Zhiguang Liu Reviewed-by: Liming Gao --- MdePkg/Include/Base.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/MdePkg/Include/Base.h b/MdePkg/Include/Base.h index e0bcd0ae67a..321d729c04b 100644 --- a/MdePkg/Include/Base.h +++ b/MdePkg/Include/Base.h @@ -195,7 +195,7 @@ SPDX-License-Identifier: BSD-2-Clause-Patent /// #define ASM_PFX(name) _CONCATENATE (__USER_LABEL_PREFIX__, name) -#if __APPLE__ +#ifdef __APPLE__ // // Apple extension that is used by the linker to optimize code size // with assembly functions. Put at the end of your .S files @@ -799,7 +799,7 @@ typedef UINTN *BASE_LIST; **/ #ifdef MDE_CPU_EBC #define STATIC_ASSERT(Expression, Message) -#elif _MSC_EXTENSIONS +#elif defined(_MSC_EXTENSIONS) #define STATIC_ASSERT static_assert #else #define STATIC_ASSERT _Static_assert From 3756d3a460a43527b2c9f862b9d86386196071e6 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Wed, 15 Jan 2020 00:00:23 -0800 Subject: [PATCH 355/384] Add inital port of BaseLib UnitTest that supports base64 encode/decode. Test currently aborts due to memory corruption. (cherry picked from commit 2af6abf3f5bee9c3f5b1dd693d64cd40d8e52209) --- MdePkg/MdePkg.dsc | 5 + MdePkg/Test/MdePkgHostTest.dsc | 2 + .../UnitTest/Library/BaseLib/Base64UnitTest.c | 391 ++++++++++++++++++ .../Library/BaseLib/BaseLibUnitTestsHost.inf | 39 ++ .../Library/BaseLib/BaseLibUnitTestsUefi.inf | 41 ++ 5 files changed, 478 insertions(+) create mode 100644 MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c create mode 100644 MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf create mode 100644 MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf diff --git a/MdePkg/MdePkg.dsc b/MdePkg/MdePkg.dsc index f8751764977..87af7408539 100644 --- a/MdePkg/MdePkg.dsc +++ b/MdePkg/MdePkg.dsc @@ -120,6 +120,11 @@ MdePkg/Library/StandaloneMmDriverEntryPoint/StandaloneMmDriverEntryPoint.inf MdePkg/Library/StandaloneMmServicesTableLib/StandaloneMmServicesTableLib.inf + # + # Add UEFI Target Based Unit Tests + # + MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf + # # Build PEIM, DXE_DRIVER, SMM_DRIVER, UEFI Shell components that test SafeIntLib # diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc index cdacebd5c9a..453a8288d9a 100644 --- a/MdePkg/Test/MdePkgHostTest.dsc +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -1,6 +1,7 @@ ## @file # # Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (C) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent # ## @@ -25,3 +26,4 @@ # Build HOST_APPLICATION that tests the SafeIntLib # MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf + MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c new file mode 100644 index 00000000000..206517b0c34 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c @@ -0,0 +1,391 @@ +/** @file +Base64UnitTest.c + +Unit Test for Base64 conversion routines. + +Copyright (C) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#define UNIT_TEST_APP_NAME "BaseLib Unit Test Application" +#define UNIT_TEST_APP_VERSION "1.0" + +/** +RFC 4648 https://tools.ietf.org/html/rfc4648 test vectors + + BASE64("") = "" + BASE64("f") = "Zg==" + BASE64("fo") = "Zm8=" + BASE64("foo") = "Zm9v" + BASE64("foob") = "Zm9vYg==" + BASE64("fooba") = "Zm9vYmE=" + BASE64("foobar") = "Zm9vYmFy" + + The test vectors are using ascii strings for the binary data + */ + +typedef struct { + CHAR8 *TestInput; + CHAR8 *TestOutput; + EFI_STATUS ExpectedStatus; + VOID *BufferToFree; + UINTN ExpectedSize; +} BASIC_TEST_CONTEXT; + + +#define B64_TEST_1 "" +#define BIN_TEST_1 "" + +#define B64_TEST_2 "Zg==" +#define BIN_TEST_2 "f" + +#define B64_TEST_3 "Zm8=" +#define BIN_TEST_3 "fo" + +#define B64_TEST_4 "Zm9v" +#define BIN_TEST_4 "foo" + +#define B64_TEST_5 "Zm9vYg==" +#define BIN_TEST_5 "foob" + +#define B64_TEST_6 "Zm9vYmE=" +#define BIN_TEST_6 "fooba" + +#define B64_TEST_7 "Zm9vYmFy" +#define BIN_TEST_7 "foobar" + +// Adds white space - also ends the last quantum with only spaces afterwards +#define B64_TEST_8_IN " Zm9\r\nvYmFy " +#define B64_TEST_8_OUT "Zm9vYmFy" +#define BIN_TEST_8 "foobar" + +// Not a quantum multiple of 4 +#define B64_ERROR_1 "Zm9vymFy=" + +// Invalid characters in the string +#define B64_ERROR_2 "Zm$vymFy" + +// Too many '=' characters +#define B64_ERROR_3 "Z===" + +// Poorly placed '=' +#define B64_ERROR_4 "Zm=vYmFy" + +#define MAX_TEST_STRING_SIZE (200) +// ------------------------------------------------ Input----------Output-----------Result-------Free--Expected Output Size +static BASIC_TEST_CONTEXT mBasicEncodeTest1 = {BIN_TEST_1, B64_TEST_1, EFI_SUCCESS, NULL, sizeof(B64_TEST_1)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest2 = {BIN_TEST_2, B64_TEST_2, EFI_SUCCESS, NULL, sizeof(B64_TEST_2)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest3 = {BIN_TEST_3, B64_TEST_3, EFI_SUCCESS, NULL, sizeof(B64_TEST_3)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest4 = {BIN_TEST_4, B64_TEST_4, EFI_SUCCESS, NULL, sizeof(B64_TEST_4)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest5 = {BIN_TEST_5, B64_TEST_5, EFI_SUCCESS, NULL, sizeof(B64_TEST_5)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest6 = {BIN_TEST_6, B64_TEST_6, EFI_SUCCESS, NULL, sizeof(B64_TEST_6)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest7 = {BIN_TEST_7, B64_TEST_7, EFI_SUCCESS, NULL, sizeof(B64_TEST_7)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest8 = {BIN_TEST_8, B64_TEST_8_OUT, EFI_SUCCESS, NULL, sizeof(B64_TEST_8_OUT)}; + +static BASIC_TEST_CONTEXT mBasicDecodeTest1 = {B64_TEST_1, BIN_TEST_1, EFI_SUCCESS, NULL, sizeof(BIN_TEST_1)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest2 = {B64_TEST_2, BIN_TEST_2, EFI_SUCCESS, NULL, sizeof(BIN_TEST_2)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest3 = {B64_TEST_3, BIN_TEST_3, EFI_SUCCESS, NULL, sizeof(BIN_TEST_3)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest4 = {B64_TEST_4, BIN_TEST_4, EFI_SUCCESS, NULL, sizeof(BIN_TEST_4)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest5 = {B64_TEST_5, BIN_TEST_5, EFI_SUCCESS, NULL, sizeof(BIN_TEST_5)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest6 = {B64_TEST_6, BIN_TEST_6, EFI_SUCCESS, NULL, sizeof(BIN_TEST_6)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest7 = {B64_TEST_7, BIN_TEST_7, EFI_SUCCESS, NULL, sizeof(BIN_TEST_7)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest8 = {B64_TEST_8_IN, BIN_TEST_8, EFI_SUCCESS, NULL, sizeof(BIN_TEST_8)-1}; + +static BASIC_TEST_CONTEXT mBasicDecodeError1 = {B64_ERROR_1, B64_ERROR_1, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError2 = {B64_ERROR_2, B64_ERROR_2, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError3 = {B64_ERROR_3, B64_ERROR_3, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError4 = {B64_ERROR_4, B64_ERROR_4, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError5 = {B64_TEST_7, BIN_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(BIN_TEST_7)-1}; + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + +/** +Simple clean up method to make sure tests clean up even if interrupted and fail in the middle. +**/ +STATIC +VOID +EFIAPI +CleanUpB64TestContext ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) { + + BASIC_TEST_CONTEXT *Btc; + + + Btc = (BASIC_TEST_CONTEXT *) Context; + if (Btc != NULL) { + //free string if set + if (Btc->BufferToFree != NULL) + { + FreePool(Btc->BufferToFree); + Btc->BufferToFree = NULL; + } + } +} + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ +static +UNIT_TEST_STATUS +EFIAPI +RfcEncodeTest( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) { + + BASIC_TEST_CONTEXT *Btc; + CHAR8 *b64String; + CHAR8 *binString; + UINTN b64StringSize; + EFI_STATUS Status; + UINT8 *BinData; + UINTN BinSize; + CHAR8 *b64WorkString; + UINTN ReturnSize; + INTN CompareStatus; + UINTN indx; + + + Btc = (BASIC_TEST_CONTEXT *) Context; + binString = Btc->TestInput; + b64String = Btc->TestOutput; + + // + // Only testing the the translate functionality, so + // preallocate the proper string buffer + + b64StringSize = AsciiStrnSizeS(b64String, MAX_TEST_STRING_SIZE); + BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); + BinData = (UINT8 *) binString; + + // Only allocate the expected buffer, and count on memory + // protections to catch buffer overruns + b64WorkString = (CHAR8 *) AllocatePool(Btc->ExpectedSize); + UT_ASSERT_NOT_NULL(b64WorkString); + + Btc->BufferToFree = b64WorkString; + ReturnSize = b64StringSize; + + Status = Base64Encode(BinData, BinSize, b64WorkString, &ReturnSize); + + UT_ASSERT_STATUS_EQUAL(Status, Btc->ExpectedStatus); + + UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); + + if (ReturnSize != 0) { + CompareStatus = AsciiStrnCmp(b64String, b64WorkString, ReturnSize); + if (CompareStatus != 0) { + UT_LOG_ERROR("b64 string compare error - size=%d\n",ReturnSize); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & b64String[indx]); + } + UT_LOG_ERROR("\n b64 work string:\n"); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & b64WorkString[indx]); + } + UT_LOG_ERROR("\n"); + } + UT_ASSERT_EQUAL(CompareStatus, 0); + } + + Btc->BufferToFree = NULL; + FreePool (b64WorkString); + return UNIT_TEST_PASSED; +} + +static +UNIT_TEST_STATUS +EFIAPI +RfcDecodeTest( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) { + + BASIC_TEST_CONTEXT *Btc; + CHAR8 *b64String; + CHAR8 *binString; + EFI_STATUS Status; + UINTN b64StringLen; + UINTN ReturnSize; + UINT8 *BinData; + UINTN BinSize; + INTN CompareStatus; + UINTN indx; + + + Btc = (BASIC_TEST_CONTEXT *) Context; + b64String = Btc->TestInput; + binString = Btc->TestOutput; + + // + // Only testing the the translate functionality + // + + b64StringLen = AsciiStrnLenS(b64String, MAX_TEST_STRING_SIZE); + BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); + + // Only allocate the expected buffer, and count on memory + // protections to catch buffer overruns + BinData = AllocatePool (Btc->ExpectedSize); + Btc->BufferToFree = BinData; + + ReturnSize = BinSize; + Status = Base64Decode(b64String, b64StringLen, BinData, &ReturnSize); + + UT_ASSERT_STATUS_EQUAL(Status, Btc->ExpectedStatus); + + // If an error is not expected, check the results + if (EFI_ERROR(Btc->ExpectedStatus)) { + if (Btc->ExpectedStatus == EFI_BUFFER_TOO_SMALL) { + UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); + } + } else { + UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); + if (ReturnSize != 0) { + CompareStatus = CompareMem(binString, BinData, ReturnSize); + if (CompareStatus != 0) { + UT_LOG_ERROR("bin string compare error - size=%d\n", ReturnSize); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & binString[indx]); + } + UT_LOG_ERROR("\nBinData:\n"); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & BinData[indx]); + } + UT_LOG_ERROR("\n"); + } + UT_ASSERT_EQUAL(CompareStatus, 0); + } + } + + Btc->BufferToFree = NULL; + FreePool (BinData); + return UNIT_TEST_PASSED; +} + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +STATIC +EFI_STATUS +EFIAPI +UnitTestingEntry () +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Fw = NULL; + UNIT_TEST_SUITE_HANDLE b64EncodeTests; + UNIT_TEST_SUITE_HANDLE b64DecodeTests; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); + if (EFI_ERROR( Status )) { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the B64 Encode Unit Test Suite. + // + Status = CreateUnitTestSuite( &b64EncodeTests, Fw, "b64 Encode binary to Ascii string", "BaseLib.b64Encode", NULL, NULL ); + if (EFI_ERROR( Status )){ + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64EncodeTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + +// --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest1); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test2", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest2); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test3", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest3); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test4", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest4); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test5", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest5); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test6", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest6); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test7", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest7); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test8", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest8); + + // + // Populate the B64 Decode Unit Test Suite. + // + Status = CreateUnitTestSuite( &b64DecodeTests, Fw, "b64 Decode Ascii string to binary", "BaseLib.b64Decode", NULL, NULL ); + if (EFI_ERROR( Status )) { + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64Decode Tests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest1 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest2 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest3 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest4 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest5 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test6", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest6 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test7", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest7 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test8", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest8 ); + + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError1 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError2 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError3 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError4 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError5 ); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Fw ); + +EXIT: + if (Fw) { + FreeUnitTestFramework( Fw ); + } + + return Status; +} + +EFI_STATUS +EFIAPI +BaseLibUnitTestAppEntry ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) + { + return UnitTestingEntry(); + } + +int +main ( + int argc, + char *argv[] + ) +{ + return UnitTestingEntry(); +} diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf new file mode 100644 index 00000000000..2dbd3effb87 --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf @@ -0,0 +1,39 @@ +## @file +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseLibUnitTestsHost + FILE_GUID = 1d005f4c-4dfa-41b5-ab0c-be91fe121459 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Base64UnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib + +[Guids] + + + + diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf new file mode 100644 index 00000000000..9a2856ec30e --- /dev/null +++ b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf @@ -0,0 +1,41 @@ +## @file +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseLibUnitTestsUefi + FILE_GUID = df5a6fed-8786-4a9d-9d02-eab39497b4a1 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = BaseLibUnitTestAppEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Base64UnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[Protocols] + + +[LibraryClasses] + BaseLib + BaseMemoryLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib + +[Guids] + + + + From 4cfb18062b2b8c09de9d186283a325acee9767f8 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Wed, 15 Jan 2020 22:30:56 -0800 Subject: [PATCH 356/384] Update Base64 Unit Test * Resolve memory corruption caused by improper test code * Change test descriptions to be more meaningful * Add error test case for encode * Remove duplicate encode test case (cherry picked from commit 290168971da29bd5d305d775ebddf55967b86f25) --- .../UnitTest/Library/BaseLib/Base64UnitTest.c | 86 +++++++++---------- 1 file changed, 41 insertions(+), 45 deletions(-) diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c index 206517b0c34..1ae52818460 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c +++ b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c @@ -62,9 +62,8 @@ typedef struct { #define B64_TEST_7 "Zm9vYmFy" #define BIN_TEST_7 "foobar" -// Adds white space - also ends the last quantum with only spaces afterwards -#define B64_TEST_8_IN " Zm9\r\nvYmFy " -#define B64_TEST_8_OUT "Zm9vYmFy" +// Adds all white space - also ends the last quantum with only spaces afterwards +#define B64_TEST_8_IN " \t\v Zm9\r\nvYmFy \f " #define BIN_TEST_8 "foobar" // Not a quantum multiple of 4 @@ -88,7 +87,7 @@ static BASIC_TEST_CONTEXT mBasicEncodeTest4 = {BIN_TEST_4, B64_TEST_4, static BASIC_TEST_CONTEXT mBasicEncodeTest5 = {BIN_TEST_5, B64_TEST_5, EFI_SUCCESS, NULL, sizeof(B64_TEST_5)}; static BASIC_TEST_CONTEXT mBasicEncodeTest6 = {BIN_TEST_6, B64_TEST_6, EFI_SUCCESS, NULL, sizeof(B64_TEST_6)}; static BASIC_TEST_CONTEXT mBasicEncodeTest7 = {BIN_TEST_7, B64_TEST_7, EFI_SUCCESS, NULL, sizeof(B64_TEST_7)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest8 = {BIN_TEST_8, B64_TEST_8_OUT, EFI_SUCCESS, NULL, sizeof(B64_TEST_8_OUT)}; +static BASIC_TEST_CONTEXT mBasicEncodeError1 = {BIN_TEST_7, B64_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(B64_TEST_7)}; static BASIC_TEST_CONTEXT mBasicDecodeTest1 = {B64_TEST_1, BIN_TEST_1, EFI_SUCCESS, NULL, sizeof(BIN_TEST_1)-1}; static BASIC_TEST_CONTEXT mBasicDecodeTest2 = {B64_TEST_2, BIN_TEST_2, EFI_SUCCESS, NULL, sizeof(BIN_TEST_2)-1}; @@ -178,9 +177,7 @@ RfcEncodeTest( BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); BinData = (UINT8 *) binString; - // Only allocate the expected buffer, and count on memory - // protections to catch buffer overruns - b64WorkString = (CHAR8 *) AllocatePool(Btc->ExpectedSize); + b64WorkString = (CHAR8 *) AllocatePool(b64StringSize); UT_ASSERT_NOT_NULL(b64WorkString); Btc->BufferToFree = b64WorkString; @@ -192,20 +189,22 @@ RfcEncodeTest( UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); - if (ReturnSize != 0) { - CompareStatus = AsciiStrnCmp(b64String, b64WorkString, ReturnSize); - if (CompareStatus != 0) { - UT_LOG_ERROR("b64 string compare error - size=%d\n",ReturnSize); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & b64String[indx]); - } - UT_LOG_ERROR("\n b64 work string:\n"); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & b64WorkString[indx]); + if (! EFI_ERROR(Btc->ExpectedStatus)) { + if (ReturnSize != 0) { + CompareStatus = AsciiStrnCmp(b64String, b64WorkString, ReturnSize); + if (CompareStatus != 0) { + UT_LOG_ERROR("b64 string compare error - size=%d\n",ReturnSize); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & b64String[indx]); + } + UT_LOG_ERROR("\n b64 work string:\n"); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR(" %2.2x", 0xff & b64WorkString[indx]); + } + UT_LOG_ERROR("\n"); } - UT_LOG_ERROR("\n"); + UT_ASSERT_EQUAL(CompareStatus, 0); } - UT_ASSERT_EQUAL(CompareStatus, 0); } Btc->BufferToFree = NULL; @@ -244,9 +243,7 @@ RfcDecodeTest( b64StringLen = AsciiStrnLenS(b64String, MAX_TEST_STRING_SIZE); BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); - // Only allocate the expected buffer, and count on memory - // protections to catch buffer overruns - BinData = AllocatePool (Btc->ExpectedSize); + BinData = AllocatePool (BinSize); Btc->BufferToFree = BinData; ReturnSize = BinSize; @@ -324,15 +321,14 @@ UnitTestingEntry () } // --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest1); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test2", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest2); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test3", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest3); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test4", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest4); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test5", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest5); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test6", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest6); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test7", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest7); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector", "Test8", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest8); - + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest1); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - f", "Test2", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest2); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest3); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest4); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest5); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest6); + AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest7); + AddTestCase( b64EncodeTests, "Too small of output buffer", "Error1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeError1); // // Populate the B64 Decode Unit Test Suite. // @@ -343,20 +339,20 @@ UnitTestingEntry () goto EXIT; } - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest1 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest2 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest3 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest4 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest5 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test6", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest6 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test7", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest7 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Test8", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest8 ); - - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError1 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError2 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError3 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError4 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector", "Error5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError5 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest1 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - f", "Test2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest2 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest3 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest4 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest5 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest6 ); + AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest7 ); + AddTestCase(b64DecodeTests, "Ignore Whitespace test", "Test8", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest8 ); + + AddTestCase(b64DecodeTests, "Not a quantum multiple of 4", "Error1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError1 ); + AddTestCase(b64DecodeTests, "Invalid characters in the string", "Error2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError2 ); + AddTestCase(b64DecodeTests, "Too many padding characters", "Error3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError3 ); + AddTestCase(b64DecodeTests, "Incorrectly placed padding character", "Error4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError4 ); + AddTestCase(b64DecodeTests, "Too small of output buffer", "Error5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError5 ); // // Execute the tests. From 97fb05595125debe14c8549af56d66e490316702 Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Wed, 15 Jan 2020 20:36:07 -0800 Subject: [PATCH 357/384] Bug fix for reallocate pool (cherry picked from commit 47dbf42513016b32945f7e913637d20ad297e810) --- .../Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c index ec7b4e06e43..0b1524421f8 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c @@ -538,6 +538,9 @@ ReallocatePool ( if (NewBuffer != NULL && OldBuffer != NULL) { memcpy (NewBuffer, OldBuffer, MIN (OldSize, NewSize)); } + if (OldBuffer != NULL) { + FreePool(OldBuffer); + } return NewBuffer; } From 1862a360f05f5029b8aa14cb5652506c6830f50c Mon Sep 17 00:00:00 2001 From: Sean Brogan Date: Thu, 16 Jan 2020 12:39:37 -0800 Subject: [PATCH 358/384] Add more context to cmocka log hack (cherry picked from commit 689d596e5f029b20bc280591360e8158cfaeed61) --- UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c | 3 +++ 1 file changed, 3 insertions(+) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index c05c8d8968c..cfeb3f1f468 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -54,7 +54,10 @@ CmockaUnitTestFunctionRunner ( // stdout and stderr in their xml format // if (UnitTest->Log != NULL) { + print_message("UnitTest: %s - %s\n", UnitTest->ClassName, UnitTest->Description); + print_message("Log Output Start\n"); print_message("%s", UnitTest->Log); + print_message("Log Output End\n"); } } } From 302eb57b18d9ac70270c18a9a2a2630cba98f8ab Mon Sep 17 00:00:00 2001 From: Michael Kubacki Date: Mon, 13 Jan 2020 14:44:50 -0800 Subject: [PATCH 359/384] MdeModulePkg/Variable: Fix VarErrorFlag RT cache offset calculation REF:https://bugzilla.tianocore.org/show_bug.cgi?id=2457 This commit fixes an offset calculation that is used to write the VarErrorFlag UEFI variable to the UEFI variable runtime cache. Currently a physical address is used instead of an offset. This commit changes the offset to zero with a length of the entire non-volatile variable store so the entire non-volatile variable store buffer in SMRAM (with the variable update modification) is copied to the runtime variable cache. This follows the same pattern used in other SynchronizeRuntimeVariableCache () calls for consistency. * Observable symptom: An exception in SMM will most likely occur due to the invalid memory reference when the VarErrorFlag variable is written. The variable is most commonly written when the UEFI variable store is full. * The issue only occurs when the variable runtime cache is enabled by the following PCD being set to TRUE: gEfiMdeModulePkgTokenSpaceGuid.PcdEnableVariableRuntimeCache Fixes: aab3b9b9a1e5e1f3fa966fb1667fc3e6c47e7706 Cc: Liming Gao Cc: Michael D Kinney Cc: Michael Turner Cc: Jian J Wang Cc: Hao A Wu Signed-off-by: Michael Kubacki Reviewed-by: Liming Gao Reviewed-by: Jian J Wang --- MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c index b0ee5e50d00..d23aea4bc71 100644 --- a/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c +++ b/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c @@ -16,7 +16,7 @@ VariableServiceSetVariable() should also check authenticate data to avoid buffer overflow, integer overflow. It should also check attribute to avoid authentication bypass. -Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.
+Copyright (c) 2006 - 2020, Intel Corporation. All rights reserved.
(C) Copyright 2015-2018 Hewlett Packard Enterprise Development LP
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -335,8 +335,8 @@ RecordVarErrorFlag ( *VarErrFlag = TempFlag; Status = SynchronizeRuntimeVariableCache ( &mVariableModuleGlobal->VariableGlobal.VariableRuntimeCacheContext.VariableRuntimeNvCache, - (UINTN) VarErrFlag - (UINTN) mNvVariableCache + (UINTN) mVariableModuleGlobal->VariableGlobal.NonVolatileVariableBase, - sizeof (TempFlag) + 0, + mNvVariableCache->Size ); ASSERT_EFI_ERROR (Status); } From 8064a0a3074c97fe1b49ff2fb7a38abacd7ba15c Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 16 Jan 2020 19:29:56 -0800 Subject: [PATCH 360/384] Add a Cmocka test for DxeResetSystem to demo mocking and advanced features. --- .../UnitTest/DxeResetSystemLibUnitTest.c | 264 ++++++++++++++++++ .../DxeResetSystemLibUnitTestHost.inf | 35 +++ MdeModulePkg/MdeModulePkg.ci.yaml | 9 + MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 29 ++ .../MockLibraryClassLibNull.c | 9 + .../MockLibraryClassLibNull.inf | 23 ++ UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 4 +- 7 files changed, 372 insertions(+), 1 deletion(-) create mode 100644 MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c create mode 100644 MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf create mode 100644 MdeModulePkg/Test/MdeModulePkgHostTest.dsc create mode 100644 UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c create mode 100644 UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c new file mode 100644 index 00000000000..678496eaead --- /dev/null +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -0,0 +1,264 @@ +/** @file +DxeResetSystemLibUnitTestHost.c + +Copyright (C) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#define UNIT_TEST_APP_NAME "DxeResetSystemLib Unit Tests" +#define UNIT_TEST_APP_VERSION "1.0" + + +///================================================================================================ +///================================================================================================ +/// +/// HELPER FUNCTIONS +/// +///================================================================================================ +///================================================================================================ + +/** + Resets the entire platform. + + @param[in] ResetType The type of reset to perform. + @param[in] ResetStatus The status code for the reset. + @param[in] DataSize The size, in bytes, of ResetData. + @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or + EfiResetShutdown the data buffer starts with a Null-terminated + string, optionally followed by additional binary data. + The string is a description that the caller may use to further + indicate the reason for the system reset. + For a ResetType of EfiResetPlatformSpecific the data buffer + also starts with a Null-terminated string that is followed + by an EFI_GUID that describes the specific type of reset to perform. +**/ +STATIC +VOID +MockResetSystem ( + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL + ) +{ + check_expected_ptr( ResetType ); + check_expected_ptr( ResetStatus ); + + // NOTE: Mocked functions can also return values, but that + // is for another demo. + + return; +} + +EFI_RUNTIME_SERVICES MockRuntime = { + { + EFI_RUNTIME_SERVICES_SIGNATURE, // Signature + EFI_RUNTIME_SERVICES_REVISION, // Revision + sizeof (EFI_RUNTIME_SERVICES), // HeaderSize + 0, // CRC32 + 0 // Reserved + }, + NULL, // GetTime + NULL, // SetTime + NULL, // GetWakeupTime + NULL, // SetWakeupTime + NULL, // SetVirtualAddressMap + NULL, // ConvertPointer + NULL, // GetVariable + NULL, // GetNextVariableName + NULL, // SetVariable + NULL, // GetNextHighMonotonicCount + MockResetSystem, // ResetSystem + NULL, // UpdateCapsule + NULL, // QueryCapsuleCapabilities + NULL // QueryVariableInfo +}; +EFI_RUNTIME_SERVICES *gRT = &MockRuntime; + + +///================================================================================================ +///================================================================================================ +/// +/// TEST CASES +/// +///================================================================================================ +///================================================================================================ + +UNIT_TEST_STATUS +EFIAPI +ResetColdShouldIssueAColdReset ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value( MockResetSystem, ResetType, EfiResetCold ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetCold(); + + return UNIT_TEST_PASSED; +} // ResetColdShouldIssueAColdReset() + +UNIT_TEST_STATUS +EFIAPI +ResetWarmShouldIssueAWarmReset ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value( MockResetSystem, ResetType, EfiResetWarm ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetWarm(); + + return UNIT_TEST_PASSED; +} // ResetWarmShouldIssueAWarmReset() + +UNIT_TEST_STATUS +EFIAPI +ResetShutdownShouldIssueAShutdown ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value( MockResetSystem, ResetType, EfiResetShutdown ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetShutdown(); + + return UNIT_TEST_PASSED; +} // ResetShutdownShouldIssueAShutdown() + +UNIT_TEST_STATUS +EFIAPI +EnterS3ShouldDoNothing ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + // The lack of expected values will cause an error if MockResetSystem is called. + EnterS3WithImmediateWake(); + + return UNIT_TEST_PASSED; +} // EnterS3ShouldDoNothing() + +UNIT_TEST_STATUS +EFIAPI +ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value( MockResetSystem, ResetType, EfiResetPlatformSpecific ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetPlatformSpecific(0, NULL); + + return UNIT_TEST_PASSED; +} // ResetPlatformSpecificShouldIssueAPlatformSpecificReset() + +UNIT_TEST_STATUS +EFIAPI +ResetSystemShouldPassTheParametersThrough ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value( MockResetSystem, ResetType, EfiResetCold ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); + + expect_value( MockResetSystem, ResetType, EfiResetShutdown ); + expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); + + ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); + + return UNIT_TEST_PASSED; +} // ResetSystemShouldPassTheParametersThrough() + +///================================================================================================ +///================================================================================================ +/// +/// TEST ENGINE +/// +///================================================================================================ +///================================================================================================ + + +STATIC +EFI_STATUS +EFIAPI +UnitTestingEntry () +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; + UNIT_TEST_SUITE_HANDLE ResetTests; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); + if (EFI_ERROR( Status )) { + DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the B64 Encode Unit Test Suite. + // + Status = CreateUnitTestSuite( &ResetTests, Framework, "DxeResetSystemLib Reset Tests", "ResetSystemLib.Reset", NULL, NULL ); + if (EFI_ERROR( Status )){ + DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for ResetTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + +// --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- + AddTestCase( ResetTests, "ResetCold should issue a cold reset", "Cold", ResetColdShouldIssueAColdReset, NULL, NULL, NULL); + AddTestCase( ResetTests, "ResetWarm should issue a warm reset", "Warm", ResetWarmShouldIssueAWarmReset, NULL, NULL, NULL); + AddTestCase( ResetTests, "ResetShutdown should issue a shutdown", "Shutdown", ResetShutdownShouldIssueAShutdown, NULL, NULL, NULL); + AddTestCase( ResetTests, "EnterS3WithImmediateWake should not reset", "S3", EnterS3ShouldDoNothing, NULL, NULL, NULL); + AddTestCase( ResetTests, "ResetPlatformSpecific should issue a platform-specific reset", "Platform", ResetPlatformSpecificShouldIssueAPlatformSpecificReset, NULL, NULL, NULL); + AddTestCase( ResetTests, "ResetSystem should pass all parameters through", "Parameters", ResetSystemShouldPassTheParametersThrough, NULL, NULL, NULL); + + // + // Execute the tests. + // + Status = RunAllTestSuites( Framework ); + +EXIT: + if (Framework) { + FreeUnitTestFramework( Framework ); + } + + return Status; +} + +int +main ( + int argc, + char *argv[] + ) +{ + return UnitTestingEntry(); +} diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf new file mode 100644 index 00000000000..d902375a8ed --- /dev/null +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf @@ -0,0 +1,35 @@ +## @file +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = DxeResetSystemLibUnitTestHost + FILE_GUID = 83E35653-B943-4C5F-BA08-9B2996AE9273 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + DxeResetSystemLibUnitTest.c + + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + + +[LibraryClasses] + ResetSystemLib + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib diff --git a/MdeModulePkg/MdeModulePkg.ci.yaml b/MdeModulePkg/MdeModulePkg.ci.yaml index 0bf149f205e..b127d272579 100644 --- a/MdeModulePkg/MdeModulePkg.ci.yaml +++ b/MdeModulePkg/MdeModulePkg.ci.yaml @@ -9,6 +9,10 @@ "CompilerPlugin": { "DscPath": "MdeModulePkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestCompilerPlugin + "HostUnitTestCompilerPlugin": { + "DscPath": "Test/MdeModulePkgHostTest.dsc" + }, ## options defined ci/Plugin/CharEncodingCheck "CharEncodingCheck": { @@ -35,6 +39,11 @@ "IgnoreInf": [], "DscPath": "MdeModulePkg.dsc" }, + ## options defined ci/Plugin/HostUnitTestDscCompleteCheck + "HostUnitTestDscCompleteCheck": { + "IgnoreInf": [""], + "DscPath": "Test/MdeModulePkgHostTest.dsc" + }, ## options defined ci/Plugin/GuidCheck "GuidCheck": { diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc new file mode 100644 index 00000000000..f15fc7766e5 --- /dev/null +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -0,0 +1,29 @@ +## @file +# +# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdeModulePkgHostTest + PLATFORM_GUID = F74AF7C6-698C-4EBA-BA49-FF6816916354 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdeModulePkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[Components] + # + # Build MdeModulePkg HOST_APPLICATION Tests + # + MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf { + + ResetSystemLib|MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf + UefiRuntimeServicesTableLib|UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf + } diff --git a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c new file mode 100644 index 00000000000..7213733a43b --- /dev/null +++ b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c @@ -0,0 +1,9 @@ +/** @file -- MockLibraryClassLibNull.c +Generic library that could be anything. It could be a boat! + +Copyright (c) Microsoft Corporation. +SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +// I'm a comment! diff --git a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf new file mode 100644 index 00000000000..3e48a912b7b --- /dev/null +++ b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf @@ -0,0 +1,23 @@ +## @file +# Generic library that could be anything. It could be a boat! +# +# Copyright (c) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MockLibraryClassLibNull + FILE_GUID = E653BA0C-1EFA-4061-81B6-A7894BD35BD1 + MODULE_TYPE = BASE + VERSION_STRING = 1.0 + LIBRARY_CLASS = MockLibraryClassLib|HOST_APPLICATION + + +[Sources] + MockLibraryClassLibNull.c + + +[Packages] + MdePkg/MdePkg.dec diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index db5ffa34068..68c6f4fad63 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -15,9 +15,11 @@ PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 PACKAGE_VERSION = 1.00 +[Includes] + Library/CmockaLib/cmocka/include + [Includes.Common.Private] PrivateInclude - Library/CmockaLib/cmocka/include Library/CmockaLib/cmocka/include/cmockery [LibraryClasses.Common.Private] From 27cd81f2deaccd5b3790a1bb0b9ac6ed10ae066f Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 16 Jan 2020 19:58:26 -0800 Subject: [PATCH 361/384] Rather than depend on a "Framework" local variable, change the Assertion and Logging macros to us GetActiveFrameworkHandle() function. --- MdePkg/Include/Library/UnitTestLib.h | 39 +++++++++++++------ .../Library/UnitTestLib/RunTests.c | 14 +++++++ .../Library/UnitTestLib/RunTestsCmocka.c | 14 +++++++ .../Test/UnitTestFrameworkPkgHostTest.dsc | 1 + 4 files changed, 56 insertions(+), 12 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 07c7897461b..00f97261530 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -271,6 +271,21 @@ SaveFrameworkState ( IN UINTN ContextToSaveSize ); +/** + Internal helper function to return a handle to the currently executing framework. + This function is generally used for communication within the UnitTest framework, but is + defined here so that it can be consumed by the Assertion and Logging macros. + + There should be no need to consume as a test writer, but it's there if you need it. + + @retval Handle to the currently executing test framework. + +**/ +UNIT_TEST_FRAMEWORK_HANDLE +GetActiveFrameworkHandle ( + VOID + ); + /// /// Unit-Test Assertion Macros and Functions /// @@ -285,7 +300,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_TRUE(Expression) \ - if(!UnitTestAssertTrue (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + if(!UnitTestAssertTrue (GetActiveFrameworkHandle(), (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -300,7 +315,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_FALSE(Expression) \ - if(!UnitTestAssertFalse (Framework, (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + if(!UnitTestAssertFalse (GetActiveFrameworkHandle(), (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -315,7 +330,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertEqual (GetActiveFrameworkHandle(), (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -331,7 +346,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ - if(!UnitTestAssertMemEqual (Framework, (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertMemEqual (GetActiveFrameworkHandle(), (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -346,7 +361,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual (Framework, (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertNotEqual (GetActiveFrameworkHandle(), (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -361,7 +376,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError (Framework, Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertNotEfiError (GetActiveFrameworkHandle(), Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -376,7 +391,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual (Framework, Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertStatusEqual (GetActiveFrameworkHandle(), Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -391,7 +406,7 @@ SaveFrameworkState ( **/ #define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull (Framework, Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ + if(!UnitTestAssertNotNull (GetActiveFrameworkHandle(), Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -551,7 +566,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_ERROR(Format, ...) \ - UnitTestLog (Framework, DEBUG_ERROR, Format, ##__VA_ARGS__ ); + UnitTestLog (GetActiveFrameworkHandle(), DEBUG_ERROR, Format, ##__VA_ARGS__ ); /** Test logging macro that records a WARNING message in the test framework log. @@ -562,7 +577,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_WARNING(Format, ...) \ - UnitTestLog (Framework, DEBUG_WARN, Format, ##__VA_ARGS__ ); + UnitTestLog (GetActiveFrameworkHandle(), DEBUG_WARN, Format, ##__VA_ARGS__ ); /** Test logging macro that records an INFO message in the test framework log. @@ -573,7 +588,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_INFO(Format, ...) \ - UnitTestLog (Framework, DEBUG_INFO, Format, ##__VA_ARGS__ ); + UnitTestLog (GetActiveFrameworkHandle(), DEBUG_INFO, Format, ##__VA_ARGS__ ); /** Test logging macro that records a VERBOSE message in the test framework log. @@ -584,7 +599,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog (Framework, DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); + UnitTestLog (GetActiveFrameworkHandle(), DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); /** Helper function for the test logging macros. diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c index aaba00a5e2f..cb6f6f58ac7 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -13,6 +13,17 @@ #include #include + +STATIC UNIT_TEST_FRAMEWORK_HANDLE mFramework = NULL; + +UNIT_TEST_FRAMEWORK_HANDLE +GetActiveFrameworkHandle( + VOID + ) +{ + return mFramework; +} + STATIC EFI_STATUS RunTestSuite ( @@ -121,6 +132,7 @@ RunAllTestSuites ( DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); DEBUG ((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + mFramework = FrameworkHandle; // // Iterate all suites @@ -140,5 +152,7 @@ RunAllTestSuites ( SaveFrameworkState (FrameworkHandle, NULL, 0); OutputUnitTestFrameworkReport (FrameworkHandle); + mFramework = NULL; + return EFI_SUCCESS; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index cfeb3f1f468..c88959b9065 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -21,6 +21,17 @@ #include #include + +STATIC UNIT_TEST_FRAMEWORK_HANDLE mFramework = NULL; + +UNIT_TEST_FRAMEWORK_HANDLE +GetActiveFrameworkHandle( + VOID + ) +{ + return mFramework; +} + // // The currently active test suite // @@ -242,6 +253,7 @@ RunAllTestSuites ( DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); + mFramework = FrameworkHandle; // // Iterate all suites @@ -255,5 +267,7 @@ RunAllTestSuites ( } } + mFramework = NULL; + return EFI_SUCCESS; } diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 2bb8ff80120..e7e2da5b262 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -30,3 +30,4 @@ UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf + UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf From d438fc8c7e11cdeecff346b44423dd5326f8dc57 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Thu, 16 Jan 2020 22:38:39 -0800 Subject: [PATCH 362/384] Update docs with advanced testing instructions and known limitations. --- UnitTestFrameworkPkg/ReadMe.md | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 42503d5e2b4..74f286059e8 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -209,6 +209,16 @@ _Note_ that this early return can have implications for memory leakage. At the end, if all test criteria pass, you should return `UNIT_TEST_PASSED`. +### More Complex Cases + +To write more advanced tests, first take a look at all the Assertion and Logging macros provided in the framework. + +Beyond that, if you're writing host-based tests and want to take a dependency on the UnitTestFrameworkPkg, you can +leverage the `cmocka.h` interface and write tests with all the features of the Cmocka framework. + +Documentation for Cmocka can be found here: +https://api.cmocka.org/ + ## Development When using the EDK2 Pytools for CI testing, the host-based unit tests will be built and run on any build that includes the `NOOPT` build target. @@ -219,6 +229,27 @@ If you are trying to iterate on a single test, a convenient pattern is to build stuart_ci_build -c .pytool/CISettings.py TOOL_CHAIN_TAG=VS2017 -p MdePkg -t NOOPT BUILDMODULE=MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.inf ``` +## Known Limitations + +### PEI, DXE, SMM + +While sample tests have been provided for these execution environments, only cursory build validation +has been performed. Care has been taken while designing the frameworks to allow for execution during +boot phases, but only UEFI Shell and host-based tests have been thoroughly evaluated. Full support for +PEI, DXE, and SMM is forthcoming, but should be considered beta/staging for now. + +### Host-Based Support vs Other Tests + +The host-based test framework is powered internally by the Cmocka framework. As such, it has abilities +that the target-based tests don't (yet). It would be awesome if this meant that it was a super set of +the target-based tests, and it worked just like the target-based tests but with more features. Unfortunately, +this is not the case. While care has been taken to keep them as close a possible, there are a few known +inconsistencies that we're still ironing out. For example, the logging messages in the target-based tests +are cached internally and associated with the running test case. They can be saved later as part of the +reporting lib. This isn't currently possible with host-based. Only the assertion failures are logged. + +We will continue trying to make these as similar as possible. + ## Copyright Copyright (c) Microsoft Corporation. From a5235562444021e9c5aff08f45daa6b5b7952c7a Mon Sep 17 00:00:00 2001 From: Laszlo Ersek Date: Thu, 9 Jan 2020 22:00:39 +0100 Subject: [PATCH 363/384] UefiCpuPkg/PiSmmCpuDxeSmm: fix 2M->4K page splitting regression for PDEs In commit 4eee0cc7cc0d ("UefiCpuPkg/PiSmmCpu: Enable 5 level paging when CPU supports", 2019-07-12), the Page Directory Entry setting was regressed (corrupted) when splitting a 2MB page to 512 4KB pages, in the InitPaging() function. Consider the following hunk, displayed with $ git show --function-context --ignore-space-change 4eee0cc7cc0db > // > // If it is 2M page, check IsAddressSplit() > // > if (((*Pd & IA32_PG_PS) != 0) && IsAddressSplit (Address)) { > // > // Based on current page table, create 4KB page table for split area. > // > ASSERT (Address == (*Pd & PHYSICAL_ADDRESS_MASK)); > > Pt = AllocatePageTableMemory (1); > ASSERT (Pt != NULL); > > + *Pd = (UINTN) Pt | IA32_PG_RW | IA32_PG_P; > + > // Split it > - for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof(*Pt); PtIndex++) { > - Pt[PtIndex] = Address + ((PtIndex << 12) | mAddressEncMask | PAGE_ATTRIBUTE_BITS); > + for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof(*Pt); PtIndex++, Pt++) { > + *Pt = Address + ((PtIndex << 12) | mAddressEncMask | PAGE_ATTRIBUTE_BITS); > } // end for PT > *Pd = (UINT64)(UINTN)Pt | mAddressEncMask | PAGE_ATTRIBUTE_BITS; > } // end if IsAddressSplit > } // end for PD First, the new assignment to the Page Directory Entry (*Pd) is superfluous. That's because (a) we set (*Pd) after the Page Table Entry loop anyway, and (b) here we do not attempt to access the memory starting at "Address" (which is mapped by the original value of the Page Directory Entry). Second, appending "Pt++" to the incrementing expression of the PTE loop is a bug. It causes "Pt" to point *right past* the just-allocated Page Table, once we finish the loop. But the PDE assignment that immediately follows the loop assumes that "Pt" still points to the *start* of the new Page Table. The result is that the originally mapped 2MB page disappears from the processor's view. The PDE now points to a "Page Table" that is filled with garbage. The random entries in that "Page Table" will cause some virtual addresses in the original 2MB area to fault. Other virtual addresses in the same range will no longer have a 1:1 physical mapping, but be scattered over random physical page frames. The second phase of the InitPaging() function ("Go through page table and set several page table entries to absent or execute-disable") already manipulates entries in wrong Page Tables, for such PDEs that got split in the first phase. This issue has been caught as follows: - OVMF is started with 2001 MB of guest RAM. - This places the main SMRAM window at 0x7C10_1000. - The SMRAM management in the SMM Core links this SMRAM window into "mSmmMemoryMap", with a FREE_PAGE_LIST record placed at the start of the area. - At "SMM Ready To Lock" time, PiSmmCpuDxeSmm calls InitPaging(). The first phase (quoted above) decides to split the 2MB page at 0x7C00_0000 into 512 4KB pages, and corrupts the PDE. The new Page Table is allocated at 0x7CE0_D000, but the PDE is set to 0x7CE0_E000 (plus attributes 0x67). - Due to the corrupted PDE, the second phase of InitPaging() already looks up the PTE for Address=0x7C10_1000 in the wrong place. The second phase goes on to mark bogus PTEs as "NX". - PiSmmCpuDxeSmm calls SetMemMapAttributes(). Address 0x7C10_1000 is at the base of the SMRAM window, therefore it happens to be listed in the SMRAM map as an EfiConventionalMemory region. SetMemMapAttributes() calls SmmSetMemoryAttributes() to mark the region as XP. However, GetPageTableEntry() in ConvertMemoryPageAttributes() fails -- address 0x7C10_1000 is no longer mapped by anything! -- and so the attribute setting fails with RETURN_UNSUPPORTED. This error goes unnoticed, as SetMemMapAttributes() ignores the return value of SmmSetMemoryAttributes(). - When SetMemMapAttributes() reaches another entry in the SMRAM map, ConvertMemoryPageAttributes() decides it needs to split a 2MB page, and calls SplitPage(). - SplitPage() calls AllocatePageTableMemory() for the new Page Table, which takes us to InternalAllocMaxAddress() in the SMM Core. - The SMM core attempts to read the FREE_PAGE_LIST record at 0x7C10_1000. Because this virtual address is no longer mapped, the firmware crashes in InternalAllocMaxAddress(), when accessing (Pages->NumberOfPages). Remove the useless assignment to (*Pd) from before the loop. Revert the loop incrementing and the PTE assignment to the known good version. Cc: Eric Dong Cc: Ray Ni Ref: https://bugzilla.redhat.com/show_bug.cgi?id=1789335 Fixes: 4eee0cc7cc0db74489b99c19eba056b53eda6358 Signed-off-by: Laszlo Ersek Reviewed-by: Philippe Mathieu-Daude Reviewed-by: Ray Ni --- UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c index c5131526f0c..c47b5573e36 100644 --- a/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c +++ b/UefiCpuPkg/PiSmmCpuDxeSmm/SmmProfile.c @@ -657,11 +657,9 @@ InitPaging ( Pt = AllocatePageTableMemory (1); ASSERT (Pt != NULL); - *Pd = (UINTN) Pt | IA32_PG_RW | IA32_PG_P; - // Split it - for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof(*Pt); PtIndex++, Pt++) { - *Pt = Address + ((PtIndex << 12) | mAddressEncMask | PAGE_ATTRIBUTE_BITS); + for (PtIndex = 0; PtIndex < SIZE_4KB / sizeof(*Pt); PtIndex++) { + Pt[PtIndex] = Address + ((PtIndex << 12) | mAddressEncMask | PAGE_ATTRIBUTE_BITS); } // end for PT *Pd = (UINT64)(UINTN)Pt | mAddressEncMask | PAGE_ATTRIBUTE_BITS; } // end if IsAddressSplit From 47873d61be4e7cc695917d8872125b04362d500f Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 17 Jan 2020 10:30:23 -0800 Subject: [PATCH 364/384] Drop a test case that no longer aligns with upstream. --- .../UnitTest/DxeResetSystemLibUnitTest.c | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index 678496eaead..91fa74968e3 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -146,19 +146,6 @@ ResetShutdownShouldIssueAShutdown ( return UNIT_TEST_PASSED; } // ResetShutdownShouldIssueAShutdown() -UNIT_TEST_STATUS -EFIAPI -EnterS3ShouldDoNothing ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN UNIT_TEST_CONTEXT Context - ) -{ - // The lack of expected values will cause an error if MockResetSystem is called. - EnterS3WithImmediateWake(); - - return UNIT_TEST_PASSED; -} // EnterS3ShouldDoNothing() - UNIT_TEST_STATUS EFIAPI ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( @@ -237,7 +224,6 @@ UnitTestingEntry () AddTestCase( ResetTests, "ResetCold should issue a cold reset", "Cold", ResetColdShouldIssueAColdReset, NULL, NULL, NULL); AddTestCase( ResetTests, "ResetWarm should issue a warm reset", "Warm", ResetWarmShouldIssueAWarmReset, NULL, NULL, NULL); AddTestCase( ResetTests, "ResetShutdown should issue a shutdown", "Shutdown", ResetShutdownShouldIssueAShutdown, NULL, NULL, NULL); - AddTestCase( ResetTests, "EnterS3WithImmediateWake should not reset", "S3", EnterS3ShouldDoNothing, NULL, NULL, NULL); AddTestCase( ResetTests, "ResetPlatformSpecific should issue a platform-specific reset", "Platform", ResetPlatformSpecificShouldIssueAPlatformSpecificReset, NULL, NULL, NULL); AddTestCase( ResetTests, "ResetSystem should pass all parameters through", "Parameters", ResetSystemShouldPassTheParametersThrough, NULL, NULL, NULL); From 61278d5624f19ab3be8477d05ed785e2deb4b16d Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 17 Jan 2020 10:30:35 -0800 Subject: [PATCH 365/384] Add a valid dependency to fix CI tests. --- MdeModulePkg/MdeModulePkg.ci.yaml | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/MdeModulePkg/MdeModulePkg.ci.yaml b/MdeModulePkg/MdeModulePkg.ci.yaml index b127d272579..3b6e7470757 100644 --- a/MdeModulePkg/MdeModulePkg.ci.yaml +++ b/MdeModulePkg/MdeModulePkg.ci.yaml @@ -28,7 +28,9 @@ "ArmPkg/ArmPkg.dec" # this should be fixed by promoting an abstraction ], # For host based unit tests - "AcceptableDependencies-HOST_APPLICATION":[], + "AcceptableDependencies-HOST_APPLICATION":[ + "UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec" + ], # For UEFI shell based apps "AcceptableDependencies-UEFI_APPLICATION":[], "IgnoreInf": [] From 335851fb2daf2fc0d50343889417139462cd143e Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 17 Jan 2020 10:42:55 -0800 Subject: [PATCH 366/384] Remove GetActiveFrameworkHandle from the public interface. --- MdePkg/Include/Library/UnitTestLib.h | 48 +++++-------------- .../Library/UnitTestLib/Assert.c | 48 ++++++++++++------- .../Library/UnitTestLib/AssertCmocka.c | 8 ---- .../Library/UnitTestLib/Log.c | 4 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 15 ++++++ 5 files changed, 62 insertions(+), 61 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 00f97261530..d7eacbbb7e3 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -271,21 +271,6 @@ SaveFrameworkState ( IN UINTN ContextToSaveSize ); -/** - Internal helper function to return a handle to the currently executing framework. - This function is generally used for communication within the UnitTest framework, but is - defined here so that it can be consumed by the Assertion and Logging macros. - - There should be no need to consume as a test writer, but it's there if you need it. - - @retval Handle to the currently executing test framework. - -**/ -UNIT_TEST_FRAMEWORK_HANDLE -GetActiveFrameworkHandle ( - VOID - ); - /// /// Unit-Test Assertion Macros and Functions /// @@ -300,7 +285,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_TRUE(Expression) \ - if(!UnitTestAssertTrue (GetActiveFrameworkHandle(), (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + if(!UnitTestAssertTrue ((Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -315,7 +300,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_FALSE(Expression) \ - if(!UnitTestAssertFalse (GetActiveFrameworkHandle(), (Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ + if(!UnitTestAssertFalse ((Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -330,7 +315,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual (GetActiveFrameworkHandle(), (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -346,7 +331,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ - if(!UnitTestAssertMemEqual (GetActiveFrameworkHandle(), (UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertMemEqual ((UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -361,7 +346,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual (GetActiveFrameworkHandle(), (UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertNotEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -376,7 +361,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError (GetActiveFrameworkHandle(), Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertNotEfiError (Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -391,7 +376,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual (GetActiveFrameworkHandle(), Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertStatusEqual (Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -406,7 +391,7 @@ GetActiveFrameworkHandle ( **/ #define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull (GetActiveFrameworkHandle(), Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ + if(!UnitTestAssertNotNull (Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -419,7 +404,6 @@ GetActiveFrameworkHandle ( BOOLEAN EFIAPI UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -436,7 +420,6 @@ UnitTestAssertTrue ( BOOLEAN EFIAPI UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -453,7 +436,6 @@ UnitTestAssertFalse ( BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -470,7 +452,6 @@ UnitTestAssertNotEfiError ( BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -489,7 +470,6 @@ UnitTestAssertEqual ( BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINTN ValueA, IN UINTN ValueB, IN UINTN Length, @@ -509,7 +489,6 @@ UnitTestAssertMemEqual ( BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -528,7 +507,6 @@ UnitTestAssertNotEqual ( BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN EFI_STATUS Expected, IN CONST CHAR8 *FunctionName, @@ -546,7 +524,6 @@ UnitTestAssertStatusEqual ( BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN VOID* Pointer, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -566,7 +543,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_ERROR(Format, ...) \ - UnitTestLog (GetActiveFrameworkHandle(), DEBUG_ERROR, Format, ##__VA_ARGS__ ); + UnitTestLog (DEBUG_ERROR, Format, ##__VA_ARGS__ ); /** Test logging macro that records a WARNING message in the test framework log. @@ -577,7 +554,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_WARNING(Format, ...) \ - UnitTestLog (GetActiveFrameworkHandle(), DEBUG_WARN, Format, ##__VA_ARGS__ ); + UnitTestLog (DEBUG_WARN, Format, ##__VA_ARGS__ ); /** Test logging macro that records an INFO message in the test framework log. @@ -588,7 +565,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_INFO(Format, ...) \ - UnitTestLog (GetActiveFrameworkHandle(), DEBUG_INFO, Format, ##__VA_ARGS__ ); + UnitTestLog (DEBUG_INFO, Format, ##__VA_ARGS__ ); /** Test logging macro that records a VERBOSE message in the test framework log. @@ -599,7 +576,7 @@ UnitTestAssertNotNull ( **/ #define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog (GetActiveFrameworkHandle(), DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); + UnitTestLog (DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); /** Helper function for the test logging macros. @@ -610,7 +587,6 @@ UnitTestAssertNotNull ( VOID EFIAPI UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINTN ErrorLevel, IN CONST CHAR8 *Format, ... diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index 2447f6c91d5..83a64ab5aa6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -65,7 +65,6 @@ UnitTestLogFailure ( BOOLEAN EFIAPI UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -73,9 +72,12 @@ UnitTestAssertTrue ( IN CONST CHAR8 *Description ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if (!Expression) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); - UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); + UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); } return Expression; } @@ -83,7 +85,6 @@ UnitTestAssertTrue ( BOOLEAN EFIAPI UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -91,9 +92,12 @@ UnitTestAssertFalse ( IN CONST CHAR8 *Description ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if (Expression) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); } return !Expression; } @@ -101,7 +105,6 @@ UnitTestAssertFalse ( BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -109,9 +112,12 @@ UnitTestAssertNotEfiError ( IN CONST CHAR8 *Description ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if (EFI_ERROR (Status)) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); - UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); + UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); } return !EFI_ERROR( Status ); } @@ -119,7 +125,6 @@ UnitTestAssertNotEfiError ( BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -129,9 +134,12 @@ UnitTestAssertEqual ( IN CONST CHAR8 *DescriptionB ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if ((ValueA != ValueB)) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); + UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); } return (ValueA == ValueB); } @@ -139,7 +147,6 @@ UnitTestAssertEqual ( BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINTN ValueA, IN UINTN ValueB, IN UINTN Length, @@ -150,9 +157,12 @@ UnitTestAssertMemEqual ( IN CONST CHAR8 *DescriptionB ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); return FALSE; } return TRUE; @@ -161,7 +171,6 @@ UnitTestAssertMemEqual ( BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -171,9 +180,12 @@ UnitTestAssertNotEqual ( IN CONST CHAR8 *DescriptionB ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if ((ValueA == ValueB)) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); + UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); } return (ValueA != ValueB); } @@ -181,7 +193,6 @@ UnitTestAssertNotEqual ( BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN EFI_STATUS Expected, IN CONST CHAR8 *FunctionName, @@ -190,9 +201,12 @@ UnitTestAssertStatusEqual ( IN CONST CHAR8 *Description ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if ((Status != Expected)) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); - UnitTestLog (Framework, DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); + UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); } return (Status == Expected); } @@ -200,7 +214,6 @@ UnitTestAssertStatusEqual ( BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN VOID* Pointer, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -208,9 +221,12 @@ UnitTestAssertNotNull ( IN CONST CHAR8 *PointerName ) { + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); if (Pointer == NULL) { UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - UnitTestLog (Framework, DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); } return (Pointer != NULL); } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c index f05bf8ea602..ced9dfecac5 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -22,7 +22,6 @@ BOOLEAN EFIAPI UnitTestAssertTrue ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -41,7 +40,6 @@ UnitTestAssertTrue ( BOOLEAN EFIAPI UnitTestAssertFalse ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN BOOLEAN Expression, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -60,7 +58,6 @@ UnitTestAssertFalse ( BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -79,7 +76,6 @@ UnitTestAssertNotEfiError ( BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -100,7 +96,6 @@ UnitTestAssertEqual ( BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINTN ValueA, IN UINTN ValueB, IN UINTN Length, @@ -125,7 +120,6 @@ UnitTestAssertMemEqual ( BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINT64 ValueA, IN UINT64 ValueB, IN CONST CHAR8 *FunctionName, @@ -146,7 +140,6 @@ UnitTestAssertNotEqual ( BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN EFI_STATUS Status, IN EFI_STATUS Expected, IN CONST CHAR8 *FunctionName, @@ -166,7 +159,6 @@ UnitTestAssertStatusEqual ( BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN VOID* Pointer, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index 4a494954541..db97191e595 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -149,7 +149,6 @@ UnitTestLogInit ( VOID EFIAPI UnitTestLog ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UINTN ErrorLevel, IN CONST CHAR8 *Format, ... @@ -160,6 +159,9 @@ UnitTestLog ( CONST CHAR8 *LogTypePrefix; VA_LIST Marker; UINTN LogLevel; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + + Framework = GetActiveFrameworkHandle(); LogTypePrefix = NULL; LogLevel = (UINTN)PcdGet32 (UnitTestLogLevel); diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 49e38fedb34..2d054245373 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -146,4 +146,19 @@ UnitTestLogInit ( IN UINTN BufferSize OPTIONAL ); +/** + Internal helper function to return a handle to the currently executing framework. + This function is generally used for communication within the UnitTest framework, but is + defined here so that it can be consumed by the Assertion and Logging macros. + + There should be no need to consume as a test writer, but it's there if you need it. + + @retval Handle to the currently executing test framework. + +**/ +UNIT_TEST_FRAMEWORK_HANDLE +GetActiveFrameworkHandle ( + VOID + ); + #endif From 078df5e0b4541a2e0ffd6997c2d5b1fffc46cabc Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Fri, 17 Jan 2020 13:01:25 -0800 Subject: [PATCH 367/384] Fix the ADO jobs. --- .azurepipelines/templates/pr-gate-build-job.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/.azurepipelines/templates/pr-gate-build-job.yml b/.azurepipelines/templates/pr-gate-build-job.yml index fe8a2d80bb0..61868554d43 100644 --- a/.azurepipelines/templates/pr-gate-build-job.yml +++ b/.azurepipelines/templates/pr-gate-build-job.yml @@ -25,7 +25,7 @@ jobs: Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_MDEMODULE_DEBUG: Build.Pkgs: 'MdeModulePkg' - Build.Targets: 'DEBUG' + Build.Targets: 'DEBUG,NOOPT' TARGET_MDEMODULE_RELEASE: Build.Pkgs: 'MdeModulePkg' Build.Targets: 'RELEASE,NO-TARGET' @@ -36,8 +36,8 @@ jobs: Build.Pkgs: 'PcAtChipsetPkg,ShellPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET' TARGET_FMP_FAT_TEST: - Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestPkg' - Build.Targets: 'DEBUG,RELEASE,NO-TARGET' + Build.Pkgs: 'FmpDevicePkg,FatPkg,UnitTestFrameworkPkg' + Build.Targets: 'DEBUG,RELEASE,NO-TARGET,NOOPT' TARGET_CRYPTO: Build.Pkgs: 'CryptoPkg' Build.Targets: 'DEBUG,RELEASE,NO-TARGET' From 4f9db3c615be7817ed51d4e4410c551d6b80ef78 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 17 Jan 2020 12:36:38 -0800 Subject: [PATCH 368/384] UnitTestFrameworkPkg/UnitTestLib: Simplify assert APIs Move Framwork into internal API. Fix code style issues Signed-off-by: Michael D Kinney --- .../Library/UnitTestLib/Assert.c | 299 ++++++++++++------ 1 file changed, 202 insertions(+), 97 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index 83a64ab5aa6..a302a663df6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -24,13 +24,16 @@ AddUnitTestFailure ( // // Make sure that you're cooking with gas. // - if (UnitTest == NULL || FailureMessage == NULL) - { + if (UnitTest == NULL || FailureMessage == NULL) { return EFI_INVALID_PARAMETER; } UnitTest->FailureType = FailureType; - AsciiStrCpyS (&UnitTest->FailureMessage[0], UNIT_TEST_TESTFAILUREMSG_LENGTH, FailureMessage); + AsciiStrCpyS ( + &UnitTest->FailureMessage[0], + UNIT_TEST_TESTFAILUREMSG_LENGTH, + FailureMessage + ); return EFI_SUCCESS; } @@ -38,14 +41,19 @@ AddUnitTestFailure ( STATIC VOID UnitTestLogFailure ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, - IN FAILURE_TYPE FailureType, - IN CONST CHAR8 *Format, + IN FAILURE_TYPE FailureType, + IN CONST CHAR8 *Format, ... ) { - CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - VA_LIST Marker; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + VA_LIST Marker; + + // + // Get active Framework handle + // + Framework = GetActiveFrameworkHandle(); // // Convert the message to an ASCII String @@ -57,7 +65,11 @@ UnitTestLogFailure ( // // Finally, add the string to the log. // - AddUnitTestFailure (((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, LogString, FailureType); + AddUnitTestFailure ( + ((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, + LogString, + FailureType + ); return; } @@ -65,19 +77,27 @@ UnitTestLogFailure ( BOOLEAN EFIAPI UnitTestAssertTrue ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if (!Expression) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTTRUE, "%a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description); - UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, Description ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTTRUE, + "%a::%d Expression (%a) is not TRUE!\n", + FunctionName, + LineNumber, + Description + ); + UnitTestLog (DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", + FunctionName, + LineNumber, + Description + ); } return Expression; } @@ -85,19 +105,28 @@ UnitTestAssertTrue ( BOOLEAN EFIAPI UnitTestAssertFalse ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if (Expression) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTFALSE, "%a::%d Expression(%a) is not FALSE!\n", FunctionName, LineNumber, Description ); - UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, Description ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTFALSE, + "%a::%d Expression(%a) is not FALSE!\n", + FunctionName, + LineNumber, + Description + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", + FunctionName, + LineNumber, + Description + ); } return !Expression; } @@ -105,19 +134,30 @@ UnitTestAssertFalse ( BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if (EFI_ERROR (Status)) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEFIERROR, "%a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status); - UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, Description, Status ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTNOTEFIERROR, + "%a::%d Status '%a' is EFI_ERROR (%r)!\n", + FunctionName, + LineNumber, + Description, + Status + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", + FunctionName, + LineNumber, + Description, + Status + ); } return !EFI_ERROR( Status ); } @@ -125,21 +165,36 @@ UnitTestAssertNotEfiError ( BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if ((ValueA != ValueB)) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, "%a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTEQUAL, + "%a::%d Value %a != %a (%d != %d)!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + ValueA, + ValueB + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + ValueA, + ValueB + ); } return (ValueA == ValueB); } @@ -147,22 +202,35 @@ UnitTestAssertEqual ( BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINTN ValueA, + IN UINTN ValueB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTEQUAL, __FUNCTION__, "%a::%d Memory at %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); - UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, Length); + UnitTestLogFailure ( + FAILURETYPE_ASSERTEQUAL, + "%a::%d Memory at %a != %a for length %d bytes!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + Length + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + Length + ); return FALSE; } return TRUE; @@ -171,21 +239,36 @@ UnitTestAssertMemEqual ( BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if ((ValueA == ValueB)) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTEQUAL,"%a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, DescriptionA, DescriptionB, ValueA, ValueB); - UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber,DescriptionA, DescriptionB, ValueA, ValueB ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTNOTEQUAL, + "%a::%d Value %a == %a (%d == %d)!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + ValueA, + ValueB + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", + FunctionName, + LineNumber, + DescriptionA, + DescriptionB, + ValueA, + ValueB + ); } return (ValueA != ValueB); } @@ -193,20 +276,33 @@ UnitTestAssertNotEqual ( BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if ((Status != Expected)) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTSTATUSEQUAL, "%a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected); - UnitTestLog (DEBUG_ERROR,"[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, Description, Status, Expected ); + UnitTestLogFailure ( + FAILURETYPE_ASSERTSTATUSEQUAL, + "%a::%d Status '%a' is %r, should be %r!\n", + FunctionName, + LineNumber, + Description, + Status, + Expected + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", + FunctionName, + LineNumber, + Description, + Status, + Expected + ); } return (Status == Expected); } @@ -214,19 +310,28 @@ UnitTestAssertStatusEqual ( BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName + IN VOID* Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; - - Framework = GetActiveFrameworkHandle(); if (Pointer == NULL) { - UnitTestLogFailure (Framework, FAILURETYPE_ASSERTNOTNULL, "%a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); - UnitTestLog (DEBUG_ERROR, "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, PointerName); + UnitTestLogFailure ( + FAILURETYPE_ASSERTNOTNULL, + "%a::%d Pointer (%a) is NULL!\n", + FunctionName, + LineNumber, + PointerName + ); + UnitTestLog ( + DEBUG_ERROR, + "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", + FunctionName, + LineNumber, + PointerName + ); } return (Pointer != NULL); } From 5a675d880fb2c6f6f79ce0fcf04c5a49bb53d362 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 17 Jan 2020 15:00:35 -0800 Subject: [PATCH 369/384] MdePkg/Include/UnitTestLib: Make all handle types unique * Add a unique type for each handle type to generate compiler error if wrong handle is used with anu unit test API * Fix incorrect handle type in RunAllTestSuites() * Fix incorrect handle type in FreeUnitTestFramework() * Start clean up of function headers Signed-off-by: Michael D Kinney --- MdePkg/Include/Library/UnitTestLib.h | 195 ++++++++++++++++----------- 1 file changed, 120 insertions(+), 75 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index d7eacbbb7e3..f52548c9a22 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -20,9 +20,27 @@ typedef UINT32 UNIT_TEST_STATUS; #define UNIT_TEST_RUNNING (0xFFFFFFFE) #define UNIT_TEST_PENDING (0xFFFFFFFF) -typedef VOID* UNIT_TEST_FRAMEWORK_HANDLE; // Same as a UNIT_TEST_FRAMEWORK* -typedef VOID* UNIT_TEST_SUITE_HANDLE; // Same as a UNIT_TEST_SUITE* -typedef VOID* UNIT_TEST_HANDLE; // Same as a UNIT_TEST* +/// +/// Unit Test Framwework Handle +/// +struct UNIT_TEST_FRAMEWORK_OBJECT; +typedef struct UNIT_TEST_FRAMEWORK_OBJECT *UNIT_TEST_FRAMEWORK_HANDLE; + +/// +/// Unit Test Suite Handle +/// +struct UNIT_TEST_SUITE_OBJECT; +typedef struct UNIT_TEST_SUITE_OBJECT *UNIT_TEST_SUITE_HANDLE; + +/// +/// Unit Test Handle +/// +struct UNIT_TEST_OBJECT; +typedef struct UNIT_TEST_OBJECT *UNIT_TEST_HANDLE; + +/// +/// Unit Test Context +/// typedef VOID* UNIT_TEST_CONTEXT; /** @@ -30,17 +48,19 @@ typedef VOID* UNIT_TEST_CONTEXT; Funtions with this prototype are registered to be dispatched by the UnitTest framework, and results are recorded as test Pass or Fail. - @param[in] Framework A handle to the current running framework that dispatched the test. - Necessary for recording certain test events with the framework. - @param[in] Context [Optional] An optional paramter that enables: 1) test-case reuse with varied - parameters and 2) test-case re-entry for Target tests that need a reboot. - This parameter is a VOID* and it is the responsibility of the test - author to ensure that the contents are well understood by all test - cases that may consume it. - + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. - @retval UNIT_TEST_PASSED Test has completed and test case was successful. - @retval UNIT_TEST_ERROR_TEST_FAILED A test assertion has failed. + @retval UNIT_TEST_PASSED Test has completed and test case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test assertion has failed. **/ typedef @@ -57,11 +77,19 @@ UNIT_TEST_STATUS UnitTest framework prior to a given test case. If this prereq function returns UNIT_TEST_ERROR_PREREQ_NOT_MET, the test case will be skipped. - @param[in] Framework Identical to UNIT_TEST_FUNCTION. - @param[in] Context Identical to UNIT_TEST_FUNCTION. + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. - @retval UNIT_TEST_PASSED Test case prerequisites are met. - @retval UNIT_TEST_ERROR_PREREQ_NOT_MET Test case should be skipped. + @retval UNIT_TEST_PASSED Test case prerequisites are met. + @retval UNIT_TEST_ERROR_PREREQ_NOT_MET Test case should be skipped. **/ typedef @@ -79,11 +107,19 @@ UNIT_TEST_STATUS The purpose of this function is to clean up any global state or test data. - @param[in] Framework Identical to UNIT_TEST_FUNCTION. - @param[in] Context Identical to UNIT_TEST_FUNCTION. + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. - @retval UNIT_TEST_PASSED Test case cleanup succeeded. - @retval UNIT_TEST_ERROR_CLEANUP_FAILED Test case cleanup failed. + @retval UNIT_TEST_PASSED Test case cleanup succeeded. + @retval UNIT_TEST_ERROR_CLEANUP_FAILED Test case cleanup failed. **/ typedef @@ -101,7 +137,9 @@ VOID The purpose of this function is to set up any global state or test data. - @param[in] Framework Identical to UNIT_TEST_FUNCTION. + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. **/ typedef @@ -118,7 +156,9 @@ VOID The purpose of this function is to clean up any global state or test data. - @param[in] Framework Identical to UNIT_TEST_FUNCTION. + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. **/ typedef @@ -136,13 +176,13 @@ VOID This function registers the test name and also initializes the internal state of the test framework to receive any new suites and tests. - @param Framework - Unit test framework to be created. - @param Title - String name of the framework. String is copied. - @param ShortTitle - Short string name of the framework. String is copied. - @param VersionString - Version string for the framework. String is copied. + @param[out] Framework Unit test framework to be created. + @param[in] Title String name of the framework. String is copied. + @param[in] ShortTitle Short string name of the framework. String is copied. + @param[in] VersionString Version string for the framework. String is copied. - @retval Success - @retval EFI_ERROR() + @retval EFI_SUCCESS The unit test framework was initialized. + @retval Other The unit test framework could not be initialized. **/ EFI_STATUS @@ -159,15 +199,15 @@ InitUnitTestFramework ( At least one test suite must be registered, because all test cases must be within a unit test suite. - @param Suite - Suite to create - @param Framework - Framework to add suite to - @param Title - String name of the suite. String is copied. - @param Package - String name of the package. String is copied. - @param Sup - Setup function, runs before suite. - @param Tdn - Teardown function, runs after suite. + @param[out] Suite Suite to create + @param[in] Framework Framework to add suite to + @param[in] Title String name of the suite. String is copied. + @param[in] Package String name of the package. String is copied. + @param[in] Sup Setup function, runs before suite. + @param[in] Tdn Teardown function, runs after suite. - @retval Success - @retval EFI_OUT_OF_RESOURCES + @retval EFI_SUCCESS The unit test suite was created. + @retval Other The unit test suite could not be created. **/ EFI_STATUS @@ -184,16 +224,17 @@ CreateUnitTestSuite ( /** Adds test case to Suite - @param Suite - Suite to add test to. - @param Description - String describing test. String is copied. - @param ClassName - String name of the test. String is copied. - @param Func - Test function. - @param PreReq - Prep function, runs before test. - @param CleanUp - Clean up function, runs after test. - @param Context - Pointer to context. + @param[in] Suite Suite to add test to. + @param[in] Description String describing test. String is copied. + @param[in] ClassName String name of the test. String is copied. + @param[in] Func Test function. + @param[in] PreReq Prep function, runs before test. + @param[in] CleanUp Clean up function, runs after test. + @param[in] Context Pointer to context. - @retval Success - @retval EFI_OUT_OF_RESOURCES + @retval EFI_SUCCESS The unit test case was added to Suite. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to add + the unit test case to Suite. **/ EFI_STATUS @@ -215,16 +256,18 @@ AddTestCase ( this function will cause the test framework to dispatch all test cases in sequence and record the results for reporting. - @param[in] Framework + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. - @retval Success - @retval EFI_ERROR() + @retval Success + @retval EFI_ERROR() **/ EFI_STATUS EFIAPI -RunAllTestSuites( - IN UNIT_TEST_SUITE_HANDLE Framework +RunAllTestSuites ( + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ); /** @@ -233,16 +276,18 @@ RunAllTestSuites( After tests are run, this will teardown the entire framework and free all allocated data within. - @param[in] Framework + @param[in] Framework A handle to the current running framework that + dispatched the test. Necessary for recording certain + test events with the framework. - @retval Success - @retval EFI_ERROR() + @retval Success + @retval EFI_ERROR() **/ EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_SUITE_HANDLE Framework + IN UNIT_TEST_FRAMEWORK_HANDLE Framework ); /** @@ -255,12 +300,12 @@ FreeUnitTestFramework ( Generally called from within a test case prior to quitting or rebooting. @param[in] Framework - @param[in] ContextToSave A buffer of test case-specific data to be saved along with framework - state. Will be passed as "Context" to the test case upon resume. - @param[in] ContextToSaveSize Size of the ContextToSave buffer. + @param[in] ContextToSave A buffer of test case-specific data to be saved along with framework + state. Will be passed as "Context" to the test case upon resume. + @param[in] ContextToSaveSize Size of the ContextToSave buffer. - @retval Success - @retval EFI_ERROR() + @retval Success + @retval EFI_ERROR() **/ EFI_STATUS @@ -311,7 +356,7 @@ SaveFrameworkState ( If the values are equal, execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param ValueA, ValueB Values to be compared for equality. Will be compared as UINT64. + @param ValueA, ValueB Values to be compared for equality. Will be compared as UINT64. **/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ @@ -326,8 +371,8 @@ SaveFrameworkState ( If the buffers are equal, execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param ValueA, ValueB Pointers to the buffers for comparison. - @param Length Number of bytes to compare. + @param ValueA, ValueB Pointers to the buffers for comparison. + @param Length Number of bytes to compare. **/ #define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ @@ -342,7 +387,7 @@ SaveFrameworkState ( If the values are non-equal, execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param ValueA, ValueB Values to be compared for inequality. Will be compared as UINT64. + @param ValueA, ValueB Values to be compared for inequality. Will be compared as UINT64. **/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ @@ -357,7 +402,7 @@ SaveFrameworkState ( If the status is !EFI_ERROR(), execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param Status Status to be checked. + @param Status Status to be checked. **/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ @@ -372,7 +417,7 @@ SaveFrameworkState ( If the values are equal, execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param Status, Expected Values to be compared for equality. + @param Status, Expected Values to be compared for equality. **/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ @@ -387,7 +432,7 @@ SaveFrameworkState ( If the pointer is not NULL, execution will continue. Otherwise, the test case will immediately return UNIT_TEST_ERROR_TEST_FAILED. - @param Pointer Pointer to be checked. + @param Pointer Pointer to be checked. **/ #define UT_ASSERT_NOT_NULL(Pointer) \ @@ -538,8 +583,8 @@ UnitTestAssertNotNull ( Test logging macro that records an ERROR message in the test framework log. Record will be associated with this test case during reporting. - @param Format Standard C formatting string. - @param ... Print args. + @param Format Standard C formatting string. + @param ... Print args. **/ #define UT_LOG_ERROR(Format, ...) \ @@ -549,8 +594,8 @@ UnitTestAssertNotNull ( Test logging macro that records a WARNING message in the test framework log. Record will be associated with this test case during reporting. - @param Format Standard C formatting string. - @param ... Print args. + @param Format Standard C formatting string. + @param ... Print args. **/ #define UT_LOG_WARNING(Format, ...) \ @@ -560,8 +605,8 @@ UnitTestAssertNotNull ( Test logging macro that records an INFO message in the test framework log. Record will be associated with this test case during reporting. - @param Format Standard C formatting string. - @param ... Print args. + @param Format Standard C formatting string. + @param ... Print args. **/ #define UT_LOG_INFO(Format, ...) \ @@ -571,8 +616,8 @@ UnitTestAssertNotNull ( Test logging macro that records a VERBOSE message in the test framework log. Record will be associated with this test case during reporting. - @param Format Standard C formatting string. - @param ... Print args. + @param Format Standard C formatting string. + @param ... Print args. **/ #define UT_LOG_VERBOSE(Format, ...) \ From 2c073bc149ff2fc8dad3059cae339a97cd3101ce Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 17 Jan 2020 15:07:31 -0800 Subject: [PATCH 370/384] UnitTestFrameworkPlg/UnitTestLib: Clean up handle usage * UnitTestLogInit() - Use UNIT_TEST * instead of UNIT_TEST_HANDLE. This is internal API that does not need to use handle. * Add ASSERT() to GetActiveFrameworkHandle() to make sure mFrameworkHandle is not NULL. This catches a call to a unit test without using RunAllTestCases(). * Fix incorrect handle type usage. Signed-off-by: Michael D Kinney --- .../Library/UnitTestLib/Assert.c | 6 ++--- .../Library/UnitTestLib/Log.c | 26 ++++++++----------- .../Library/UnitTestLib/RunTests.c | 11 ++++---- .../Library/UnitTestLib/RunTestsCmocka.c | 23 ++++++++-------- .../Library/UnitTestLib/UnitTestLib.c | 22 +++++++++------- .../PrivateInclude/UnitTestFrameworkTypes.h | 6 ++--- 6 files changed, 46 insertions(+), 48 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index a302a663df6..00adc0528e6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -46,14 +46,14 @@ UnitTestLogFailure ( ... ) { - UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle; CHAR8 LogString[UNIT_TEST_TESTFAILUREMSG_LENGTH]; VA_LIST Marker; // // Get active Framework handle // - Framework = GetActiveFrameworkHandle(); + FrameworkHandle = GetActiveFrameworkHandle (); // // Convert the message to an ASCII String @@ -66,7 +66,7 @@ UnitTestLogFailure ( // Finally, add the string to the log. // AddUnitTestFailure ( - ((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, + ((UNIT_TEST_FRAMEWORK *)FrameworkHandle)->CurrentTest, LogString, FailureType ); diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index db97191e595..718b0b64f6b 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -109,15 +109,11 @@ AddStringToUnitTestLog ( VOID EFIAPI UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer, OPTIONAL - IN UINTN BufferSize OPTIONAL + IN OUT UNIT_TEST *Test, + IN UINT8 *Buffer, OPTIONAL + IN UINTN BufferSize OPTIONAL ) { - UNIT_TEST *Test; - - Test = (UNIT_TEST *)TestHandle; - // // Make sure that you're cooking with gas. // @@ -154,14 +150,14 @@ UnitTestLog ( ... ) { - CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; - CONST CHAR8 *LogTypePrefix; - VA_LIST Marker; - UINTN LogLevel; - UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle; + CHAR8 NewFormatString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; + CONST CHAR8 *LogTypePrefix; + VA_LIST Marker; + UINTN LogLevel; - Framework = GetActiveFrameworkHandle(); + FrameworkHandle = GetActiveFrameworkHandle (); LogTypePrefix = NULL; LogLevel = (UINTN)PcdGet32 (UnitTestLogLevel); @@ -194,5 +190,5 @@ UnitTestLog ( // // Finally, add the string to the log. // - AddStringToUnitTestLog (((UNIT_TEST_FRAMEWORK *)Framework)->CurrentTest, LogString); + AddStringToUnitTestLog (((UNIT_TEST_FRAMEWORK *)FrameworkHandle)->CurrentTest, LogString); } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c index cb6f6f58ac7..afc25cf6652 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -14,14 +14,15 @@ #include -STATIC UNIT_TEST_FRAMEWORK_HANDLE mFramework = NULL; +STATIC UNIT_TEST_FRAMEWORK_HANDLE mFrameworkHandle = NULL; UNIT_TEST_FRAMEWORK_HANDLE -GetActiveFrameworkHandle( +GetActiveFrameworkHandle ( VOID ) { - return mFramework; + ASSERT (mFrameworkHandle != NULL); + return mFrameworkHandle; } STATIC @@ -132,7 +133,7 @@ RunAllTestSuites ( DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); DEBUG ((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - mFramework = FrameworkHandle; + mFrameworkHandle = FrameworkHandle; // // Iterate all suites @@ -152,7 +153,7 @@ RunAllTestSuites ( SaveFrameworkState (FrameworkHandle, NULL, 0); OutputUnitTestFrameworkReport (FrameworkHandle); - mFramework = NULL; + mFrameworkHandle = NULL; return EFI_SUCCESS; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index c88959b9065..f1b5a7d5ac2 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -22,14 +22,15 @@ #include -STATIC UNIT_TEST_FRAMEWORK_HANDLE mFramework = NULL; +STATIC UNIT_TEST_FRAMEWORK_HANDLE mFrameworkHandle = NULL; UNIT_TEST_FRAMEWORK_HANDLE -GetActiveFrameworkHandle( +GetActiveFrameworkHandle ( VOID ) { - return mFramework; + ASSERT (mFrameworkHandle != NULL); + return mFrameworkHandle; } // @@ -50,14 +51,13 @@ CmockaUnitTestFunctionRunner ( Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); - if (UnitTest->RunTest == NULL) { UnitTest->Result = UNIT_TEST_SKIPPED; } else { UnitTest->Result = UNIT_TEST_RUNNING; Framework->CurrentTest = UnitTest; - UnitTest->Result = UnitTest->RunTest (Framework, UnitTest->Context); + UnitTest->Result = UnitTest->RunTest ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); Framework->CurrentTest = NULL; // Print out the log messages - This is a partial solution as it @@ -92,7 +92,7 @@ CmockaUnitTestSetupFunctionRunner ( } Framework->CurrentTest = UnitTest; - Result = UnitTest->PreReq (Framework, UnitTest->Context); + Result = UnitTest->PreReq ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); Framework->CurrentTest = NULL; // @@ -114,13 +114,12 @@ CmockaUnitTestTeardownFunctionRunner ( Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); - if (UnitTest->CleanUp == NULL) { return 0; } Framework->CurrentTest = UnitTest; - UnitTest->CleanUp (Framework, UnitTest->Context); + UnitTest->CleanUp ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); Framework->CurrentTest = NULL; // // Return 0 for success. Non-zero for error. @@ -143,7 +142,7 @@ CmockaUnitTestSuiteSetupFunctionRunner ( } Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); - mActiveUnitTestSuite->Setup (Framework); + mActiveUnitTestSuite->Setup ((UNIT_TEST_FRAMEWORK_HANDLE)Framework); // // Always succeed // @@ -165,7 +164,7 @@ CmockaUnitTestSuiteTeardownFunctionRunner ( } Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); - mActiveUnitTestSuite->Teardown (Framework); + mActiveUnitTestSuite->Teardown ((UNIT_TEST_FRAMEWORK_HANDLE)Framework); // // Always succeed // @@ -253,7 +252,7 @@ RunAllTestSuites ( DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); DEBUG((DEBUG_VERBOSE, "------------ RUNNING ALL TEST SUITES --------------\n")); DEBUG((DEBUG_VERBOSE, "---------------------------------------------------------\n")); - mFramework = FrameworkHandle; + mFrameworkHandle = FrameworkHandle; // // Iterate all suites @@ -267,7 +266,7 @@ RunAllTestSuites ( } } - mFramework = NULL; + mFrameworkHandle = NULL; return EFI_SUCCESS; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 2292e637aec..04986df9eb6 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -175,9 +175,10 @@ InitUnitTestFramework ( IN CHAR8 *VersionString ) { - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK *NewFramework; - UNIT_TEST_SAVE_HEADER *SavedState; + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE NewFrameworkHandle; + UNIT_TEST_FRAMEWORK *NewFramework; + UNIT_TEST_SAVE_HEADER *SavedState; Status = EFI_SUCCESS; NewFramework = NULL; @@ -208,6 +209,7 @@ InitUnitTestFramework ( // // Next, set up all the test data. // + NewFrameworkHandle = (UNIT_TEST_FRAMEWORK_HANDLE)NewFramework; NewFramework->Title = AllocateAndCopyString (Title); NewFramework->ShortTitle = AllocateAndCopyString (ShortTitle); NewFramework->VersionString = AllocateAndCopyString (VersionString); @@ -230,9 +232,9 @@ InitUnitTestFramework ( // // If there is a persisted context, load it now. // - if (DoesCacheExist (NewFramework)) { + if (DoesCacheExist (NewFrameworkHandle)) { SavedState = (UNIT_TEST_SAVE_HEADER *)NewFramework->SavedState; - Status = LoadUnitTestCache (NewFramework, &SavedState); + Status = LoadUnitTestCache (NewFrameworkHandle, &SavedState); if (EFI_ERROR (Status)) { // // Don't actually report it as an error, but emit a warning. @@ -247,12 +249,12 @@ InitUnitTestFramework ( // If we're good, then let's copy the framework. // if (!EFI_ERROR (Status)) { - *Framework = NewFramework; + *Framework = NewFrameworkHandle; } else { // // Otherwise, we need to undo this horrible thing that we've done. // - FreeUnitTestFramework ((UNIT_TEST_FRAMEWORK_HANDLE)NewFramework); + FreeUnitTestFramework (NewFrameworkHandle); } return Status; @@ -299,7 +301,7 @@ CreateUnitTestSuite ( NewSuiteEntry->UTS.Package = AllocateAndCopyString (Package); NewSuiteEntry->UTS.Setup = Sup; NewSuiteEntry->UTS.Teardown = Tdn; - NewSuiteEntry->UTS.ParentFramework = Framework; + NewSuiteEntry->UTS.ParentFramework = FrameworkHandle; InitializeListHead (&(NewSuiteEntry->Entry)); // List entry for sibling suites. InitializeListHead (&(NewSuiteEntry->UTS.TestCaseList)); // List entry for child tests. if (NewSuiteEntry->UTS.Title == NULL) { @@ -323,7 +325,7 @@ CreateUnitTestSuite ( // if (!EFI_ERROR( Status )) { InsertTailList (&(Framework->TestSuiteList), (LIST_ENTRY *)NewSuiteEntry); - *Suite = &NewSuiteEntry->UTS; + *Suite = (UNIT_TEST_SUITE_HANDLE)(&NewSuiteEntry->UTS); } else { // // Otherwise, make with the destruction. @@ -381,7 +383,7 @@ AddTestCase ( NewTestEntry->UT.RunTest = Func; NewTestEntry->UT.Context = Context; NewTestEntry->UT.Result = UNIT_TEST_PENDING; - NewTestEntry->UT.ParentSuite = Suite; + NewTestEntry->UT.ParentSuite = SuiteHandle; InitializeListHead (&(NewTestEntry->Entry)); // List entry for sibling tests. if (NewTestEntry->UT.Description == NULL) { Status = EFI_OUT_OF_RESOURCES; diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 2d054245373..62dd65629d3 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -141,9 +141,9 @@ typedef struct VOID EFIAPI UnitTestLogInit ( - IN OUT UNIT_TEST_HANDLE TestHandle, - IN UINT8 *Buffer OPTIONAL, - IN UINTN BufferSize OPTIONAL + IN OUT UNIT_TEST *Test, + IN UINT8 *Buffer OPTIONAL, + IN UINTN BufferSize OPTIONAL ); /** From e7dda6afd96cd2f6c9a72d2b8a36c10f879eadc7 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 17 Jan 2020 16:11:17 -0800 Subject: [PATCH 371/384] MdeModulePkg/DxeResetSystemLib/UnitTest: Add UefiRuntimeServicesLib instance Signed-off-by: Michael D Kinney --- .../UnitTest/DxeResetSystemLibUnitTest.c | 8 +++--- .../DxeResetSystemLibUnitTestHost.inf | 3 --- .../MochUefiRuntimeServicesTableLib.c | 13 ++++++++++ .../MochUefiRuntimeServicesTableLib.inf | 25 +++++++++++++++++++ MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 2 +- 5 files changed, 42 insertions(+), 9 deletions(-) create mode 100644 MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c create mode 100644 MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index 91fa74968e3..a0ba0095e9a 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -1,8 +1,8 @@ /** @file -DxeResetSystemLibUnitTestHost.c + Unit tests of the DxeResetSystemLib instance of the ResetSystemLib class -Copyright (C) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent + Copyright (C) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -90,8 +90,6 @@ EFI_RUNTIME_SERVICES MockRuntime = { NULL, // QueryCapsuleCapabilities NULL // QueryVariableInfo }; -EFI_RUNTIME_SERVICES *gRT = &MockRuntime; - ///================================================================================================ ///================================================================================================ diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf index d902375a8ed..f3014c22682 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf @@ -3,7 +3,6 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## - [Defines] INF_VERSION = 0x00010006 BASE_NAME = DxeResetSystemLibUnitTestHost @@ -20,13 +19,11 @@ [Sources] DxeResetSystemLibUnitTest.c - [Packages] MdePkg/MdePkg.dec MdeModulePkg/MdeModulePkg.dec UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - [LibraryClasses] ResetSystemLib BaseLib diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c new file mode 100644 index 00000000000..bb9f50b616d --- /dev/null +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c @@ -0,0 +1,13 @@ +/** @file + Moch implementation of the UEFI Runtime Services Table Library. + + Copyright (C) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +extern EFI_RUNTIME_SERVICES MockRuntime; + +EFI_RUNTIME_SERVICES *gRT = &MockRuntime; diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf new file mode 100644 index 00000000000..a3773bb453e --- /dev/null +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf @@ -0,0 +1,25 @@ +## @file +# Moch implementation of the UEFI Runtime Services Table Library. +# +# Copyright (c) 2020, Intel Corporation. All rights reserved.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = MochUefiRuntimeServicesTableLib + FILE_GUID = 4EA215EE-85C1-4A0A-847F-D2A8DE20805F + MODULE_TYPE = UEFI_DRIVER + VERSION_STRING = 1.0 + LIBRARY_CLASS = UefiRuntimeServicesTableLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_APPLICATION UEFI_DRIVER SMM_CORE + +# +# VALID_ARCHITECTURES = IA32 X64 EBC +# + +[Sources] + MochUefiRuntimeServicesTableLib.c + +[Packages] + MdePkg/MdePkg.dec diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index f15fc7766e5..3a71af34ada 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -25,5 +25,5 @@ MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf { ResetSystemLib|MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf - UefiRuntimeServicesTableLib|UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf + UefiRuntimeServicesTableLib|MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf } From 9a1a0216debf46c848577fb0a7a92588879f4018 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Fri, 17 Jan 2020 16:11:47 -0800 Subject: [PATCH 372/384] UnitTestFrameworkPkg: Remove MockLibraryClassLibNull Signed-off-by: Michael D Kinney --- .../MockLibraryClassLibNull.c | 9 -------- .../MockLibraryClassLibNull.inf | 23 ------------------- .../Test/UnitTestFrameworkPkgHostTest.dsc | 1 - 3 files changed, 33 deletions(-) delete mode 100644 UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c delete mode 100644 UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf diff --git a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c deleted file mode 100644 index 7213733a43b..00000000000 --- a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.c +++ /dev/null @@ -1,9 +0,0 @@ -/** @file -- MockLibraryClassLibNull.c -Generic library that could be anything. It could be a boat! - -Copyright (c) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -// I'm a comment! diff --git a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf b/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf deleted file mode 100644 index 3e48a912b7b..00000000000 --- a/UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf +++ /dev/null @@ -1,23 +0,0 @@ -## @file -# Generic library that could be anything. It could be a boat! -# -# Copyright (c) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = MockLibraryClassLibNull - FILE_GUID = E653BA0C-1EFA-4061-81B6-A7894BD35BD1 - MODULE_TYPE = BASE - VERSION_STRING = 1.0 - LIBRARY_CLASS = MockLibraryClassLib|HOST_APPLICATION - - -[Sources] - MockLibraryClassLibNull.c - - -[Packages] - MdePkg/MdePkg.dec diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index e7e2da5b262..2bb8ff80120 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -30,4 +30,3 @@ UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf - UnitTestFrameworkPkg/Library/MockLibraryClassLibNull/MockLibraryClassLibNull.inf From 67e9484362785337c5ebe835b3ce28825aeae0be Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 18 Jan 2020 11:08:22 -0800 Subject: [PATCH 373/384] Remove UNIT_TEST_FRAMEWORK_HANDLE parameter Remove the UNIT_TEST_FRAMEWORK_HANDLE from the 5 function prototype for the Suite Setup, Suite Teardown, Unit Test Prerequiisite, Unit Test Function, Unit Test Cleanup. Update UnitTestLib test runners to remove this parameter. Remove parameter from all unit test cases. Signed-off-by: Michael D Kinney --- .../UnitTest/DxeResetSystemLibUnitTest.c | 5 -- MdePkg/Include/Library/UnitTestLib.h | 7 +- .../UnitTest/Library/BaseLib/Base64UnitTest.c | 3 - .../IA32/SafeIntLibUintnIntnUnitTests.c | 17 ---- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 84 ------------------- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 17 ---- .../X64/SafeIntLibUintnIntnUnitTests.c | 17 ---- .../Library/UnitTestLib/RunTests.c | 10 +-- .../Library/UnitTestLib/RunTestsCmocka.c | 10 +-- .../Sample/SampleUnitTest/SampleUnitTest.c | 5 -- 10 files changed, 12 insertions(+), 163 deletions(-) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index a0ba0095e9a..0312f9c6e43 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -102,7 +102,6 @@ EFI_RUNTIME_SERVICES MockRuntime = { UNIT_TEST_STATUS EFIAPI ResetColdShouldIssueAColdReset ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -117,7 +116,6 @@ ResetColdShouldIssueAColdReset ( UNIT_TEST_STATUS EFIAPI ResetWarmShouldIssueAWarmReset ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -132,7 +130,6 @@ ResetWarmShouldIssueAWarmReset ( UNIT_TEST_STATUS EFIAPI ResetShutdownShouldIssueAShutdown ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -147,7 +144,6 @@ ResetShutdownShouldIssueAShutdown ( UNIT_TEST_STATUS EFIAPI ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -162,7 +158,6 @@ ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( UNIT_TEST_STATUS EFIAPI ResetSystemShouldPassTheParametersThrough ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index f52548c9a22..b19388464a0 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -66,7 +66,6 @@ typedef VOID* UNIT_TEST_CONTEXT; typedef UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_FUNCTION)( - UNIT_TEST_FRAMEWORK_HANDLE Framework, UNIT_TEST_CONTEXT Context ); @@ -95,7 +94,6 @@ UNIT_TEST_STATUS typedef UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_PREREQ)( - UNIT_TEST_FRAMEWORK_HANDLE Framework, UNIT_TEST_CONTEXT Context ); @@ -125,7 +123,6 @@ UNIT_TEST_STATUS typedef VOID (EFIAPI *UNIT_TEST_CLEANUP)( - UNIT_TEST_FRAMEWORK_HANDLE Framework, UNIT_TEST_CONTEXT Context ); @@ -145,7 +142,7 @@ VOID typedef VOID (EFIAPI *UNIT_TEST_SUITE_SETUP)( - UNIT_TEST_FRAMEWORK_HANDLE Framework + VOID ); /** @@ -164,7 +161,7 @@ VOID typedef VOID (EFIAPI *UNIT_TEST_SUITE_TEARDOWN)( - UNIT_TEST_FRAMEWORK_HANDLE Framework + VOID ); /// diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c index 1ae52818460..a8fb511a314 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c +++ b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c @@ -119,7 +119,6 @@ STATIC VOID EFIAPI CleanUpB64TestContext ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -148,7 +147,6 @@ static UNIT_TEST_STATUS EFIAPI RfcEncodeTest( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -216,7 +214,6 @@ static UNIT_TEST_STATUS EFIAPI RfcDecodeTest( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c index 045810263ac..a24b66667e4 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -13,7 +13,6 @@ UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -43,7 +42,6 @@ TestSafeInt32ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -73,7 +71,6 @@ TestSafeUint32ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -96,7 +93,6 @@ TestSafeIntnToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -126,7 +122,6 @@ TestSafeIntnToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -149,7 +144,6 @@ TestSafeUintnToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -179,7 +173,6 @@ TestSafeUintnToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -203,7 +196,6 @@ TestSafeUintnToInt64 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -242,7 +234,6 @@ TestSafeInt64ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -276,7 +267,6 @@ TestSafeInt64ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -306,7 +296,6 @@ TestSafeUint64ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -336,7 +325,6 @@ TestSafeUint64ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUintnAdd ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -369,7 +357,6 @@ TestSafeUintnAdd ( UNIT_TEST_STATUS EFIAPI TestSafeIntnAdd ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -414,7 +401,6 @@ TestSafeIntnAdd ( UNIT_TEST_STATUS EFIAPI TestSafeUintnSub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -447,7 +433,6 @@ TestSafeUintnSub ( UNIT_TEST_STATUS EFIAPI TestSafeIntnSub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -492,7 +477,6 @@ TestSafeIntnSub ( UNIT_TEST_STATUS EFIAPI TestSafeUintnMult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -525,7 +509,6 @@ TestSafeUintnMult ( UNIT_TEST_STATUS EFIAPI TestSafeIntnMult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 997e67ea71f..58e16b08079 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -18,7 +18,6 @@ UNIT_TEST_STATUS EFIAPI TestSafeInt8ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -48,7 +47,6 @@ TestSafeInt8ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt8ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -78,7 +76,6 @@ TestSafeInt8ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt8ToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -108,7 +105,6 @@ TestSafeInt8ToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt8ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -138,7 +134,6 @@ TestSafeInt8ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeInt8ToUint64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -168,7 +163,6 @@ TestSafeInt8ToUint64 ( UNIT_TEST_STATUS EFIAPI TestSafeUint8ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -198,7 +192,6 @@ TestSafeUint8ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint8ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -233,7 +226,6 @@ TestSafeUint8ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -272,7 +264,6 @@ TestSafeInt16ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -316,7 +307,6 @@ TestSafeInt16ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -350,7 +340,6 @@ TestSafeInt16ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -378,7 +367,6 @@ TestSafeInt16ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -408,7 +396,6 @@ TestSafeInt16ToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -438,7 +425,6 @@ TestSafeInt16ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeInt16ToUint64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -468,7 +454,6 @@ TestSafeInt16ToUint64 ( UNIT_TEST_STATUS EFIAPI TestSafeUint16ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -498,7 +483,6 @@ TestSafeUint16ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint16ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -531,7 +515,6 @@ TestSafeUint16ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint16ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -561,7 +544,6 @@ TestSafeUint16ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint16ToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -591,7 +573,6 @@ TestSafeUint16ToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -630,7 +611,6 @@ TestSafeInt32ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -672,7 +652,6 @@ TestSafeInt32ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -710,7 +689,6 @@ TestSafeInt32ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -749,7 +727,6 @@ TestSafeInt32ToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -787,7 +764,6 @@ TestSafeInt32ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -817,7 +793,6 @@ TestSafeInt32ToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUint64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -847,7 +822,6 @@ TestSafeInt32ToUint64 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -877,7 +851,6 @@ TestSafeUint32ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -910,7 +883,6 @@ TestSafeUint32ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -940,7 +912,6 @@ TestSafeUint32ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -970,7 +941,6 @@ TestSafeUint32ToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1000,7 +970,6 @@ TestSafeUint32ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1030,7 +999,6 @@ TestSafeUint32ToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1069,7 +1037,6 @@ TestSafeIntnToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1111,7 +1078,6 @@ TestSafeIntnToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1145,7 +1111,6 @@ TestSafeIntnToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1184,7 +1149,6 @@ TestSafeIntnToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1218,7 +1182,6 @@ TestSafeIntnToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1248,7 +1211,6 @@ TestSafeIntnToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1278,7 +1240,6 @@ TestSafeIntnToUint64 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1308,7 +1269,6 @@ TestSafeUintnToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1341,7 +1301,6 @@ TestSafeUintnToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1371,7 +1330,6 @@ TestSafeUintnToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1401,7 +1359,6 @@ TestSafeUintnToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1431,7 +1388,6 @@ TestSafeUintnToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1461,7 +1417,6 @@ TestSafeUintnToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1500,7 +1455,6 @@ TestSafeInt64ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1542,7 +1496,6 @@ TestSafeInt64ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1576,7 +1529,6 @@ TestSafeInt64ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1615,7 +1567,6 @@ TestSafeInt64ToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1649,7 +1600,6 @@ TestSafeInt64ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1688,7 +1638,6 @@ TestSafeInt64ToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1722,7 +1671,6 @@ TestSafeInt64ToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUint64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1752,7 +1700,6 @@ TestSafeInt64ToUint64 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToInt8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1782,7 +1729,6 @@ TestSafeUint64ToInt8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToChar8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1815,7 +1761,6 @@ TestSafeUint64ToChar8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUint8 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1845,7 +1790,6 @@ TestSafeUint64ToUint8 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToInt16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1875,7 +1819,6 @@ TestSafeUint64ToInt16 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUint16 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1905,7 +1848,6 @@ TestSafeUint64ToUint16 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1935,7 +1877,6 @@ TestSafeUint64ToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1965,7 +1906,6 @@ TestSafeUint64ToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToInt64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -1998,7 +1938,6 @@ TestSafeUint64ToInt64 ( UNIT_TEST_STATUS EFIAPI TestSafeUint8Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2031,7 +1970,6 @@ TestSafeUint8Add ( UNIT_TEST_STATUS EFIAPI TestSafeUint16Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2061,7 +1999,6 @@ TestSafeUint16Add ( UNIT_TEST_STATUS EFIAPI TestSafeUint32Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2094,7 +2031,6 @@ TestSafeUint32Add ( UNIT_TEST_STATUS EFIAPI TestSafeUint64Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2127,7 +2063,6 @@ TestSafeUint64Add ( UNIT_TEST_STATUS EFIAPI TestSafeInt8Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2173,7 +2108,6 @@ TestSafeInt8Add ( UNIT_TEST_STATUS EFIAPI TestSafeInt16Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2218,7 +2152,6 @@ TestSafeInt16Add ( UNIT_TEST_STATUS EFIAPI TestSafeInt32Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2263,7 +2196,6 @@ TestSafeInt32Add ( UNIT_TEST_STATUS EFIAPI TestSafeInt64Add ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2311,7 +2243,6 @@ TestSafeInt64Add ( UNIT_TEST_STATUS EFIAPI TestSafeUint8Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2344,7 +2275,6 @@ TestSafeUint8Sub ( UNIT_TEST_STATUS EFIAPI TestSafeUint16Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2377,7 +2307,6 @@ TestSafeUint16Sub ( UNIT_TEST_STATUS EFIAPI TestSafeUint32Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2410,7 +2339,6 @@ TestSafeUint32Sub ( UNIT_TEST_STATUS EFIAPI TestSafeUint64Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2443,7 +2371,6 @@ TestSafeUint64Sub ( UNIT_TEST_STATUS EFIAPI TestSafeInt8Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2488,7 +2415,6 @@ TestSafeInt8Sub ( UNIT_TEST_STATUS EFIAPI TestSafeInt16Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2533,7 +2459,6 @@ TestSafeInt16Sub ( UNIT_TEST_STATUS EFIAPI TestSafeInt32Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2578,7 +2503,6 @@ TestSafeInt32Sub ( UNIT_TEST_STATUS EFIAPI TestSafeInt64Sub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2626,7 +2550,6 @@ TestSafeInt64Sub ( UNIT_TEST_STATUS EFIAPI TestSafeUint8Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2659,7 +2582,6 @@ TestSafeUint8Mult ( UNIT_TEST_STATUS EFIAPI TestSafeUint16Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2692,7 +2614,6 @@ TestSafeUint16Mult ( UNIT_TEST_STATUS EFIAPI TestSafeUint32Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2725,7 +2646,6 @@ TestSafeUint32Mult ( UNIT_TEST_STATUS EFIAPI TestSafeUint64Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2758,7 +2678,6 @@ TestSafeUint64Mult ( UNIT_TEST_STATUS EFIAPI TestSafeInt8Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2792,7 +2711,6 @@ TestSafeInt8Mult ( UNIT_TEST_STATUS EFIAPI TestSafeInt16Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2826,7 +2744,6 @@ TestSafeInt16Mult ( UNIT_TEST_STATUS EFIAPI TestSafeInt32Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -2860,7 +2777,6 @@ TestSafeInt32Mult ( UNIT_TEST_STATUS EFIAPI TestSafeInt64Mult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index d97fa5aec86..af67d409de0 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -21,119 +21,102 @@ UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUintn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUint32ToIntn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeIntnToInt32( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint32( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnToUint32( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnToIntn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt64( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeInt64ToIntn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUintn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUint64ToIntn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUintn( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnAdd( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeIntnAdd( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnSub( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeIntnSub( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeUintnMult( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); UNIT_TEST_STATUS EFIAPI TestSafeIntnMult( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ); diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c index d5a3beb1c3a..01fcf1096d2 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -13,7 +13,6 @@ UNIT_TEST_STATUS EFIAPI TestSafeInt32ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -43,7 +42,6 @@ TestSafeInt32ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUint32ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -71,7 +69,6 @@ TestSafeUint32ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToInt32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -110,7 +107,6 @@ TestSafeIntnToInt32 ( UNIT_TEST_STATUS EFIAPI TestSafeIntnToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -144,7 +140,6 @@ TestSafeIntnToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToUint32 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -174,7 +169,6 @@ TestSafeUintnToUint32 ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -204,7 +198,6 @@ TestSafeUintnToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeUintnToInt64 ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -234,7 +227,6 @@ TestSafeUintnToInt64 ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -257,7 +249,6 @@ TestSafeInt64ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeInt64ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -287,7 +278,6 @@ TestSafeInt64ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToIntn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -317,7 +307,6 @@ TestSafeUint64ToIntn ( UNIT_TEST_STATUS EFIAPI TestSafeUint64ToUintn ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -340,7 +329,6 @@ TestSafeUint64ToUintn ( UNIT_TEST_STATUS EFIAPI TestSafeUintnAdd ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -373,7 +361,6 @@ TestSafeUintnAdd ( UNIT_TEST_STATUS EFIAPI TestSafeIntnAdd ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -418,7 +405,6 @@ TestSafeIntnAdd ( UNIT_TEST_STATUS EFIAPI TestSafeUintnSub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -451,7 +437,6 @@ TestSafeUintnSub ( UNIT_TEST_STATUS EFIAPI TestSafeIntnSub ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -496,7 +481,6 @@ TestSafeIntnSub ( UNIT_TEST_STATUS EFIAPI TestSafeUintnMult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -529,7 +513,6 @@ TestSafeUintnMult ( UNIT_TEST_STATUS EFIAPI TestSafeIntnMult ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c index afc25cf6652..8340e18f15d 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -47,7 +47,7 @@ RunTestSuite ( DEBUG ((DEBUG_VERBOSE, "---------------------------------------------------------\n")); if (Suite->Setup != NULL) { - Suite->Setup (Suite->ParentFramework); + Suite->Setup (); } // @@ -77,7 +77,7 @@ RunTestSuite ( // Next, if we're still running, make sure that our test prerequisites are in place. if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) { DEBUG ((DEBUG_VERBOSE, "PREREQ\n")); - if (Test->PreReq (Suite->ParentFramework, Test->Context) != UNIT_TEST_PASSED) { + if (Test->PreReq (Test->Context) != UNIT_TEST_PASSED) { DEBUG ((DEBUG_ERROR, "PreReq Not Met\n")); Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; ParentFramework->CurrentTest = NULL; @@ -91,13 +91,13 @@ RunTestSuite ( // or quit. The UNIT_TEST_RUNNING state will allow the test to resume // but will prevent the PreReq from being dispatched a second time. Test->Result = UNIT_TEST_RUNNING; - Test->Result = Test->RunTest (Suite->ParentFramework, Test->Context); + Test->Result = Test->RunTest (Test->Context); // // Finally, clean everything up, if need be. if (Test->CleanUp != NULL) { DEBUG (( DEBUG_VERBOSE, "CLEANUP\n")); - Test->CleanUp (Suite->ParentFramework, Test->Context); + Test->CleanUp (Test->Context); } // @@ -107,7 +107,7 @@ RunTestSuite ( } if (Suite->Teardown != NULL) { - Suite->Teardown( Suite->ParentFramework ); + Suite->Teardown (); } return EFI_SUCCESS; diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index f1b5a7d5ac2..9b58a83a493 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -57,7 +57,7 @@ CmockaUnitTestFunctionRunner ( UnitTest->Result = UNIT_TEST_RUNNING; Framework->CurrentTest = UnitTest; - UnitTest->Result = UnitTest->RunTest ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); + UnitTest->Result = UnitTest->RunTest (UnitTest->Context); Framework->CurrentTest = NULL; // Print out the log messages - This is a partial solution as it @@ -92,7 +92,7 @@ CmockaUnitTestSetupFunctionRunner ( } Framework->CurrentTest = UnitTest; - Result = UnitTest->PreReq ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); + Result = UnitTest->PreReq (UnitTest->Context); Framework->CurrentTest = NULL; // @@ -119,7 +119,7 @@ CmockaUnitTestTeardownFunctionRunner ( } Framework->CurrentTest = UnitTest; - UnitTest->CleanUp ((UNIT_TEST_FRAMEWORK_HANDLE)Framework, UnitTest->Context); + UnitTest->CleanUp (UnitTest->Context); Framework->CurrentTest = NULL; // // Return 0 for success. Non-zero for error. @@ -142,7 +142,7 @@ CmockaUnitTestSuiteSetupFunctionRunner ( } Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); - mActiveUnitTestSuite->Setup ((UNIT_TEST_FRAMEWORK_HANDLE)Framework); + mActiveUnitTestSuite->Setup (); // // Always succeed // @@ -164,7 +164,7 @@ CmockaUnitTestSuiteTeardownFunctionRunner ( } Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); - mActiveUnitTestSuite->Teardown ((UNIT_TEST_FRAMEWORK_HANDLE)Framework); + mActiveUnitTestSuite->Teardown (); // // Always succeed // diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 6d2ccdec686..2c629b6666c 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -37,7 +37,6 @@ VOID *mSampleGlobalTestPointer = NULL; UNIT_TEST_STATUS EFIAPI MakeSureThatPointerIsNull ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -49,7 +48,6 @@ MakeSureThatPointerIsNull ( VOID EFIAPI ClearThePointer ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -69,7 +67,6 @@ ClearThePointer ( UNIT_TEST_STATUS EFIAPI OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -88,7 +85,6 @@ OnePlusOneShouldEqualTwo ( UNIT_TEST_STATUS EFIAPI GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { @@ -105,7 +101,6 @@ GlobalBooleanShouldBeChangeable ( UNIT_TEST_STATUS EFIAPI GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, IN UNIT_TEST_CONTEXT Context ) { From 6e1ebc6d14d8f773a3c571f50e4c60ff2c9c225c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 18 Jan 2020 11:14:01 -0800 Subject: [PATCH 374/384] Fix misspelling Signed-off-by: Michael D Kinney --- .../UnitTest/MochUefiRuntimeServicesTableLib.c | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c index bb9f50b616d..3b36da15e11 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c @@ -1,5 +1,5 @@ /** @file - Moch implementation of the UEFI Runtime Services Table Library. + Mock implementation of the UEFI Runtime Services Table Library. Copyright (C) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent From c458e7e73381c4cbc5a3d20990905d9bed78a991 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Sat, 18 Jan 2020 11:28:20 -0800 Subject: [PATCH 375/384] Complete fix of misplelled word 'Moch' to 'Mock' Signed-off-by: Michael D Kinney --- ...rvicesTableLib.c => MockUefiRuntimeServicesTableLib.c} | 4 ++-- ...esTableLib.inf => MockUefiRuntimeServicesTableLib.inf} | 8 ++++---- MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) rename MdeModulePkg/Library/DxeResetSystemLib/UnitTest/{MochUefiRuntimeServicesTableLib.c => MockUefiRuntimeServicesTableLib.c} (67%) rename MdeModulePkg/Library/DxeResetSystemLib/UnitTest/{MochUefiRuntimeServicesTableLib.inf => MockUefiRuntimeServicesTableLib.inf} (56%) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c similarity index 67% rename from MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c rename to MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c index 3b36da15e11..59ea6a8b49b 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c @@ -8,6 +8,6 @@ #include -extern EFI_RUNTIME_SERVICES MockRuntime; +extern EFI_RUNTIME_SERVICES MockRuntime; -EFI_RUNTIME_SERVICES *gRT = &MockRuntime; +EFI_RUNTIME_SERVICES *gRT = &MockRuntime; diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf similarity index 56% rename from MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf rename to MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf index a3773bb453e..e716b855a31 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf @@ -1,5 +1,5 @@ ## @file -# Moch implementation of the UEFI Runtime Services Table Library. +# Mock implementation of the UEFI Runtime Services Table Library. # # Copyright (c) 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -8,18 +8,18 @@ [Defines] INF_VERSION = 0x00010005 - BASE_NAME = MochUefiRuntimeServicesTableLib + BASE_NAME = MockUefiRuntimeServicesTableLib FILE_GUID = 4EA215EE-85C1-4A0A-847F-D2A8DE20805F MODULE_TYPE = UEFI_DRIVER VERSION_STRING = 1.0 - LIBRARY_CLASS = UefiRuntimeServicesTableLib|DXE_CORE DXE_DRIVER DXE_RUNTIME_DRIVER DXE_SMM_DRIVER UEFI_APPLICATION UEFI_DRIVER SMM_CORE + LIBRARY_CLASS = UefiRuntimeServicesTableLib|HOST_APPLICATION # # VALID_ARCHITECTURES = IA32 X64 EBC # [Sources] - MochUefiRuntimeServicesTableLib.c + MockUefiRuntimeServicesTableLib.c [Packages] MdePkg/MdePkg.dec diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index 3a71af34ada..eaedb1a431e 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -25,5 +25,5 @@ MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf { ResetSystemLib|MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf - UefiRuntimeServicesTableLib|MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MochUefiRuntimeServicesTableLib.inf + UefiRuntimeServicesTableLib|MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf } From 966e3a5f9910504b6c2b797441ac23b903d7e852 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 21 Jan 2020 10:58:47 -0800 Subject: [PATCH 376/384] Add Mock library to the HostApplication DSC. --- MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 2 ++ 1 file changed, 2 insertions(+) diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index eaedb1a431e..4fbb21201c0 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -19,6 +19,8 @@ !include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc [Components] + MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf + # # Build MdeModulePkg HOST_APPLICATION Tests # From 24c158d45ca557b3d2c72101ddbce9e11d194115 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 21 Jan 2020 10:59:15 -0800 Subject: [PATCH 377/384] Fix a spelling error. --- UnitTestFrameworkPkg/ReadMe.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 74f286059e8..32730df7718 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -55,7 +55,7 @@ Most of these examples will refer to the SampleUnitTestUefiShell app found in th In our INF file, we'll need to bring in the `UnitTestLib` library. Conveniently, the interface header for the `UnitTestLib` is located in `MdePkg`, so you shouldn't need to depend on any other -packages. As long as your DSC file knows where to find the lib implmentation that you want to use, +packages. As long as your DSC file knows where to find the lib implementation that you want to use, you should be good to go. See this example in 'SampleUnitTestApp.inf'... From 598c0feec23cfac31d809d0583b6ac9b3ad17689 Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Tue, 21 Jan 2020 14:44:22 -0800 Subject: [PATCH 378/384] Update BaseSafeIntLib test cases to reflect the correct implementations of SafeIntToChar8(). --- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 86 +++++++++++++++---- 1 file changed, 68 insertions(+), 18 deletions(-) diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 58e16b08079..3c4e19d52e9 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -272,12 +272,12 @@ TestSafeInt16ToChar8 ( CHAR8 Result; // - // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. // // - // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast // Operand = 0x5b; Result = 0; @@ -285,14 +285,25 @@ TestSafeInt16ToChar8 ( UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); - Operand = (-35); + Operand = 0; + Result = 0; Status = SafeInt16ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); - UT_ASSERT_EQUAL((-35), Result); + UT_ASSERT_EQUAL(0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(MAX_INT8, Result); // // Otherwise should result in an error status // + Operand = (-35); + Status = SafeInt16ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + Operand = 0x1234; Status = SafeInt16ToChar8(Operand, &Result); UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); @@ -618,11 +629,13 @@ TestSafeInt32ToChar8 ( INT32 Operand; CHAR8 Result; - // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // // - // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast + // If Operand is between 0 and MAX_INT8 inclusive, then it's a cast // Operand = 0x5b; Result = 0; @@ -630,14 +643,25 @@ TestSafeInt32ToChar8 ( UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); - Operand = (-57); + Operand = 0; + Result = 0; Status = SafeInt32ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); - UT_ASSERT_EQUAL((-57), Result); + UT_ASSERT_EQUAL(0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(MAX_INT8, Result); // // Otherwise should result in an error status // + Operand = (-57); + Status = SafeInt32ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + Operand = (0x5bababab); Status = SafeInt32ToChar8(Operand, &Result); UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); @@ -1044,8 +1068,10 @@ TestSafeIntnToChar8 ( INTN Operand; CHAR8 Result; - // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast @@ -1056,14 +1082,25 @@ TestSafeIntnToChar8 ( UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); - Operand = (-53); + Operand = 0; + Result = 0; Status = SafeIntnToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); - UT_ASSERT_EQUAL((-53), Result); + UT_ASSERT_EQUAL(0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(MAX_INT8, Result); // // Otherwise should result in an error status // + Operand = (-53); + Status = SafeIntnToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + Operand = (0x5bababab); Status = SafeIntnToChar8(Operand, &Result); UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); @@ -1462,8 +1499,10 @@ TestSafeInt64ToChar8 ( INT64 Operand; CHAR8 Result; - // CHAR8 is typedefed as char, which by default is signed, thus - // CHAR8 is same as INT8, so same tests as above: + // + // CHAR8 is typedefed as char, which may be signed or unsigned based + // on the compiler. Thus, for compatibility CHAR8 should be between 0 and MAX_INT8. + // // // If Operand is between MIN_INT8 and MAX_INT8 inclusive, then it's a cast @@ -1474,14 +1513,25 @@ TestSafeInt64ToChar8 ( UT_ASSERT_NOT_EFI_ERROR(Status); UT_ASSERT_EQUAL(0x5b, Result); - Operand = (-37); + Operand = 0; + Result = 0; Status = SafeInt64ToChar8(Operand, &Result); UT_ASSERT_NOT_EFI_ERROR(Status); - UT_ASSERT_EQUAL((-37), Result); + UT_ASSERT_EQUAL(0, Result); + + Operand = MAX_INT8; + Result = 0; + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_NOT_EFI_ERROR(Status); + UT_ASSERT_EQUAL(MAX_INT8, Result); // // Otherwise should result in an error status // + Operand = (-37); + Status = SafeInt64ToChar8(Operand, &Result); + UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); + Operand = (0x5babababefefefef); Status = SafeInt64ToChar8(Operand, &Result); UT_ASSERT_EQUAL(RETURN_BUFFER_TOO_SMALL, Status); From f7449d69e6b7b6efc9a6e60193e9755e9e368b55 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 21 Jan 2020 15:04:30 -0800 Subject: [PATCH 379/384] UnitTestFrameworkPkg: General cleanups * Change DEC PACKAGE_NAME from UnitTestPkg to UnitTestFrameworkPkg. * CHange token space guid name from UnitTestPkgTokenSpaceGuid to UnitTestFrameworkPkgTokenSpaceGuid * Add detailed description of PcdUnitTestLogLevel * Add package UNI file with description of package and PcdUnitTestLogLevel. * Remove use of defines from DebugLib and add unit test specific defines for logging levels. * Change "PREREQ" and "PreReq" to "PREREQUISITE" and "Prerequisite" * Change param/field "ClassName" to "Name" * Change param/field "Package" to "Name" * Change param/field "Func" to "Function" * Complete UnitTestLib.h class function/macro descriptions * Update function headers for UnitTestLib instance to match class. * CreateUnitTestSuite() - Check if SuiteHandle is NULL * AddTestCase() - Check if Function is NULL. * AddTestCase() - Check of NewTestEntry->UT.Name is NULL. * UintTestLog() - Remove LogLevel local variable. * UnitTestAssertMemEqual() - Change ValueA and ValueB to BufferA and BufferB and make them VOID* instead of UINTN. Update macro to use (VOID *)(UINTN) typecase for max compat with possible input params. * UnitTestLib/Assert.c - Use UT_LOG_ERROR() instead of UnitTestLog() Signed-off-by: Michael D Kinney --- MdePkg/Include/Library/UnitTestLib.h | 748 ++++++++++-------- .../Library/UnitTestLib/Assert.c | 192 ++++- .../Library/UnitTestLib/AssertCmocka.c | 261 ++++-- .../Library/UnitTestLib/Log.c | 29 +- .../Library/UnitTestLib/RunTests.c | 26 +- .../Library/UnitTestLib/RunTestsCmocka.c | 20 +- .../Library/UnitTestLib/UnitTestLib.c | 178 ++++- .../Library/UnitTestLib/UnitTestLib.inf | 2 +- .../Library/UnitTestLib/UnitTestLibCmocka.inf | 2 +- .../UnitTestResultReportLib.c | 18 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 6 +- UnitTestFrameworkPkg/ReadMe.md | 4 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec | 22 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.uni | 21 + 14 files changed, 1072 insertions(+), 457 deletions(-) create mode 100644 UnitTestFrameworkPkg/UnitTestFrameworkPkg.uni diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index b19388464a0..42b63b90719 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -3,25 +3,35 @@ and the framework to focus on runnings, reporting, statistics, etc. Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #ifndef __UNIT_TEST_LIB_H__ #define __UNIT_TEST_LIB_H__ +/// +/// Unit Test Status +/// typedef UINT32 UNIT_TEST_STATUS; -#define UNIT_TEST_PASSED (0) -#define UNIT_TEST_ERROR_PREREQ_NOT_MET (1) -#define UNIT_TEST_ERROR_TEST_FAILED (2) -#define UNIT_TEST_ERROR_CLEANUP_FAILED (3) -#define UNIT_TEST_SKIPPED (0xFFFFFFFD) -#define UNIT_TEST_RUNNING (0xFFFFFFFE) -#define UNIT_TEST_PENDING (0xFFFFFFFF) +#define UNIT_TEST_PASSED (0) +#define UNIT_TEST_ERROR_PREREQUISITE_NOT_MET (1) +#define UNIT_TEST_ERROR_TEST_FAILED (2) +#define UNIT_TEST_ERROR_CLEANUP_FAILED (3) +#define UNIT_TEST_SKIPPED (0xFFFFFFFD) +#define UNIT_TEST_RUNNING (0xFFFFFFFE) +#define UNIT_TEST_PENDING (0xFFFFFFFF) + +/// +/// Declare PcdUnitTestLogLevel bits and UnitTestLog() ErrorLevel parameter. +/// +#define UNIT_TEST_LOG_LEVEL_ERROR BIT0 +#define UNIT_TEST_LOG_LEVEL_WARN BIT1 +#define UNIT_TEST_LOG_LEVEL_INFO BIT2 +#define UNIT_TEST_LOG_LEVEL_VERBOSE BIT3 /// -/// Unit Test Framwework Handle +/// Unit Test Framework Handle /// struct UNIT_TEST_FRAMEWORK_OBJECT; typedef struct UNIT_TEST_FRAMEWORK_OBJECT *UNIT_TEST_FRAMEWORK_HANDLE; @@ -45,12 +55,10 @@ typedef VOID* UNIT_TEST_CONTEXT; /** The prototype for a single UnitTest case function. + Funtions with this prototype are registered to be dispatched by the UnitTest framework, and results are recorded as test Pass or Fail. - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. @param[in] Context [Optional] An optional paramter that enables: 1) test-case reuse with varied parameters and 2) test-case re-entry for Target tests that need a @@ -59,26 +67,24 @@ typedef VOID* UNIT_TEST_CONTEXT; contents are well understood by all test cases that may consume it. - @retval UNIT_TEST_PASSED Test has completed and test case was successful. - @retval UNIT_TEST_ERROR_TEST_FAILED A test assertion has failed. + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. **/ typedef UNIT_TEST_STATUS (EFIAPI *UNIT_TEST_FUNCTION)( - UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ); /** Unit-Test Prerequisite Function pointer type. - NOTE: Should be the same as UnitTest. - Funtions with this prototype are registered to be dispatched by the - UnitTest framework prior to a given test case. If this prereq function returns - UNIT_TEST_ERROR_PREREQ_NOT_MET, the test case will be skipped. - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. + Funtions with this prototype are registered to be dispatched by the unit test + framework prior to a given test case. If this prereq function returns + UNIT_TEST_ERROR_PREREQUISITE_NOT_MET, the test case will be skipped. + @param[in] Context [Optional] An optional paramter that enables: 1) test-case reuse with varied parameters and 2) test-case re-entry for Target tests that need a @@ -87,27 +93,26 @@ UNIT_TEST_STATUS contents are well understood by all test cases that may consume it. - @retval UNIT_TEST_PASSED Test case prerequisites are met. - @retval UNIT_TEST_ERROR_PREREQ_NOT_MET Test case should be skipped. + @retval UNIT_TEST_PASSED Unit test case prerequisites + are met. + @retval UNIT_TEST_ERROR_PREREQUISITE_NOT_MET Test case should be skipped. **/ typedef UNIT_TEST_STATUS -(EFIAPI *UNIT_TEST_PREREQ)( - UNIT_TEST_CONTEXT Context +(EFIAPI *UNIT_TEST_PREREQUISITE)( + IN UNIT_TEST_CONTEXT Context ); /** - Unit-Test Test Cleanup (after) function pointer type. - Funtions with this prototype are registered to be dispatched by the - UnitTest framework after a given test case. This will be called even if the Test - Case returns an error, but not if the prerequisite fails and the test is skipped. + Unit-Test Cleanup (after) function pointer type. - The purpose of this function is to clean up any global state or test data. + Funtions with this prototype are registered to be dispatched by the + unit test framework after a given test case. This will be called even if the + test case returns an error, but not if the prerequisite fails and the test is + skipped. The purpose of this function is to clean up any global state or + test data. - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. @param[in] Context [Optional] An optional paramter that enables: 1) test-case reuse with varied parameters and 2) test-case re-entry for Target tests that need a @@ -123,21 +128,16 @@ UNIT_TEST_STATUS typedef VOID (EFIAPI *UNIT_TEST_CLEANUP)( - UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ); /** - Unit-Test Test Suite Setup (before) function pointer type. - Funtions with this prototype are registered to be dispatched by the - UnitTest framework prior to running any of the test cases in a test suite. - It will only be run once at the beginning of the suite (not prior to each case). + Unit-Test Test Suite Setup (before) function pointer type. Funtions with this + prototype are registered to be dispatched by the UnitTest framework prior to + running any of the test cases in a test suite. It will only be run once at + the beginning of the suite (not prior to each case). The purpose of this function is to set up any global state or test data. - - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. - **/ typedef VOID @@ -146,17 +146,12 @@ VOID ); /** - Unit-Test Test Suite Teardown (after) function pointer type. - Funtions with this prototype are registered to be dispatched by the - UnitTest framework after= running all of the test cases in a test suite. - It will only be run once at the end of the suite. + Unit-Test Test Suite Teardown (after) function pointer type. Funtions with + this prototype are registered to be dispatched by the UnitTest framework after + running all of the test cases in a test suite. It will only be run once at + the end of the suite. The purpose of this function is to clean up any global state or test data. - - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. - **/ typedef VOID @@ -164,107 +159,130 @@ VOID VOID ); -/// -/// Unit-Test Library Functions -/// - /** - Method to Initialize the Unit Test framework. - This function registers the test name and also initializes the internal - state of the test framework to receive any new suites and tests. - - @param[out] Framework Unit test framework to be created. - @param[in] Title String name of the framework. String is copied. - @param[in] ShortTitle Short string name of the framework. String is copied. - @param[in] VersionString Version string for the framework. String is copied. - - @retval EFI_SUCCESS The unit test framework was initialized. - @retval Other The unit test framework could not be initialized. - + Method to Initialize the Unit Test framework. This function registers the + test name and also initializes the internal state of the test framework to + receive any new suites and tests. + + @param[out] FrameworkHandle Unit test framework to be created. + @param[in] Title Null-terminated ASCII string that is the user + friendly name of the framework. String is + copied. + @param[in] ShortTitle Null-terminaled ASCII short string that is the + short name of the framework with no spaces. + String is copied. + @param[in] VersionString Null-terminaled ASCII version string for the + framework. String is copied. + + @retval EFI_SUCCESS The unit test framework was initialized. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER Title is NULL. + @retval EFI_INVALID_PARAMETER ShortTitle is NULL. + @retval EFI_INVALID_PARAMETER VersionString is NULL. + @retval EFI_INVALID_PARAMETER ShortTitle is invalid. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test framework. **/ EFI_STATUS EFIAPI InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + OUT UNIT_TEST_FRAMEWORK_HANDLE *FrameworkHandle, IN CHAR8 *Title, IN CHAR8 *ShortTitle, IN CHAR8 *VersionString ); /** - Registers a Unit Test Suite in the Unit Test Framework + Registers a Unit Test Suite in the Unit Test Framework. At least one test suite must be registered, because all test cases must be within a unit test suite. - @param[out] Suite Suite to create - @param[in] Framework Framework to add suite to - @param[in] Title String name of the suite. String is copied. - @param[in] Package String name of the package. String is copied. - @param[in] Sup Setup function, runs before suite. - @param[in] Tdn Teardown function, runs after suite. - - @retval EFI_SUCCESS The unit test suite was created. - @retval Other The unit test suite could not be created. - + @param[out] SuiteHandle Unit test suite to create + @param[in] FrameworkHandle Unit test framework to add unit test suite to + @param[in] Title Null-terminated ASCII string that is the user + friendly name of the test suite. String is + copied. + @param[in] Name Null-terminated ASCII string that is the short + name of the test suite with no spaces. String + is copied. + @param[in] Setup Setup function, runs before suite. This is an + optional parameter that may be NULL. + @param[in] Teardown Teardown function, runs after suite. This is an + optional parameter that may be NULL. + + @retval EFI_SUCCESS The unit test suite was created. + @retval EFI_INVALID_PARAMETER SuiteHandle is NULL. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER Title is NULL. + @retval EFI_INVALID_PARAMETER Name is NULL. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test suite. **/ EFI_STATUS EFIAPI CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + OUT UNIT_TEST_SUITE_HANDLE *SuiteHandle, + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup OPTIONAL, - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + IN CHAR8 *Name, + IN UNIT_TEST_SUITE_SETUP Setup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Teardown OPTIONAL ); /** Adds test case to Suite - @param[in] Suite Suite to add test to. - @param[in] Description String describing test. String is copied. - @param[in] ClassName String name of the test. String is copied. - @param[in] Func Test function. - @param[in] PreReq Prep function, runs before test. - @param[in] CleanUp Clean up function, runs after test. - @param[in] Context Pointer to context. - - @retval EFI_SUCCESS The unit test case was added to Suite. - @retval EFI_OUT_OF_RESOURCES There are not enough resources available to add - the unit test case to Suite. - + @param[in] SuiteHandle Unit test suite to add test to. + @param[in] Description Null-terminated ASCII string that is the user + friendly description of a test. String is copied. + @param[in] Name Null-terminated ASCII string that is the short name + of the test with no spaces. String is copied. + @param[in] Function Unit test function. + @param[in] Prerequisite Prerequisite function, runs before test. This is + an optional parameter that may be NULL. + @param[in] CleanUp Clean up function, runs after test. This is an + optional parameter that may be NULL. + @param[in] Context Pointer to context. This is an optional parameter + that may be NULL. + + @retval EFI_SUCCESS The unit test case was added to Suite. + @retval EFI_INVALID_PARAMETER SuiteHandle is NULL. + @retval EFI_INVALID_PARAMETER Description is NULL. + @retval EFI_INVALID_PARAMETER Name is NULL. + @retval EFI_INVALID_PARAMETER Function is NULL. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + add the unit test case to Suite. **/ EFI_STATUS EFIAPI AddTestCase ( - IN UNIT_TEST_SUITE_HANDLE Suite, + IN UNIT_TEST_SUITE_HANDLE SuiteHandle, IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq OPTIONAL, - IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, - IN UNIT_TEST_CONTEXT Context OPTIONAL + IN CHAR8 *Name, + IN UNIT_TEST_FUNCTION Function, + IN UNIT_TEST_PREREQUISITE Prerequisite OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, + IN UNIT_TEST_CONTEXT Context OPTIONAL ); /** - The primary driver of UnitTest execution. + Execute all unit test cases in all unit test suites added to a Framework. - Once a test framework is initialized and all suites and test cases are registered, - this function will cause the test framework to dispatch all test cases in sequence - and record the results for reporting. + Once a unit test framework is initialized and all unit test suites and unit + test cases are registered, this function will cause the unit test framework to + dispatch all unit test cases in sequence and record the results for reporting. - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. - - @retval Success - @retval EFI_ERROR() + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. **/ EFI_STATUS EFIAPI RunAllTestSuites ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle ); /** @@ -273,364 +291,466 @@ RunAllTestSuites ( After tests are run, this will teardown the entire framework and free all allocated data within. - @param[in] Framework A handle to the current running framework that - dispatched the test. Necessary for recording certain - test events with the framework. - - @retval Success - @retval EFI_ERROR() + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + @retval EFI_SUCCESS All resources associated with framework were + freed. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. **/ EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle ); /** - Leverages a framework-specific mechanism (see UnitTestPersistenceLib if you're a framework author) - to save the state of the executing framework along with any allocated data so that the test - may be resumed upon reentry. A test case should pass any needed context (which, to prevent an infinite - loop, should be at least the current execution count) which will be saved by the framework and + Leverages a framework-specific mechanism (see UnitTestPersistenceLib if you're + a framework author) to save the state of the executing framework along with + any allocated data so that the test may be resumed upon reentry. A test case + should pass any needed context (which, to prevent an infinite loop, should be + at least the current execution count) which will be saved by the framework and passed to the test case upon resume. Generally called from within a test case prior to quitting or rebooting. - @param[in] Framework - @param[in] ContextToSave A buffer of test case-specific data to be saved along with framework - state. Will be passed as "Context" to the test case upon resume. + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + @param[in] ContextToSave A buffer of test case-specific data to be saved + along with framework state. Will be passed as + "Context" to the test case upon resume. This + is an optional parameter that may be NULL. @param[in] ContextToSaveSize Size of the ContextToSave buffer. - @retval Success - @retval EFI_ERROR() - + @retval EFI_SUCCESS The framework state and context were saved. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER ContextToSave is not NULL and + ContextToSaveSize is 0. + @retval EFI_INVALID_PARAMETER ContextToSave is >= 4GB. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + save the framework and context state. + @retval EFI_DEVICE_ERROR The framework and context state could not be + saved to a persistent storage devide due to a + device error. **/ EFI_STATUS EFIAPI SaveFrameworkState ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework, + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, IN UINTN ContextToSaveSize ); -/// -/// Unit-Test Assertion Macros and Functions -/// /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check an expression for "TRUE". If the - expression evaluates to TRUE, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param Expression Expression to be evaluated for TRUE. + This macro uses the framework assertion logic to check an expression for + "TRUE". If the expression evaluates to TRUE, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] Expression Expression to be evaluated for TRUE. **/ -#define UT_ASSERT_TRUE(Expression) \ +#define UT_ASSERT_TRUE(Expression) \ if(!UnitTestAssertTrue ((Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check an expression for "FALSE". If the - expression evaluates to FALSE, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param Expression Expression to be evaluated for FALSE. + This macro uses the framework assertion logic to check an expression for + "FALSE". If the expression evaluates to FALSE, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] Expression Expression to be evaluated for FALSE. **/ -#define UT_ASSERT_FALSE(Expression) \ +#define UT_ASSERT_FALSE(Expression) \ if(!UnitTestAssertFalse ((Expression), __FUNCTION__, __LINE__, __FILE__, #Expression)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether two simple values are equal. - If the values are equal, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param ValueA, ValueB Values to be compared for equality. Will be compared as UINT64. + This macro uses the framework assertion logic to check whether two simple + values are equal. If the values are equal, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] ValueA Value to be compared for equality (64-bit comparison). + @param[in] ValueB Value to be compared for equality (64-bit comparison). **/ -#define UT_ASSERT_EQUAL(ValueA, ValueB) \ +#define UT_ASSERT_EQUAL(ValueA, ValueB) \ if(!UnitTestAssertEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether two memory buffers are equal. - If the buffers are equal, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param ValueA, ValueB Pointers to the buffers for comparison. - @param Length Number of bytes to compare. + This macro uses the framework assertion logic to check whether two memory + buffers are equal. If the buffers are equal, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] BufferA Pointer to a buffer for comparison. + @param[in] BufferB Pointer to a buffer for comparison. + @param[in] Length Number of bytes to compare in BufferA and BufferB. **/ -#define UT_ASSERT_MEM_EQUAL(ValueA, ValueB, Length) \ - if(!UnitTestAssertMemEqual ((UINTN)ValueA, (UINTN)ValueB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ +#define UT_ASSERT_MEM_EQUAL(BufferA, BufferB, Length) \ + if(!UnitTestAssertMemEqual ((VOID *)(UINTN)BufferA, (VOID *)(UINTN)BufferB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #BufferA, #BufferB)) { \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether two simple values are non-equal. - If the values are non-equal, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param ValueA, ValueB Values to be compared for inequality. Will be compared as UINT64. + This macro uses the framework assertion logic to check whether two simple + values are non-equal. If the values are non-equal, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] ValueA Value to be compared for inequality (64-bit comparison). + @param[in] ValueB Value to be compared for inequality (64-bit comparison). **/ -#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ +#define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ if(!UnitTestAssertNotEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether an EFI_STATUS value is !EFI_ERROR(). - If the status is !EFI_ERROR(), execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param Status Status to be checked. + This macro uses the framework assertion logic to check whether an EFI_STATUS + value is !EFI_ERROR(). If the status is !EFI_ERROR(), execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] Status EFI_STATUS value to check. **/ -#define UT_ASSERT_NOT_EFI_ERROR(Status) \ +#define UT_ASSERT_NOT_EFI_ERROR(Status) \ if(!UnitTestAssertNotEfiError (Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether two EFI_STATUS values are equal. - If the values are equal, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param Status, Expected Values to be compared for equality. + This macro uses the framework assertion logic to check whether two EFI_STATUS + values are equal. If the values are equal, execution continues. + Otherwise, the test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] Status EFI_STATUS values to compare for equality. + @param[in] Expected EFI_STATUS values to compare for equality. **/ -#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ +#define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ if(!UnitTestAssertStatusEqual (Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Test assertion macro that checks an expression against the framework assertion logic. - - This macro uses the framework assertion logic to check whether a pointer is not NULL. - If the pointer is not NULL, execution will continue. Otherwise, the test case - will immediately return UNIT_TEST_ERROR_TEST_FAILED. - - @param Pointer Pointer to be checked. + This macro uses the framework assertion logic to check whether a pointer is + not NULL. If the pointer is not NULL, execution continues. Otherwise, the + test case immediately returns UNIT_TEST_ERROR_TEST_FAILED. + @param[in] Pointer Pointer to be checked against NULL. **/ -#define UT_ASSERT_NOT_NULL(Pointer) \ +#define UT_ASSERT_NOT_NULL(Pointer) \ if(!UnitTestAssertNotNull (Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ - return UNIT_TEST_ERROR_TEST_FAILED; \ + return UNIT_TEST_ERROR_TEST_FAILED; \ } /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If Expression is TRUE, then TRUE is returned. + If Expression is FALSE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + @retval TRUE Expression is TRUE. + @retval FALSE Expression is FALSE. **/ BOOLEAN EFIAPI UnitTestAssertTrue ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If Expression is FALSE, then TRUE is returned. + If Expression is TRUE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + + @retval TRUE Expression is FALSE. + @retval FALSE Expression is TRUE. **/ BOOLEAN EFIAPI UnitTestAssertFalse ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If Status is not an EFI_ERROR(), then TRUE is returned. + If Status is an EFI_ERROR(), then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Status The EFI_STATUS value to evaluate. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the status + expression being evaluated. + @retval TRUE Status is not an EFI_ERROR(). + @retval FALSE Status is an EFI_ERROR(). **/ BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If ValueA is equal ValueB, then TRUE is returned. + If ValueA is not equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA, + and DescriptionB are recorded and FALSE is returned. + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is equal to ValueB. + @retval FALSE ValueA is not equal to ValueB. **/ BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. - + If the contents of BufferA are identical to the contents of BufferB, then TRUE + is returned. If the contents of BufferA are not identical to the contents of + BufferB, then an assert is triggered and the location of the assert provided + by FunctionName, LineNumber, FileName, DescriptionA, and DescriptionB are + recorded and FALSE is returned. + + @param[in] BufferA Pointer to a buffer for comparison. + @param[in] BufferB Pointer to a buffer for comparison. + @param[in] Length Number of bytes to compare in BufferA and BufferB. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of BufferA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of BufferB. + + @retval TRUE The contents of BufferA are identical to the contents of + BufferB. + @retval FALSE The contents of BufferA are not identical to the contents of + BufferB. **/ BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN VOID *BufferA, + IN VOID *BufferB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If ValueA is not equal ValueB, then TRUE is returned. + If ValueA is equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA + and DescriptionB are recorded and FALSE is returned. + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is not equal to ValueB. + @retval FALSE ValueA is equal to ValueB. **/ BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If Status is equal to Expected, then TRUE is returned. + If Status is not equal to Expected, then an assert is triggered and the + location of the assert provided by FunctionName, LineNumber, FileName, and + Description are recorded and FALSE is returned. + + @param[in] Status EFI_STATUS value returned from an API under test. + @param[in] Expected The expected EFI_STATUS return value from an API + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string that is a description + of Status. + @retval TRUE Status is equal to Expected. + @retval FALSE Status is not equal to Expected. **/ BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ); /** - Helper function for the test assertion macros. - Please call via the public macro. - Do not call directly. + If Pointer is not equal to NULL, then TRUE is returned. + If Pointer is equal to NULL, then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and PointerName + are recorded and FALSE is returned. + @param[in] Pointer Pointer value to be checked against NULL. + @param[in] Expected The expected EFI_STATUS return value from a function + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] PointerName Null-terminated ASCII string that is a description + of Pointer. + + @retval TRUE Pointer is not equal to NULL. + @retval FALSE Pointer is equal to NULL. **/ BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName + IN VOID *Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName ); -/// -/// Unit-Test Logging Macros and Functions -/// /** Test logging macro that records an ERROR message in the test framework log. - Record will be associated with this test case during reporting. - - @param Format Standard C formatting string. - @param ... Print args. + Record is associated with the currently executing test case. + @param[in] Format Formatting string following the format defined in + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. **/ -#define UT_LOG_ERROR(Format, ...) \ - UnitTestLog (DEBUG_ERROR, Format, ##__VA_ARGS__ ); +#define UT_LOG_ERROR(Format, ...) \ + UnitTestLog (UNIT_TEST_LOG_LEVEL_ERROR, Format, ##__VA_ARGS__) /** Test logging macro that records a WARNING message in the test framework log. - Record will be associated with this test case during reporting. - - @param Format Standard C formatting string. - @param ... Print args. + Record is associated with the currently executing test case. + @param[in] Format Formatting string following the format defined in + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. **/ #define UT_LOG_WARNING(Format, ...) \ - UnitTestLog (DEBUG_WARN, Format, ##__VA_ARGS__ ); + UnitTestLog (UNIT_TEST_LOG_LEVEL_WARN, Format, ##__VA_ARGS__) /** Test logging macro that records an INFO message in the test framework log. - Record will be associated with this test case during reporting. - - @param Format Standard C formatting string. - @param ... Print args. + Record is associated with the currently executing test case. + @param[in] Format Formatting string following the format defined in + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. **/ -#define UT_LOG_INFO(Format, ...) \ - UnitTestLog (DEBUG_INFO, Format, ##__VA_ARGS__ ); +#define UT_LOG_INFO(Format, ...) \ + UnitTestLog (UNIT_TEST_LOG_LEVEL_INFO, Format, ##__VA_ARGS__) /** Test logging macro that records a VERBOSE message in the test framework log. - Record will be associated with this test case during reporting. - - @param Format Standard C formatting string. - @param ... Print args. + Record is associated with the currently executing test case. + @param[in] Format Formatting string following the format defined in + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. **/ #define UT_LOG_VERBOSE(Format, ...) \ - UnitTestLog (DEBUG_VERBOSE, Format, ##__VA_ARGS__ ); + UnitTestLog (UNIT_TEST_LOG_LEVEL_VERBOSE, Format, ##__VA_ARGS__) /** - Helper function for the test logging macros. - Please call via the public macros. - Do not call directly. + Test logging function that records a messages in the test framework log. + Record is associated with the currently executing test case. + @param[in] ErrorLevel The error level of the unit test log message. + @param[in] Format Formatting string following the format defined in the + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. **/ VOID EFIAPI UnitTestLog ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, ... ); diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c index 00adc0528e6..dd85b84b080 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Assert.c @@ -74,6 +74,24 @@ UnitTestLogFailure ( return; } +/** + If Expression is TRUE, then TRUE is returned. + If Expression is FALSE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + + @retval TRUE Expression is TRUE. + @retval FALSE Expression is FALSE. +**/ BOOLEAN EFIAPI UnitTestAssertTrue ( @@ -92,7 +110,7 @@ UnitTestAssertTrue ( LineNumber, Description ); - UnitTestLog (DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Expression (%a) is not TRUE!\n", FunctionName, LineNumber, @@ -102,6 +120,24 @@ UnitTestAssertTrue ( return Expression; } +/** + If Expression is FALSE, then TRUE is returned. + If Expression is TRUE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + + @retval TRUE Expression is FALSE. + @retval FALSE Expression is TRUE. +**/ BOOLEAN EFIAPI UnitTestAssertFalse ( @@ -120,8 +156,7 @@ UnitTestAssertFalse ( LineNumber, Description ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Expression (%a) is not FALSE!\n", FunctionName, LineNumber, @@ -131,6 +166,24 @@ UnitTestAssertFalse ( return !Expression; } +/** + If Status is not an EFI_ERROR(), then TRUE is returned. + If Status is an EFI_ERROR(), then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Status The EFI_STATUS value to evaluate. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the status + expression being evaluated. + + @retval TRUE Status is not an EFI_ERROR(). + @retval FALSE Status is an EFI_ERROR(). +**/ BOOLEAN EFIAPI UnitTestAssertNotEfiError ( @@ -150,8 +203,7 @@ UnitTestAssertNotEfiError ( Description, Status ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Status '%a' is EFI_ERROR (%r)!\n", FunctionName, LineNumber, @@ -162,6 +214,27 @@ UnitTestAssertNotEfiError ( return !EFI_ERROR( Status ); } +/** + If ValueA is equal ValueB, then TRUE is returned. + If ValueA is not equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA, + and DescriptionB are recorded and FALSE is returned. + + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is equal to ValueB. + @retval FALSE ValueA is not equal to ValueB. +**/ BOOLEAN EFIAPI UnitTestAssertEqual ( @@ -185,8 +258,7 @@ UnitTestAssertEqual ( ValueA, ValueB ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Value %a != %a (%d != %d)!\n", FunctionName, LineNumber, @@ -199,11 +271,36 @@ UnitTestAssertEqual ( return (ValueA == ValueB); } +/** + If the contents of BufferA are identical to the contents of BufferB, then TRUE + is returned. If the contents of BufferA are not identical to the contents of + BufferB, then an assert is triggered and the location of the assert provided + by FunctionName, LineNumber, FileName, DescriptionA, and DescriptionB are + recorded and FALSE is returned. + + @param[in] BufferA Pointer to a buffer for comparison. + @param[in] BufferB Pointer to a buffer for comparison. + @param[in] Length Number of bytes to compare in BufferA and BufferB. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of BufferA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of BufferB. + + @retval TRUE The contents of BufferA are identical to the contents of + BufferB. + @retval FALSE The contents of BufferA are not identical to the contents of + BufferB. +**/ BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UINTN ValueA, - IN UINTN ValueB, + IN VOID *BufferA, + IN VOID *BufferB, IN UINTN Length, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, @@ -212,7 +309,7 @@ UnitTestAssertMemEqual ( IN CONST CHAR8 *DescriptionB ) { - if (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) != 0) { + if (CompareMem(BufferA, BufferB, Length) != 0) { UnitTestLogFailure ( FAILURETYPE_ASSERTEQUAL, "%a::%d Memory at %a != %a for length %d bytes!\n", @@ -222,8 +319,7 @@ UnitTestAssertMemEqual ( DescriptionB, Length ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Value %a != %a for length %d bytes!\n", FunctionName, LineNumber, @@ -236,6 +332,27 @@ UnitTestAssertMemEqual ( return TRUE; } +/** + If ValueA is not equal ValueB, then TRUE is returned. + If ValueA is equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA + and DescriptionB are recorded and FALSE is returned. + + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is not equal to ValueB. + @retval FALSE ValueA is equal to ValueB. +**/ BOOLEAN EFIAPI UnitTestAssertNotEqual ( @@ -259,8 +376,7 @@ UnitTestAssertNotEqual ( ValueA, ValueB ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Value %a == %a (%d == %d)!\n", FunctionName, LineNumber, @@ -273,6 +389,26 @@ UnitTestAssertNotEqual ( return (ValueA != ValueB); } +/** + If Status is equal to Expected, then TRUE is returned. + If Status is not equal to Expected, then an assert is triggered and the + location of the assert provided by FunctionName, LineNumber, FileName, and + Description are recorded and FALSE is returned. + + @param[in] Status EFI_STATUS value returned from an API under test. + @param[in] Expected The expected EFI_STATUS return value from an API + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string that is a description + of Status. + + @retval TRUE Status is equal to Expected. + @retval FALSE Status is not equal to Expected. +**/ BOOLEAN EFIAPI UnitTestAssertStatusEqual ( @@ -294,8 +430,7 @@ UnitTestAssertStatusEqual ( Status, Expected ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Status '%a' is %r, should be %r!\n", FunctionName, LineNumber, @@ -307,10 +442,30 @@ UnitTestAssertStatusEqual ( return (Status == Expected); } +/** + If Pointer is not equal to NULL, then TRUE is returned. + If Pointer is equal to NULL, then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and PointerName + are recorded and FALSE is returned. + + @param[in] Pointer Pointer value to be checked against NULL. + @param[in] Expected The expected EFI_STATUS return value from a function + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] PointerName Null-terminated ASCII string that is a description + of Pointer. + + @retval TRUE Pointer is not equal to NULL. + @retval FALSE Pointer is equal to NULL. +**/ BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN VOID* Pointer, + IN VOID *Pointer, IN CONST CHAR8 *FunctionName, IN UINTN LineNumber, IN CONST CHAR8 *FileName, @@ -325,8 +480,7 @@ UnitTestAssertNotNull ( LineNumber, PointerName ); - UnitTestLog ( - DEBUG_ERROR, + UT_LOG_ERROR ( "[ASSERT FAIL] %a::%d Pointer (%a) is NULL!\n", FunctionName, LineNumber, diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c index ced9dfecac5..0bafa78314a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -19,14 +19,32 @@ #define MAX_STRING_SIZE 1025 +/** + If Expression is TRUE, then TRUE is returned. + If Expression is FALSE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + + @retval TRUE Expression is TRUE. + @retval FALSE Expression is FALSE. +**/ BOOLEAN EFIAPI UnitTestAssertTrue ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -37,14 +55,32 @@ UnitTestAssertTrue ( return Expression; } +/** + If Expression is FALSE, then TRUE is returned. + If Expression is TRUE, then an assert is triggered and the location of the + assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Expression The BOOLEAN result of the expression evaluation. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the expression being + evaluated. + + @retval TRUE Expression is FALSE. + @retval FALSE Expression is TRUE. +**/ BOOLEAN EFIAPI UnitTestAssertFalse ( - IN BOOLEAN Expression, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN BOOLEAN Expression, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -55,14 +91,32 @@ UnitTestAssertFalse ( return !Expression; } +/** + If Status is not an EFI_ERROR(), then TRUE is returned. + If Status is an EFI_ERROR(), then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and Description are + recorded and FALSE is returned. + + @param[in] Status The EFI_STATUS value to evaluate. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string of the status + expression being evaluated. + + @retval TRUE Status is not an EFI_ERROR(). + @retval FALSE Status is an EFI_ERROR(). +**/ BOOLEAN EFIAPI UnitTestAssertNotEfiError ( - IN EFI_STATUS Status, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -73,16 +127,37 @@ UnitTestAssertNotEfiError ( return !EFI_ERROR (Status); } +/** + If ValueA is equal ValueB, then TRUE is returned. + If ValueA is not equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA, + and DescriptionB are recorded and FALSE is returned. + + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is equal to ValueB. + @retval FALSE ValueA is not equal to ValueB. +**/ BOOLEAN EFIAPI UnitTestAssertEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -93,40 +168,86 @@ UnitTestAssertEqual ( return (ValueA == ValueB); } +/** + If the contents of BufferA are identical to the contents of BufferB, then TRUE + is returned. If the contents of BufferA are not identical to the contents of + BufferB, then an assert is triggered and the location of the assert provided + by FunctionName, LineNumber, FileName, DescriptionA, and DescriptionB are + recorded and FALSE is returned. + + @param[in] BufferA Pointer to a buffer for comparison. + @param[in] BufferB Pointer to a buffer for comparison. + @param[in] Length Number of bytes to compare in BufferA and BufferB. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of BufferA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of BufferB. + + @retval TRUE The contents of BufferA are identical to the contents of + BufferB. + @retval FALSE The contents of BufferA are not identical to the contents of + BufferB. +**/ BOOLEAN EFIAPI UnitTestAssertMemEqual ( - IN UINTN ValueA, - IN UINTN ValueB, - IN UINTN Length, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN VOID *BufferA, + IN VOID *BufferB, + IN UINTN Length, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { CHAR8 TempStr[MAX_STRING_SIZE]; BOOLEAN Result; - Result = (CompareMem((VOID*)ValueA, (VOID*)ValueB, Length) == 0); + Result = (CompareMem(BufferA, BufferB, Length) == 0); - snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, (VOID *)ValueA, DescriptionB, (VOID *)ValueB); + snprintf (TempStr, sizeof(TempStr), "UT_ASSERT_MEM_EQUAL(%s:%p, %s:%p)", DescriptionA, BufferA, DescriptionB, BufferB); _assert_true (Result, TempStr, FileName, (INT32)LineNumber); return Result; } +/** + If ValueA is not equal ValueB, then TRUE is returned. + If ValueA is equal to ValueB, then an assert is triggered and the location + of the assert provided by FunctionName, LineNumber, FileName, DescriptionA + and DescriptionB are recorded and FALSE is returned. + + @param[in] ValueA 64-bit value. + @param[in] ValueB 64-bit value. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] DescriptionA Null-terminated ASCII string that is a description + of ValueA. + @param[in] DescriptionB Null-terminated ASCII string that is a description + of ValueB. + + @retval TRUE ValueA is not equal to ValueB. + @retval FALSE ValueA is equal to ValueB. +**/ BOOLEAN EFIAPI UnitTestAssertNotEqual ( - IN UINT64 ValueA, - IN UINT64 ValueB, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *DescriptionA, - IN CONST CHAR8 *DescriptionB + IN UINT64 ValueA, + IN UINT64 ValueB, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *DescriptionA, + IN CONST CHAR8 *DescriptionB ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -137,15 +258,35 @@ UnitTestAssertNotEqual ( return (ValueA != ValueB); } +/** + If Status is equal to Expected, then TRUE is returned. + If Status is not equal to Expected, then an assert is triggered and the + location of the assert provided by FunctionName, LineNumber, FileName, and + Description are recorded and FALSE is returned. + + @param[in] Status EFI_STATUS value returned from an API under test. + @param[in] Expected The expected EFI_STATUS return value from an API + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] Description Null-terminated ASCII string that is a description + of Status. + + @retval TRUE Status is equal to Expected. + @retval FALSE Status is not equal to Expected. +**/ BOOLEAN EFIAPI UnitTestAssertStatusEqual ( - IN EFI_STATUS Status, - IN EFI_STATUS Expected, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *Description + IN EFI_STATUS Status, + IN EFI_STATUS Expected, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *Description ) { CHAR8 TempStr[MAX_STRING_SIZE]; @@ -156,14 +297,34 @@ UnitTestAssertStatusEqual ( return (Status == Expected); } +/** + If Pointer is not equal to NULL, then TRUE is returned. + If Pointer is equal to NULL, then an assert is triggered and the location of + the assert provided by FunctionName, LineNumber, FileName, and PointerName + are recorded and FALSE is returned. + + @param[in] Pointer Pointer value to be checked against NULL. + @param[in] Expected The expected EFI_STATUS return value from a function + under test. + @param[in] FunctionName Null-terminated ASCII string of the function + executing the assert macro. + @param[in] LineNumber The source file line number of the assert macro. + @param[in] FileName Null-terminated ASCII string of the filename + executing the assert macro. + @param[in] PointerName Null-terminated ASCII string that is a description + of Pointer. + + @retval TRUE Pointer is not equal to NULL. + @retval FALSE Pointer is equal to NULL. +**/ BOOLEAN EFIAPI UnitTestAssertNotNull ( - IN VOID* Pointer, - IN CONST CHAR8 *FunctionName, - IN UINTN LineNumber, - IN CONST CHAR8 *FileName, - IN CONST CHAR8 *PointerName + IN VOID *Pointer, + IN CONST CHAR8 *FunctionName, + IN UINTN LineNumber, + IN CONST CHAR8 *FileName, + IN CONST CHAR8 *PointerName ) { CHAR8 TempStr[MAX_STRING_SIZE]; diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index 718b0b64f6b..fc94ea3058e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -24,11 +24,11 @@ struct _UNIT_TEST_LOG_PREFIX_STRING { CHAR8 *String; }; -struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = { - { DEBUG_ERROR, "[ERROR] " }, - { DEBUG_WARN, "[WARNING] " }, - { DEBUG_INFO, "[INFO] " }, - { DEBUG_VERBOSE, "[VERBOSE] " } +struct _UNIT_TEST_LOG_PREFIX_STRING mLogPrefixStrings[] = { + { UNIT_TEST_LOG_LEVEL_ERROR, "[ERROR] " }, + { UNIT_TEST_LOG_LEVEL_WARN, "[WARNING] " }, + { UNIT_TEST_LOG_LEVEL_INFO, "[INFO] " }, + { UNIT_TEST_LOG_LEVEL_VERBOSE, "[VERBOSE] " } }; // @@ -142,11 +142,20 @@ UnitTestLogInit ( } } +/** + Test logging function that records a messages in the test framework log. + Record is associated with the currently executing test case. + + @param[in] ErrorLevel The error level of the unit test log message. + @param[in] Format Formatting string following the format defined in the + MdePkg/Include/Library/PrintLib.h. + @param[in] ... Print args. +**/ VOID EFIAPI UnitTestLog ( - IN UINTN ErrorLevel, - IN CONST CHAR8 *Format, + IN UINTN ErrorLevel, + IN CONST CHAR8 *Format, ... ) { @@ -155,17 +164,15 @@ UnitTestLog ( CHAR8 LogString[UNIT_TEST_MAX_SINGLE_LOG_STRING_LENGTH]; CONST CHAR8 *LogTypePrefix; VA_LIST Marker; - UINTN LogLevel; FrameworkHandle = GetActiveFrameworkHandle (); LogTypePrefix = NULL; - LogLevel = (UINTN)PcdGet32 (UnitTestLogLevel); // - // Make sure that this debug mode is enabled. + // Make sure that this unit test log level is enabled. // - if ((ErrorLevel & LogLevel) == 0) { + if ((ErrorLevel & (UINTN)PcdGet32 (PcdUnitTestLogLevel)) == 0) { return; } diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c index 8340e18f15d..1830955cca4 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -75,11 +75,11 @@ RunTestSuite ( // // Next, if we're still running, make sure that our test prerequisites are in place. - if (Test->Result == UNIT_TEST_PENDING && Test->PreReq != NULL) { + if (Test->Result == UNIT_TEST_PENDING && Test->Prerequisite != NULL) { DEBUG ((DEBUG_VERBOSE, "PREREQ\n")); - if (Test->PreReq (Test->Context) != UNIT_TEST_PASSED) { - DEBUG ((DEBUG_ERROR, "PreReq Not Met\n")); - Test->Result = UNIT_TEST_ERROR_PREREQ_NOT_MET; + if (Test->Prerequisite (Test->Context) != UNIT_TEST_PASSED) { + DEBUG ((DEBUG_ERROR, "Prerequisite Not Met\n")); + Test->Result = UNIT_TEST_ERROR_PREREQUISITE_NOT_MET; ParentFramework->CurrentTest = NULL; continue; } @@ -89,14 +89,14 @@ RunTestSuite ( // Now we should be ready to call the actual test. // We set the status to UNIT_TEST_RUNNING in case the test needs to reboot // or quit. The UNIT_TEST_RUNNING state will allow the test to resume - // but will prevent the PreReq from being dispatched a second time. + // but will prevent the Prerequisite from being dispatched a second time. Test->Result = UNIT_TEST_RUNNING; Test->Result = Test->RunTest (Test->Context); // // Finally, clean everything up, if need be. if (Test->CleanUp != NULL) { - DEBUG (( DEBUG_VERBOSE, "CLEANUP\n")); + DEBUG ((DEBUG_VERBOSE, "CLEANUP\n")); Test->CleanUp (Test->Context); } @@ -113,6 +113,20 @@ RunTestSuite ( return EFI_SUCCESS; } +/** + Execute all unit test cases in all unit test suites added to a Framework. + + Once a unit test framework is initialized and all unit test suites and unit + test cases are registered, this function will cause the unit test framework to + dispatch all unit test cases in sequence and record the results for reporting. + + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. +**/ EFI_STATUS EFIAPI RunAllTestSuites ( diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 9b58a83a493..1abee28b988 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -65,7 +65,7 @@ CmockaUnitTestFunctionRunner ( // stdout and stderr in their xml format // if (UnitTest->Log != NULL) { - print_message("UnitTest: %s - %s\n", UnitTest->ClassName, UnitTest->Description); + print_message("UnitTest: %s - %s\n", UnitTest->Name, UnitTest->Description); print_message("Log Output Start\n"); print_message("%s", UnitTest->Log); print_message("Log Output End\n"); @@ -87,12 +87,12 @@ CmockaUnitTestSetupFunctionRunner ( Suite = (UNIT_TEST_SUITE *)(UnitTest->ParentSuite); Framework = (UNIT_TEST_FRAMEWORK *)(Suite->ParentFramework); - if (UnitTest->PreReq == NULL) { + if (UnitTest->Prerequisite == NULL) { return 0; } Framework->CurrentTest = UnitTest; - Result = UnitTest->PreReq (UnitTest->Context); + Result = UnitTest->Prerequisite (UnitTest->Context); Framework->CurrentTest = NULL; // @@ -232,6 +232,20 @@ RunTestSuite ( return EFI_SUCCESS; } +/** + Execute all unit test cases in all unit test suites added to a Framework. + + Once a unit test framework is initialized and all unit test suites and unit + test cases are registered, this function will cause the unit test framework to + dispatch all unit test cases in sequence and record the results for reporting. + + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. +**/ EFI_STATUS EFIAPI RunAllTestSuites ( diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 04986df9eb6..5486f4ed1ad 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -95,7 +95,7 @@ SetSuiteFingerprint ( // For this one, we'll use the fingerprint from the framework, and the title of the suite. NewFingerprint = CalculateCrc32( &Framework->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Title, (AsciiStrLen( Suite->Title ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Package, (AsciiStrLen(Suite->Package) * sizeof(CHAR8)) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Suite->Name, (AsciiStrLen(Suite->Name) * sizeof(CHAR8)) ); CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); return; @@ -114,7 +114,7 @@ SetTestFingerprint ( // For this one, we'll use the fingerprint from the suite, and the description and classname of the test. NewFingerprint = CalculateCrc32( &Suite->Fingerprint[0], UNIT_TEST_FINGERPRINT_SIZE ); NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Description, (AsciiStrLen( Test->Description ) * sizeof( CHAR8 )) ); - NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->ClassName, (AsciiStrLen(Test->ClassName) * sizeof(CHAR8)) ); + NewFingerprint = (NewFingerprint >> 8) ^ CalculateCrc32( Test->Name, (AsciiStrLen(Test->Name) * sizeof(CHAR8)) ); CopyMem( Fingerprint, &NewFingerprint, UNIT_TEST_FINGERPRINT_SIZE ); return; @@ -130,10 +130,24 @@ CompareFingerprints ( return (CompareMem( FingerprintA, FingerprintB, UNIT_TEST_FINGERPRINT_SIZE ) == 0); } +/** + Cleanup a test framework. + + After tests are run, this will teardown the entire framework and free all + allocated data within. + + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + + @retval EFI_SUCCESS All resources associated with framework were + freed. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. +**/ EFI_STATUS EFIAPI FreeUnitTestFramework ( - IN UNIT_TEST_FRAMEWORK_HANDLE Framework + IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle ) { // TODO: Finish this function. @@ -160,16 +174,34 @@ FreeUnitTestTestEntry ( return EFI_SUCCESS; } -/* - Method to Initialize the Unit Test framework - - @retval Success - Unit Test init. - @retval EFI_ERROR - Unit Tests init failed. -*/ +/** + Method to Initialize the Unit Test framework. This function registers the + test name and also initializes the internal state of the test framework to + receive any new suites and tests. + + @param[out] FrameworkHandle Unit test framework to be created. + @param[in] Title Null-terminated ASCII string that is the user + friendly name of the framework. String is + copied. + @param[in] ShortTitle Null-terminaled ASCII short string that is the + short name of the framework with no spaces. + String is copied. + @param[in] VersionString Null-terminaled ASCII version string for the + framework. String is copied. + + @retval EFI_SUCCESS The unit test framework was initialized. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER Title is NULL. + @retval EFI_INVALID_PARAMETER ShortTitle is NULL. + @retval EFI_INVALID_PARAMETER VersionString is NULL. + @retval EFI_INVALID_PARAMETER ShortTitle is invalid. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test framework. +**/ EFI_STATUS EFIAPI InitUnitTestFramework ( - OUT UNIT_TEST_FRAMEWORK_HANDLE *Framework, + OUT UNIT_TEST_FRAMEWORK_HANDLE *FrameworkHandle, IN CHAR8 *Title, IN CHAR8 *ShortTitle, IN CHAR8 *VersionString @@ -186,7 +218,7 @@ InitUnitTestFramework ( // // First, check all pointers and make sure nothing's broked. // - if (Framework == NULL || Title == NULL || + if (FrameworkHandle == NULL || Title == NULL || ShortTitle == NULL || VersionString == NULL) { return EFI_INVALID_PARAMETER; } @@ -249,7 +281,7 @@ InitUnitTestFramework ( // If we're good, then let's copy the framework. // if (!EFI_ERROR (Status)) { - *Framework = NewFrameworkHandle; + *FrameworkHandle = NewFrameworkHandle; } else { // // Otherwise, we need to undo this horrible thing that we've done. @@ -260,15 +292,41 @@ InitUnitTestFramework ( return Status; } +/** + Registers a Unit Test Suite in the Unit Test Framework. + At least one test suite must be registered, because all test cases must be + within a unit test suite. + + @param[out] SuiteHandle Unit test suite to create + @param[in] FrameworkHandle Unit test framework to add unit test suite to + @param[in] Title Null-terminated ASCII string that is the user + friendly name of the test suite. String is + copied. + @param[in] Name Null-terminated ASCII string that is the short + name of the test suite with no spaces. String + is copied. + @param[in] Setup Setup function, runs before suite. This is an + optional parameter that may be NULL. + @param[in] Teardown Teardown function, runs after suite. This is an + optional parameter that may be NULL. + + @retval EFI_SUCCESS The unit test suite was created. + @retval EFI_INVALID_PARAMETER SuiteHandle is NULL. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER Title is NULL. + @retval EFI_INVALID_PARAMETER Name is NULL. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit test suite. +**/ EFI_STATUS EFIAPI CreateUnitTestSuite ( - OUT UNIT_TEST_SUITE_HANDLE *Suite, + OUT UNIT_TEST_SUITE_HANDLE *SuiteHandle, IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, IN CHAR8 *Title, - IN CHAR8 *Package, - IN UNIT_TEST_SUITE_SETUP Sup, OPTIONAL - IN UNIT_TEST_SUITE_TEARDOWN Tdn OPTIONAL + IN CHAR8 *Name, + IN UNIT_TEST_SUITE_SETUP Setup OPTIONAL, + IN UNIT_TEST_SUITE_TEARDOWN Teardown OPTIONAL ) { EFI_STATUS Status; @@ -281,7 +339,7 @@ CreateUnitTestSuite ( // // First, let's check to make sure that our parameters look good. // - if ((Framework == NULL) || (Title == NULL) || (Package == NULL)) { + if ((SuiteHandle == NULL) || (Framework == NULL) || (Title == NULL) || (Name == NULL)) { return EFI_INVALID_PARAMETER; } @@ -298,9 +356,9 @@ CreateUnitTestSuite ( // NewSuiteEntry->UTS.NumTests = 0; NewSuiteEntry->UTS.Title = AllocateAndCopyString (Title); - NewSuiteEntry->UTS.Package = AllocateAndCopyString (Package); - NewSuiteEntry->UTS.Setup = Sup; - NewSuiteEntry->UTS.Teardown = Tdn; + NewSuiteEntry->UTS.Name = AllocateAndCopyString (Name); + NewSuiteEntry->UTS.Setup = Setup; + NewSuiteEntry->UTS.Teardown = Teardown; NewSuiteEntry->UTS.ParentFramework = FrameworkHandle; InitializeListHead (&(NewSuiteEntry->Entry)); // List entry for sibling suites. InitializeListHead (&(NewSuiteEntry->UTS.TestCaseList)); // List entry for child tests. @@ -309,7 +367,7 @@ CreateUnitTestSuite ( goto Exit; } - if (NewSuiteEntry->UTS.Package == NULL) { + if (NewSuiteEntry->UTS.Name == NULL) { Status = EFI_OUT_OF_RESOURCES; goto Exit; } @@ -325,7 +383,7 @@ CreateUnitTestSuite ( // if (!EFI_ERROR( Status )) { InsertTailList (&(Framework->TestSuiteList), (LIST_ENTRY *)NewSuiteEntry); - *Suite = (UNIT_TEST_SUITE_HANDLE)(&NewSuiteEntry->UTS); + *SuiteHandle = (UNIT_TEST_SUITE_HANDLE)(&NewSuiteEntry->UTS); } else { // // Otherwise, make with the destruction. @@ -336,15 +394,39 @@ CreateUnitTestSuite ( return Status; } +/** + Adds test case to Suite + + @param[in] SuiteHandle Unit test suite to add test to. + @param[in] Description Null-terminated ASCII string that is the user + friendly description of a test. String is copied. + @param[in] Name Null-terminated ASCII string that is the short name + of the test with no spaces. String is copied. + @param[in] Function Unit test function. + @param[in] Prerequisite Prerequisite function, runs before test. This is + an optional parameter that may be NULL. + @param[in] CleanUp Clean up function, runs after test. This is an + optional parameter that may be NULL. + @param[in] Context Pointer to context. This is an optional parameter + that may be NULL. + + @retval EFI_SUCCESS The unit test case was added to Suite. + @retval EFI_INVALID_PARAMETER SuiteHandle is NULL. + @retval EFI_INVALID_PARAMETER Description is NULL. + @retval EFI_INVALID_PARAMETER Name is NULL. + @retval EFI_INVALID_PARAMETER Function is NULL. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + add the unit test case to Suite. +**/ EFI_STATUS EFIAPI AddTestCase ( IN UNIT_TEST_SUITE_HANDLE SuiteHandle, IN CHAR8 *Description, - IN CHAR8 *ClassName, - IN UNIT_TEST_FUNCTION Func, - IN UNIT_TEST_PREREQ PreReq, OPTIONAL - IN UNIT_TEST_CLEANUP CleanUp, OPTIONAL + IN CHAR8 *Name, + IN UNIT_TEST_FUNCTION Function, + IN UNIT_TEST_PREREQUISITE Prerequisite OPTIONAL, + IN UNIT_TEST_CLEANUP CleanUp OPTIONAL, IN UNIT_TEST_CONTEXT Context OPTIONAL ) { @@ -360,7 +442,7 @@ AddTestCase ( // // First, let's check to make sure that our parameters look good. // - if ((Suite == NULL) || (Description == NULL) || (ClassName == NULL)) { + if ((Suite == NULL) || (Description == NULL) || (Name == NULL) || (Function == NULL)) { return EFI_INVALID_PARAMETER; } @@ -374,13 +456,13 @@ AddTestCase ( // // Copy the fields we think we need. NewTestEntry->UT.Description = AllocateAndCopyString (Description); - NewTestEntry->UT.ClassName = AllocateAndCopyString (ClassName); + NewTestEntry->UT.Name = AllocateAndCopyString (Name); NewTestEntry->UT.FailureType = FAILURETYPE_NOFAILURE; NewTestEntry->UT.FailureMessage[0] = '\0'; NewTestEntry->UT.Log = NULL; - NewTestEntry->UT.PreReq = PreReq; + NewTestEntry->UT.Prerequisite = Prerequisite; NewTestEntry->UT.CleanUp = CleanUp; - NewTestEntry->UT.RunTest = Func; + NewTestEntry->UT.RunTest = Function; NewTestEntry->UT.Context = Context; NewTestEntry->UT.Result = UNIT_TEST_PENDING; NewTestEntry->UT.ParentSuite = SuiteHandle; @@ -389,6 +471,10 @@ AddTestCase ( Status = EFI_OUT_OF_RESOURCES; goto Exit; } + if (NewTestEntry->UT.Name == NULL) { + Status = EFI_OUT_OF_RESOURCES; + goto Exit; + } // // Create the test fingerprint. @@ -690,11 +776,41 @@ SerializeState ( return Header; } +/** + Leverages a framework-specific mechanism (see UnitTestPersistenceLib if you're + a framework author) to save the state of the executing framework along with + any allocated data so that the test may be resumed upon reentry. A test case + should pass any needed context (which, to prevent an infinite loop, should be + at least the current execution count) which will be saved by the framework and + passed to the test case upon resume. + + Generally called from within a test case prior to quitting or rebooting. + + @param[in] FrameworkHandle A handle to the current running framework that + dispatched the test. Necessary for recording + certain test events with the framework. + @param[in] ContextToSave A buffer of test case-specific data to be saved + along with framework state. Will be passed as + "Context" to the test case upon resume. This + is an optional parameter that may be NULL. + @param[in] ContextToSaveSize Size of the ContextToSave buffer. + + @retval EFI_SUCCESS The framework state and context were saved. + @retval EFI_INVALID_PARAMETER FrameworkHandle is NULL. + @retval EFI_INVALID_PARAMETER ContextToSave is not NULL and + ContextToSaveSize is 0. + @retval EFI_INVALID_PARAMETER ContextToSave is >= 4GB. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + save the framework and context state. + @retval EFI_DEVICE_ERROR The framework and context state could not be + saved to a persistent storage devide due to a + device error. +**/ EFI_STATUS EFIAPI SaveFrameworkState ( IN UNIT_TEST_FRAMEWORK_HANDLE FrameworkHandle, - IN UNIT_TEST_CONTEXT ContextToSave, OPTIONAL + IN UNIT_TEST_CONTEXT ContextToSave OPTIONAL, IN UINTN ContextToSaveSize ) { diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf index 0df2f8afec4..5f2c810ef2e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf @@ -35,4 +35,4 @@ UnitTestResultReportLib [Pcd] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES + gUnitTestFrameworkPkgTokenSpaceGuid.PcdUnitTestLogLevel ## CONSUMES diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf index cc6931937da..15090f84d30 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf @@ -36,4 +36,4 @@ CmockaLib [Pcd] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel ## CONSUMES + gUnitTestFrameworkPkgTokenSpaceGuid.PcdUnitTestLogLevel ## CONSUMES diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c index 30d4eb2dcc5..a802afce7db 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -34,12 +34,12 @@ struct _UNIT_TEST_FAILURE_TYPE_STRING { }; struct _UNIT_TEST_STATUS_STRING mStatusStrings[] = { - { UNIT_TEST_PASSED, "PASSED"}, - { UNIT_TEST_ERROR_PREREQ_NOT_MET, "NOT RUN - PREREQ FAILED"}, - { UNIT_TEST_ERROR_TEST_FAILED, "FAILED"}, - { UNIT_TEST_RUNNING, "RUNNING"}, - { UNIT_TEST_PENDING, "PENDING"}, - { 0, "**UNKNOWN**"} + { UNIT_TEST_PASSED, "PASSED"}, + { UNIT_TEST_ERROR_PREREQUISITE_NOT_MET, "NOT RUN - PREREQUISITE FAILED"}, + { UNIT_TEST_ERROR_TEST_FAILED, "FAILED"}, + { UNIT_TEST_RUNNING, "RUNNING"}, + { UNIT_TEST_PENDING, "PENDING"}, + { 0, "**UNKNOWN**"} }; struct _UNIT_TEST_FAILURE_TYPE_STRING mFailureTypeStrings[] = { @@ -155,7 +155,7 @@ OutputUnitTestFrameworkReport ( ReportPrint ("/////////////////////////////////////////////////////////\n"); ReportPrint (" SUITE: %a\n", Suite->UTS.Title); - ReportPrint (" PACKAGE: %a\n", Suite->UTS.Package); + ReportPrint (" PACKAGE: %a\n", Suite->UTS.Name); ReportPrint ("/////////////////////////////////////////////////////////\n"); // @@ -166,7 +166,7 @@ OutputUnitTestFrameworkReport ( Test = (UNIT_TEST_LIST_ENTRY*)GetNextNode(&(Suite->UTS.TestCaseList), (LIST_ENTRY*)Test)) { ReportPrint ("*********************************************************\n"); - ReportPrint (" CLASS NAME: %a\n", Test->UT.ClassName); + ReportPrint (" CLASS NAME: %a\n", Test->UT.Name); ReportPrint (" TEST: %a\n", Test->UT.Description); ReportPrint (" STATUS: %a\n", GetStringForUnitTestStatus (Test->UT.Result)); ReportPrint (" FAILURE: %a\n", GetStringForFailureType (Test->UT.FailureType)); @@ -186,7 +186,7 @@ OutputUnitTestFrameworkReport ( break; case UNIT_TEST_PENDING: // Fall through... case UNIT_TEST_RUNNING: // Fall through... - case UNIT_TEST_ERROR_PREREQ_NOT_MET: + case UNIT_TEST_ERROR_PREREQUISITE_NOT_MET: SNotRun++; break; default: diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 62dd65629d3..193d63c8d35 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -46,14 +46,14 @@ typedef UINT32 FAILURE_TYPE; typedef struct { CHAR8 *Description; - CHAR8 *ClassName; //can't have spaces and should be short + CHAR8 *Name; //can't have spaces and should be short CHAR8 *Log; FAILURE_TYPE FailureType; CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; UNIT_TEST_STATUS Result; UNIT_TEST_FUNCTION RunTest; - UNIT_TEST_PREREQ PreReq; + UNIT_TEST_PREREQUISITE Prerequisite; UNIT_TEST_CLEANUP CleanUp; UNIT_TEST_CONTEXT Context; UNIT_TEST_SUITE_HANDLE ParentSuite; @@ -67,7 +67,7 @@ typedef struct { typedef struct { UINTN NumTests; CHAR8 *Title; - CHAR8 *Package; + CHAR8 *Name; UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; UNIT_TEST_SUITE_SETUP Setup; UNIT_TEST_SUITE_TEARDOWN Teardown; diff --git a/UnitTestFrameworkPkg/ReadMe.md b/UnitTestFrameworkPkg/ReadMe.md index 32730df7718..7296f0a45c5 100644 --- a/UnitTestFrameworkPkg/ReadMe.md +++ b/UnitTestFrameworkPkg/ReadMe.md @@ -143,9 +143,9 @@ usage to the suite title and package name strings in the test suites. The former latter is for xUnit parsing. The test case function pointer is what is actually executed as the "test" and the prototype should be `UNIT_TEST_FUNCTION`. The last three parameters require a little bit more explaining. -The prerequisite check function has a prototype of `UNIT_TEST_PREREQ` and -- if provided -- will be called +The prerequisite check function has a prototype of `UNIT_TEST_PREREQUISITE` and -- if provided -- will be called immediately before the test case. If this function returns any error, the test case will not be run and will be -recorded as `UNIT_TEST_ERROR_PREREQ_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called +recorded as `UNIT_TEST_ERROR_PREREQUISITE_NOT_MET`. The cleanup function (prototype `UNIT_TEST_CLEANUP`) will be called immediately after the test case to provide an opportunity to reset any global state that may have been changed in the test case. In the event of a prerequisite failure, the cleanup function will also be skipped. If either of these functions is not needed, pass `NULL`. diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec index 68c6f4fad63..069289f0096 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec @@ -1,8 +1,7 @@ ## @file -# -# This Package provides all definitions(including functions, MACROs, structures -# and library classes) and libraries instances, which are used to support Unit -# Testing and Interface testing +# This Package provides all definitions (including functions, MACROs, +# structures library classes, and PCDs) and libraries instances, which are used +# to support unit testing and interface testing. # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent @@ -11,7 +10,8 @@ [Defines] DEC_SPECIFICATION = 0x00010005 - PACKAGE_NAME = UnitTestPkg + PACKAGE_NAME = UnitTestFrameworkPkg + PACKAGE_UNI_FILE = UnitTestFrameworkPkg.uni PACKAGE_GUID = 4A70C4A0-D72C-4D3F-9943-BE7C41C50BA3 PACKAGE_VERSION = 1.00 @@ -36,7 +36,15 @@ UnitTestBootLib|PrivateInclude/Library/UnitTestBootLib.h [Guids] - gUnitTestPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } + gUnitTestFrameworkPkgTokenSpaceGuid = { 0x833d3aba, 0x39b4, 0x43a2, { 0xb9, 0x30, 0x7a, 0x34, 0x53, 0x39, 0x31, 0xb3 } } [PcdsFixedAtBuild] - gUnitTestPkgTokenSpaceGuid.UnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 + ## This flag is used to control build time optimization based on unit test + # log level. The default value is 0xFFFFFFFF to enable all unit test log + # messages. + # BIT0 - Error unit test log messages.
+ # BIT1 - Warning unit test log messages.
+ # BIT2 - Informational unit test log messages.
+ # BIT3 - Verbose unit test log messages.
+ # @Prompt Unit Test Log Message Level + gUnitTestFrameworkPkgTokenSpaceGuid.PcdUnitTestLogLevel|0xFFFFFFFF|UINT32|0x00000001 diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.uni b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.uni new file mode 100644 index 00000000000..180675ae1a0 --- /dev/null +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.uni @@ -0,0 +1,21 @@ +// /** @file +// This Package provides all definitions (including functions, MACROs, +// structures library classes, and PCDs) and libraries instances, which are used +// to support unit testing and interface testing. +// +// Copyright (c) 2020, Intel Corporation. All rights reserved.
+// SPDX-License-Identifier: BSD-2-Clause-Patent +// +// **/ + +#string STR_PACKAGE_ABSTRACT #language en-US "This Package provides all definitions (including functions, MACROs, structures library classes, and PCDs) and libraries instances, which are used to support unit testing and interface testing." + +#string STR_PACKAGE_DESCRIPTION #language en-US "This Package provides all definitions (including functions, MACROs, structures library classes, and PCDs) and libraries instances, which are used to support unit testing and interface testing." + +#string STR_gUnitTestFrameworkPkgTokenSpaceGuid_PcdUnitTestLogLevel_PROMPT #language en-US "Unit Test Log Message Level" + +#string STR_gUnitTestFrameworkPkgTokenSpaceGuid_PcdUnitTestLogLevel_HELP #language en-US "This flag is used to control build time optimization based on unit test log level. The default value is 0xFFFFFFFF to enable all unit test log messages.

\n" + "BIT0 - Error unit test log messages.
\n" + "BIT1 - Warning unit test log messages.
\n" + "BIT2 - Informational unit test log messages.
\n" + "BIT3 - Verbose unit test log messages.
\n" From 4523df71d196a3e5dba8a270c048d7be1dca8b9c Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 21 Jan 2020 15:11:31 -0800 Subject: [PATCH 380/384] UnitTestFrameworkPkg/UnitTestLib: Remove unused local Framework Remove local variable Framework that is set but not used. Resolves GCC build failure. Signed-off-by: Michael D Kinney --- UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c | 6 ------ 1 file changed, 6 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 1abee28b988..240200b83fb 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -132,8 +132,6 @@ CmockaUnitTestSuiteSetupFunctionRunner ( void **state ) { - UNIT_TEST_FRAMEWORK *Framework; - if (mActiveUnitTestSuite == NULL) { return -1; } @@ -141,7 +139,6 @@ CmockaUnitTestSuiteSetupFunctionRunner ( return 0; } - Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); mActiveUnitTestSuite->Setup (); // // Always succeed @@ -154,8 +151,6 @@ CmockaUnitTestSuiteTeardownFunctionRunner ( void **state ) { - UNIT_TEST_FRAMEWORK *Framework; - if (mActiveUnitTestSuite == NULL) { return -1; } @@ -163,7 +158,6 @@ CmockaUnitTestSuiteTeardownFunctionRunner ( return 0; } - Framework = (UNIT_TEST_FRAMEWORK *)(mActiveUnitTestSuite->ParentFramework); mActiveUnitTestSuite->Teardown (); // // Always succeed From ef82a8fc205e2823461d8aab321dd8eb8e1ffe41 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 21 Jan 2020 15:23:00 -0800 Subject: [PATCH 381/384] MdeModulePkg/DxeResetSystemLib/Test: Update mock ResetSystem() API to be EFIAPI Resolves GCC build failure. Signed-off-by: Michael D Kinney --- .../DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c | 1 + 1 file changed, 1 insertion(+) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index 0312f9c6e43..8ce13db2749 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -51,6 +51,7 @@ **/ STATIC VOID +EFIAPI MockResetSystem ( IN EFI_RESET_TYPE ResetType, IN EFI_STATUS ResetStatus, From 1f0a85099a70c423e4b6d48ae45910e824299b15 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Tue, 21 Jan 2020 18:41:47 -0800 Subject: [PATCH 382/384] UnitTestFrameworkPkg: More clean ups * EDK II code style issues * CR/LF line endings * Copyright updates Signed-off-by: Michael D Kinney --- .../UnitTest/DxeResetSystemLibUnitTest.c | 556 ++++++------ .../DxeResetSystemLibUnitTestHost.inf | 66 +- .../MockUefiRuntimeServicesTableLib.c | 26 +- MdeModulePkg/Test/MdeModulePkgHostTest.dsc | 63 +- MdePkg/Test/MdePkgHostTest.dsc | 3 +- .../UnitTest/Library/BaseLib/Base64UnitTest.c | 788 +++++++++--------- .../Library/BaseLib/BaseLibUnitTestsHost.inf | 71 +- .../Library/BaseLib/BaseLibUnitTestsUefi.inf | 74 +- .../IA32/SafeIntLibUintnIntnUnitTests.c | 2 +- .../BaseSafeIntLib/TestBaseSafeIntLib.c | 6 +- .../BaseSafeIntLib/TestBaseSafeIntLib.h | 2 +- .../BaseSafeIntLib/TestBaseSafeIntLibDxe.inf | 4 +- .../BaseSafeIntLib/TestBaseSafeIntLibHost.inf | 2 +- .../BaseSafeIntLib/TestBaseSafeIntLibPei.inf | 4 +- .../BaseSafeIntLib/TestBaseSafeIntLibSmm.inf | 4 +- .../TestBaseSafeIntLibUefiShell.inf | 2 +- .../X64/SafeIntLibUintnIntnUnitTests.c | 2 +- .../Library/CmockaLib/CmockaLib.inf | 2 +- .../Library/CmockaLib/CmockaLib.uni | 2 +- .../Posix/DebugLibPosix/DebugLibPosix.c | 6 +- .../Posix/DebugLibPosix/DebugLibPosix.inf | 2 +- .../MemoryAllocationLibPosix.c | 3 +- .../MemoryAllocationLibPosix.inf | 2 +- .../UnitTestBootLibUsbClass.c | 4 +- .../UnitTestBootLibUsbClass.inf | 3 +- .../Library/UnitTestLib/AssertCmocka.c | 3 +- .../Library/UnitTestLib/Log.c | 1 - .../Library/UnitTestLib/RunTests.c | 2 - .../Library/UnitTestLib/RunTestsCmocka.c | 4 +- .../Library/UnitTestLib/UnitTestLib.c | 7 +- .../Library/UnitTestLib/UnitTestLib.inf | 1 - .../Library/UnitTestLib/UnitTestLibCmocka.inf | 3 +- .../UnitTestPersistenceLibNull.c | 5 +- .../UnitTestPersistenceLibNull.inf | 1 - .../UnitTestPersistenceLibSimpleFileSystem.c | 1 - ...UnitTestPersistenceLibSimpleFileSystem.inf | 1 - .../UnitTestResultReportLib.c | 2 - .../UnitTestResultReportLibConOut.c | 6 +- .../UnitTestResultReportLibConOut.inf | 1 - .../UnitTestResultReportLibDebugLib.c | 6 +- .../UnitTestResultReportLibDebugLib.inf | 1 - .../PrivateInclude/Library/UnitTestBootLib.h | 2 +- .../Library/UnitTestPersistenceLib.h | 2 +- .../Library/UnitTestResultReportLib.h | 2 +- .../PrivateInclude/UnitTestFrameworkTypes.h | 163 ++-- .../Sample/SampleUnitTest/SampleUnitTest.c | 236 ++++-- .../SampleUnitTest/SampleUnitTestDxe.inf | 73 +- .../SampleUnitTest/SampleUnitTestHost.inf | 60 +- .../SampleUnitTest/SampleUnitTestPei.inf | 13 +- .../SampleUnitTest/SampleUnitTestSmm.inf | 15 +- .../SampleUnitTestUefiShell.inf | 16 +- .../Test/UnitTestFrameworkPkgHostTest.dsc | 65 +- UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc | 5 +- .../UnitTestFrameworkPkgHost.dsc.inc | 3 +- .../UnitTestFrameworkPkgTarget.dsc.inc | 3 +- 55 files changed, 1271 insertions(+), 1131 deletions(-) diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c index 8ce13db2749..5f7cedb61bd 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTest.c @@ -1,244 +1,312 @@ -/** @file - Unit tests of the DxeResetSystemLib instance of the ResetSystemLib class - - Copyright (C) Microsoft Corporation. - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include - -#include -#include - -#define UNIT_TEST_APP_NAME "DxeResetSystemLib Unit Tests" -#define UNIT_TEST_APP_VERSION "1.0" - - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - -/** - Resets the entire platform. - - @param[in] ResetType The type of reset to perform. - @param[in] ResetStatus The status code for the reset. - @param[in] DataSize The size, in bytes, of ResetData. - @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or - EfiResetShutdown the data buffer starts with a Null-terminated - string, optionally followed by additional binary data. - The string is a description that the caller may use to further - indicate the reason for the system reset. - For a ResetType of EfiResetPlatformSpecific the data buffer - also starts with a Null-terminated string that is followed - by an EFI_GUID that describes the specific type of reset to perform. -**/ -STATIC -VOID -EFIAPI -MockResetSystem ( - IN EFI_RESET_TYPE ResetType, - IN EFI_STATUS ResetStatus, - IN UINTN DataSize, - IN VOID *ResetData OPTIONAL - ) -{ - check_expected_ptr( ResetType ); - check_expected_ptr( ResetStatus ); - - // NOTE: Mocked functions can also return values, but that - // is for another demo. - - return; -} - -EFI_RUNTIME_SERVICES MockRuntime = { - { - EFI_RUNTIME_SERVICES_SIGNATURE, // Signature - EFI_RUNTIME_SERVICES_REVISION, // Revision - sizeof (EFI_RUNTIME_SERVICES), // HeaderSize - 0, // CRC32 - 0 // Reserved - }, - NULL, // GetTime - NULL, // SetTime - NULL, // GetWakeupTime - NULL, // SetWakeupTime - NULL, // SetVirtualAddressMap - NULL, // ConvertPointer - NULL, // GetVariable - NULL, // GetNextVariableName - NULL, // SetVariable - NULL, // GetNextHighMonotonicCount - MockResetSystem, // ResetSystem - NULL, // UpdateCapsule - NULL, // QueryCapsuleCapabilities - NULL // QueryVariableInfo -}; - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - -UNIT_TEST_STATUS -EFIAPI -ResetColdShouldIssueAColdReset ( - IN UNIT_TEST_CONTEXT Context - ) -{ - expect_value( MockResetSystem, ResetType, EfiResetCold ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetCold(); - - return UNIT_TEST_PASSED; -} // ResetColdShouldIssueAColdReset() - -UNIT_TEST_STATUS -EFIAPI -ResetWarmShouldIssueAWarmReset ( - IN UNIT_TEST_CONTEXT Context - ) -{ - expect_value( MockResetSystem, ResetType, EfiResetWarm ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetWarm(); - - return UNIT_TEST_PASSED; -} // ResetWarmShouldIssueAWarmReset() - -UNIT_TEST_STATUS -EFIAPI -ResetShutdownShouldIssueAShutdown ( - IN UNIT_TEST_CONTEXT Context - ) -{ - expect_value( MockResetSystem, ResetType, EfiResetShutdown ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetShutdown(); - - return UNIT_TEST_PASSED; -} // ResetShutdownShouldIssueAShutdown() - -UNIT_TEST_STATUS -EFIAPI -ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( - IN UNIT_TEST_CONTEXT Context - ) -{ - expect_value( MockResetSystem, ResetType, EfiResetPlatformSpecific ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetPlatformSpecific(0, NULL); - - return UNIT_TEST_PASSED; -} // ResetPlatformSpecificShouldIssueAPlatformSpecificReset() - -UNIT_TEST_STATUS -EFIAPI -ResetSystemShouldPassTheParametersThrough ( - IN UNIT_TEST_CONTEXT Context - ) -{ - expect_value( MockResetSystem, ResetType, EfiResetCold ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); - - expect_value( MockResetSystem, ResetType, EfiResetShutdown ); - expect_value( MockResetSystem, ResetStatus, EFI_SUCCESS ); - - ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL); - - return UNIT_TEST_PASSED; -} // ResetSystemShouldPassTheParametersThrough() - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -STATIC -EFI_STATUS -EFIAPI -UnitTestingEntry () -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE ResetTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); - if (EFI_ERROR( Status )) { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the B64 Encode Unit Test Suite. - // - Status = CreateUnitTestSuite( &ResetTests, Framework, "DxeResetSystemLib Reset Tests", "ResetSystemLib.Reset", NULL, NULL ); - if (EFI_ERROR( Status )){ - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for ResetTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - -// --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- - AddTestCase( ResetTests, "ResetCold should issue a cold reset", "Cold", ResetColdShouldIssueAColdReset, NULL, NULL, NULL); - AddTestCase( ResetTests, "ResetWarm should issue a warm reset", "Warm", ResetWarmShouldIssueAWarmReset, NULL, NULL, NULL); - AddTestCase( ResetTests, "ResetShutdown should issue a shutdown", "Shutdown", ResetShutdownShouldIssueAShutdown, NULL, NULL, NULL); - AddTestCase( ResetTests, "ResetPlatformSpecific should issue a platform-specific reset", "Platform", ResetPlatformSpecificShouldIssueAPlatformSpecificReset, NULL, NULL, NULL); - AddTestCase( ResetTests, "ResetSystem should pass all parameters through", "Parameters", ResetSystemShouldPassTheParametersThrough, NULL, NULL, NULL); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Framework ); - -EXIT: - if (Framework) { - FreeUnitTestFramework( Framework ); - } - - return Status; -} - -int -main ( - int argc, - char *argv[] - ) -{ - return UnitTestingEntry(); -} +/** @file + Unit tests of the DxeResetSystemLib instance of the ResetSystemLib class + + Copyright (C) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#include +#include +#include +#include +#include + +#include +#include + +#define UNIT_TEST_APP_NAME "DxeResetSystemLib Unit Tests" +#define UNIT_TEST_APP_VERSION "1.0" + +/** + Resets the entire platform. + + @param[in] ResetType The type of reset to perform. + @param[in] ResetStatus The status code for the reset. + @param[in] DataSize The size, in bytes, of ResetData. + @param[in] ResetData For a ResetType of EfiResetCold, EfiResetWarm, or + EfiResetShutdown the data buffer starts with a Null-terminated + string, optionally followed by additional binary data. + The string is a description that the caller may use to further + indicate the reason for the system reset. + For a ResetType of EfiResetPlatformSpecific the data buffer + also starts with a Null-terminated string that is followed + by an EFI_GUID that describes the specific type of reset to perform. +**/ +STATIC +VOID +EFIAPI +MockResetSystem ( + IN EFI_RESET_TYPE ResetType, + IN EFI_STATUS ResetStatus, + IN UINTN DataSize, + IN VOID *ResetData OPTIONAL + ) +{ + check_expected_ptr (ResetType); + check_expected_ptr (ResetStatus); + + // + // NOTE: Mocked functions can also return values, but that + // is for another demo. +} + +/// +/// Mock version of the UEFI Runtime Services Table +/// +EFI_RUNTIME_SERVICES MockRuntime = { + { + EFI_RUNTIME_SERVICES_SIGNATURE, // Signature + EFI_RUNTIME_SERVICES_REVISION, // Revision + sizeof (EFI_RUNTIME_SERVICES), // HeaderSize + 0, // CRC32 + 0 // Reserved + }, + NULL, // GetTime + NULL, // SetTime + NULL, // GetWakeupTime + NULL, // SetWakeupTime + NULL, // SetVirtualAddressMap + NULL, // ConvertPointer + NULL, // GetVariable + NULL, // GetNextVariableName + NULL, // SetVariable + NULL, // GetNextHighMonotonicCount + MockResetSystem, // ResetSystem + NULL, // UpdateCapsule + NULL, // QueryCapsuleCapabilities + NULL // QueryVariableInfo +}; + +/** + Unit test for ColdReset () API of the ResetSystemLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +ResetColdShouldIssueAColdReset ( + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value (MockResetSystem, ResetType, EfiResetCold); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetCold (); + + return UNIT_TEST_PASSED; +} + +/** + Unit test for WarmReset () API of the ResetSystemLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +ResetWarmShouldIssueAWarmReset ( + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value (MockResetSystem, ResetType, EfiResetWarm); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetWarm (); + + return UNIT_TEST_PASSED; +} + +/** + Unit test for ResetShutdown () API of the ResetSystemLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +ResetShutdownShouldIssueAShutdown ( + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value (MockResetSystem, ResetType, EfiResetShutdown); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetShutdown (); + + return UNIT_TEST_PASSED; +} + +/** + Unit test for ResetPlatformSpecific () API of the ResetSystemLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +ResetPlatformSpecificShouldIssueAPlatformSpecificReset ( + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value (MockResetSystem, ResetType, EfiResetPlatformSpecific); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetPlatformSpecific (0, NULL); + + return UNIT_TEST_PASSED; +} + +/** + Unit test for ResetSystem () API of the ResetSystemLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +UNIT_TEST_STATUS +EFIAPI +ResetSystemShouldPassTheParametersThrough ( + IN UNIT_TEST_CONTEXT Context + ) +{ + expect_value (MockResetSystem, ResetType, EfiResetCold); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetSystem (EfiResetCold, EFI_SUCCESS, 0, NULL); + + expect_value (MockResetSystem, ResetType, EfiResetShutdown); + expect_value (MockResetSystem, ResetStatus, EFI_SUCCESS); + + ResetSystem (EfiResetShutdown, EFI_SUCCESS, 0, NULL); + + return UNIT_TEST_PASSED; +} + +/** + Initialze the unit test framework, suite, and unit tests for the + ResetSystemLib and run the ResetSystemLib unit test. + + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit tests. +**/ +STATIC +EFI_STATUS +EFIAPI +UnitTestingEntry ( + VOID + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_SUITE_HANDLE ResetTests; + + Framework = NULL; + + DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Framework, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the ResetSytemLib Unit Test Suite. + // + Status = CreateUnitTestSuite (&ResetTests, Framework, "DxeResetSystemLib Reset Tests", "ResetSystemLib.Reset", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for ResetTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + + // + // --------------Suite-----------Description--------------Name----------Function--------Pre---Post-------------------Context----------- + // + AddTestCase (ResetTests, "ResetCold should issue a cold reset", "Cold", ResetColdShouldIssueAColdReset, NULL, NULL, NULL); + AddTestCase (ResetTests, "ResetWarm should issue a warm reset", "Warm", ResetWarmShouldIssueAWarmReset, NULL, NULL, NULL); + AddTestCase (ResetTests, "ResetShutdown should issue a shutdown", "Shutdown", ResetShutdownShouldIssueAShutdown, NULL, NULL, NULL); + AddTestCase (ResetTests, "ResetPlatformSpecific should issue a platform-specific reset", "Platform", ResetPlatformSpecificShouldIssueAPlatformSpecificReset, NULL, NULL, NULL); + AddTestCase (ResetTests, "ResetSystem should pass all parameters through", "Parameters", ResetSystemShouldPassTheParametersThrough, NULL, NULL, NULL); + + // + // Execute the tests. + // + Status = RunAllTestSuites (Framework); + +EXIT: + if (Framework) { + FreeUnitTestFramework (Framework); + } + + return Status; +} + +/** + Standard POSIX C entry point for host based unit test execution. +**/ +int +main ( + int argc, + char *argv[] + ) +{ + return UnitTestingEntry (); +} diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf index f3014c22682..54f968e810f 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf @@ -1,32 +1,34 @@ -## @file -# Copyright (C) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = DxeResetSystemLibUnitTestHost - FILE_GUID = 83E35653-B943-4C5F-BA08-9B2996AE9273 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - DxeResetSystemLibUnitTest.c - -[Packages] - MdePkg/MdePkg.dec - MdeModulePkg/MdeModulePkg.dec - UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec - -[LibraryClasses] - ResetSystemLib - BaseLib - BaseMemoryLib - DebugLib - UnitTestLib +## @file +# Unit tests of the DxeResetSystemLib instance of the ResetSystemLib class +# +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = DxeResetSystemLibUnitTestHost + FILE_GUID = 83E35653-B943-4C5F-BA08-9B2996AE9273 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + DxeResetSystemLibUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + MdeModulePkg/MdeModulePkg.dec + UnitTestFrameworkPkg/UnitTestFrameworkPkg.dec + +[LibraryClasses] + ResetSystemLib + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib diff --git a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c index 59ea6a8b49b..3540e1c039f 100644 --- a/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c +++ b/MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.c @@ -1,13 +1,13 @@ -/** @file - Mock implementation of the UEFI Runtime Services Table Library. - - Copyright (C) Microsoft Corporation. - SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include - -extern EFI_RUNTIME_SERVICES MockRuntime; - -EFI_RUNTIME_SERVICES *gRT = &MockRuntime; +/** @file + Mock implementation of the UEFI Runtime Services Table Library. + + Copyright (C) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include + +extern EFI_RUNTIME_SERVICES MockRuntime; + +EFI_RUNTIME_SERVICES *gRT = &MockRuntime; diff --git a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc index 4fbb21201c0..72a119db456 100644 --- a/MdeModulePkg/Test/MdeModulePkgHostTest.dsc +++ b/MdeModulePkg/Test/MdeModulePkgHostTest.dsc @@ -1,31 +1,32 @@ -## @file -# -# Copyright (c) 2019, Intel Corporation. All rights reserved.
-# Copyright (C) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - PLATFORM_NAME = MdeModulePkgHostTest - PLATFORM_GUID = F74AF7C6-698C-4EBA-BA49-FF6816916354 - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/MdeModulePkg/HostTest - SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT - -!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc - -[Components] - MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf - - # - # Build MdeModulePkg HOST_APPLICATION Tests - # - MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf { - - ResetSystemLib|MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf - UefiRuntimeServicesTableLib|MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf - } +## @file +# MdeModulePkg DSC file used to build host-based unit tests. +# +# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
+# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = MdeModulePkgHostTest + PLATFORM_GUID = F74AF7C6-698C-4EBA-BA49-FF6816916354 + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/MdeModulePkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[Components] + MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf + + # + # Build MdeModulePkg HOST_APPLICATION Tests + # + MdeModulePkg/Library/DxeResetSystemLib/UnitTest/DxeResetSystemLibUnitTestHost.inf { + + ResetSystemLib|MdeModulePkg/Library/DxeResetSystemLib/DxeResetSystemLib.inf + UefiRuntimeServicesTableLib|MdeModulePkg/Library/DxeResetSystemLib/UnitTest/MockUefiRuntimeServicesTableLib.inf + } diff --git a/MdePkg/Test/MdePkgHostTest.dsc b/MdePkg/Test/MdePkgHostTest.dsc index 453a8288d9a..3d677ee75ce 100644 --- a/MdePkg/Test/MdePkgHostTest.dsc +++ b/MdePkg/Test/MdePkgHostTest.dsc @@ -1,6 +1,7 @@ ## @file +# MdePkg DSC file used to build host-based unit tests. # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# Copyright (C) Microsoft Corporation. # SPDX-License-Identifier: BSD-2-Clause-Patent # diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c index a8fb511a314..0ad078155cd 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c +++ b/MdePkg/Test/UnitTest/Library/BaseLib/Base64UnitTest.c @@ -1,384 +1,404 @@ -/** @file -Base64UnitTest.c - -Unit Test for Base64 conversion routines. - -Copyright (C) Microsoft Corporation. -SPDX-License-Identifier: BSD-2-Clause-Patent - -**/ - -#include -#include -#include -#include -#include -#include - -#define UNIT_TEST_APP_NAME "BaseLib Unit Test Application" -#define UNIT_TEST_APP_VERSION "1.0" - -/** -RFC 4648 https://tools.ietf.org/html/rfc4648 test vectors - - BASE64("") = "" - BASE64("f") = "Zg==" - BASE64("fo") = "Zm8=" - BASE64("foo") = "Zm9v" - BASE64("foob") = "Zm9vYg==" - BASE64("fooba") = "Zm9vYmE=" - BASE64("foobar") = "Zm9vYmFy" - - The test vectors are using ascii strings for the binary data - */ - -typedef struct { - CHAR8 *TestInput; - CHAR8 *TestOutput; - EFI_STATUS ExpectedStatus; - VOID *BufferToFree; - UINTN ExpectedSize; -} BASIC_TEST_CONTEXT; - - -#define B64_TEST_1 "" -#define BIN_TEST_1 "" - -#define B64_TEST_2 "Zg==" -#define BIN_TEST_2 "f" - -#define B64_TEST_3 "Zm8=" -#define BIN_TEST_3 "fo" - -#define B64_TEST_4 "Zm9v" -#define BIN_TEST_4 "foo" - -#define B64_TEST_5 "Zm9vYg==" -#define BIN_TEST_5 "foob" - -#define B64_TEST_6 "Zm9vYmE=" -#define BIN_TEST_6 "fooba" - -#define B64_TEST_7 "Zm9vYmFy" -#define BIN_TEST_7 "foobar" - -// Adds all white space - also ends the last quantum with only spaces afterwards -#define B64_TEST_8_IN " \t\v Zm9\r\nvYmFy \f " -#define BIN_TEST_8 "foobar" - -// Not a quantum multiple of 4 -#define B64_ERROR_1 "Zm9vymFy=" - -// Invalid characters in the string -#define B64_ERROR_2 "Zm$vymFy" - -// Too many '=' characters -#define B64_ERROR_3 "Z===" - -// Poorly placed '=' -#define B64_ERROR_4 "Zm=vYmFy" - -#define MAX_TEST_STRING_SIZE (200) -// ------------------------------------------------ Input----------Output-----------Result-------Free--Expected Output Size -static BASIC_TEST_CONTEXT mBasicEncodeTest1 = {BIN_TEST_1, B64_TEST_1, EFI_SUCCESS, NULL, sizeof(B64_TEST_1)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest2 = {BIN_TEST_2, B64_TEST_2, EFI_SUCCESS, NULL, sizeof(B64_TEST_2)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest3 = {BIN_TEST_3, B64_TEST_3, EFI_SUCCESS, NULL, sizeof(B64_TEST_3)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest4 = {BIN_TEST_4, B64_TEST_4, EFI_SUCCESS, NULL, sizeof(B64_TEST_4)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest5 = {BIN_TEST_5, B64_TEST_5, EFI_SUCCESS, NULL, sizeof(B64_TEST_5)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest6 = {BIN_TEST_6, B64_TEST_6, EFI_SUCCESS, NULL, sizeof(B64_TEST_6)}; -static BASIC_TEST_CONTEXT mBasicEncodeTest7 = {BIN_TEST_7, B64_TEST_7, EFI_SUCCESS, NULL, sizeof(B64_TEST_7)}; -static BASIC_TEST_CONTEXT mBasicEncodeError1 = {BIN_TEST_7, B64_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(B64_TEST_7)}; - -static BASIC_TEST_CONTEXT mBasicDecodeTest1 = {B64_TEST_1, BIN_TEST_1, EFI_SUCCESS, NULL, sizeof(BIN_TEST_1)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest2 = {B64_TEST_2, BIN_TEST_2, EFI_SUCCESS, NULL, sizeof(BIN_TEST_2)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest3 = {B64_TEST_3, BIN_TEST_3, EFI_SUCCESS, NULL, sizeof(BIN_TEST_3)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest4 = {B64_TEST_4, BIN_TEST_4, EFI_SUCCESS, NULL, sizeof(BIN_TEST_4)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest5 = {B64_TEST_5, BIN_TEST_5, EFI_SUCCESS, NULL, sizeof(BIN_TEST_5)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest6 = {B64_TEST_6, BIN_TEST_6, EFI_SUCCESS, NULL, sizeof(BIN_TEST_6)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest7 = {B64_TEST_7, BIN_TEST_7, EFI_SUCCESS, NULL, sizeof(BIN_TEST_7)-1}; -static BASIC_TEST_CONTEXT mBasicDecodeTest8 = {B64_TEST_8_IN, BIN_TEST_8, EFI_SUCCESS, NULL, sizeof(BIN_TEST_8)-1}; - -static BASIC_TEST_CONTEXT mBasicDecodeError1 = {B64_ERROR_1, B64_ERROR_1, EFI_INVALID_PARAMETER, NULL, 0}; -static BASIC_TEST_CONTEXT mBasicDecodeError2 = {B64_ERROR_2, B64_ERROR_2, EFI_INVALID_PARAMETER, NULL, 0}; -static BASIC_TEST_CONTEXT mBasicDecodeError3 = {B64_ERROR_3, B64_ERROR_3, EFI_INVALID_PARAMETER, NULL, 0}; -static BASIC_TEST_CONTEXT mBasicDecodeError4 = {B64_ERROR_4, B64_ERROR_4, EFI_INVALID_PARAMETER, NULL, 0}; -static BASIC_TEST_CONTEXT mBasicDecodeError5 = {B64_TEST_7, BIN_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(BIN_TEST_7)-1}; - -///================================================================================================ -///================================================================================================ -/// -/// HELPER FUNCTIONS -/// -///================================================================================================ -///================================================================================================ - -/** -Simple clean up method to make sure tests clean up even if interrupted and fail in the middle. -**/ -STATIC -VOID -EFIAPI -CleanUpB64TestContext ( - IN UNIT_TEST_CONTEXT Context - ) { - - BASIC_TEST_CONTEXT *Btc; - - - Btc = (BASIC_TEST_CONTEXT *) Context; - if (Btc != NULL) { - //free string if set - if (Btc->BufferToFree != NULL) - { - FreePool(Btc->BufferToFree); - Btc->BufferToFree = NULL; - } - } -} - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ -static -UNIT_TEST_STATUS -EFIAPI -RfcEncodeTest( - IN UNIT_TEST_CONTEXT Context - ) { - - BASIC_TEST_CONTEXT *Btc; - CHAR8 *b64String; - CHAR8 *binString; - UINTN b64StringSize; - EFI_STATUS Status; - UINT8 *BinData; - UINTN BinSize; - CHAR8 *b64WorkString; - UINTN ReturnSize; - INTN CompareStatus; - UINTN indx; - - - Btc = (BASIC_TEST_CONTEXT *) Context; - binString = Btc->TestInput; - b64String = Btc->TestOutput; - - // - // Only testing the the translate functionality, so - // preallocate the proper string buffer - - b64StringSize = AsciiStrnSizeS(b64String, MAX_TEST_STRING_SIZE); - BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); - BinData = (UINT8 *) binString; - - b64WorkString = (CHAR8 *) AllocatePool(b64StringSize); - UT_ASSERT_NOT_NULL(b64WorkString); - - Btc->BufferToFree = b64WorkString; - ReturnSize = b64StringSize; - - Status = Base64Encode(BinData, BinSize, b64WorkString, &ReturnSize); - - UT_ASSERT_STATUS_EQUAL(Status, Btc->ExpectedStatus); - - UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); - - if (! EFI_ERROR(Btc->ExpectedStatus)) { - if (ReturnSize != 0) { - CompareStatus = AsciiStrnCmp(b64String, b64WorkString, ReturnSize); - if (CompareStatus != 0) { - UT_LOG_ERROR("b64 string compare error - size=%d\n",ReturnSize); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & b64String[indx]); - } - UT_LOG_ERROR("\n b64 work string:\n"); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & b64WorkString[indx]); - } - UT_LOG_ERROR("\n"); - } - UT_ASSERT_EQUAL(CompareStatus, 0); - } - } - - Btc->BufferToFree = NULL; - FreePool (b64WorkString); - return UNIT_TEST_PASSED; -} - -static -UNIT_TEST_STATUS -EFIAPI -RfcDecodeTest( - IN UNIT_TEST_CONTEXT Context - ) { - - BASIC_TEST_CONTEXT *Btc; - CHAR8 *b64String; - CHAR8 *binString; - EFI_STATUS Status; - UINTN b64StringLen; - UINTN ReturnSize; - UINT8 *BinData; - UINTN BinSize; - INTN CompareStatus; - UINTN indx; - - - Btc = (BASIC_TEST_CONTEXT *) Context; - b64String = Btc->TestInput; - binString = Btc->TestOutput; - - // - // Only testing the the translate functionality - // - - b64StringLen = AsciiStrnLenS(b64String, MAX_TEST_STRING_SIZE); - BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); - - BinData = AllocatePool (BinSize); - Btc->BufferToFree = BinData; - - ReturnSize = BinSize; - Status = Base64Decode(b64String, b64StringLen, BinData, &ReturnSize); - - UT_ASSERT_STATUS_EQUAL(Status, Btc->ExpectedStatus); - - // If an error is not expected, check the results - if (EFI_ERROR(Btc->ExpectedStatus)) { - if (Btc->ExpectedStatus == EFI_BUFFER_TOO_SMALL) { - UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); - } - } else { - UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); - if (ReturnSize != 0) { - CompareStatus = CompareMem(binString, BinData, ReturnSize); - if (CompareStatus != 0) { - UT_LOG_ERROR("bin string compare error - size=%d\n", ReturnSize); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & binString[indx]); - } - UT_LOG_ERROR("\nBinData:\n"); - for (indx = 0; indx < ReturnSize; indx++) { - UT_LOG_ERROR(" %2.2x", 0xff & BinData[indx]); - } - UT_LOG_ERROR("\n"); - } - UT_ASSERT_EQUAL(CompareStatus, 0); - } - } - - Btc->BufferToFree = NULL; - FreePool (BinData); - return UNIT_TEST_PASSED; -} - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - - -STATIC -EFI_STATUS -EFIAPI -UnitTestingEntry () -{ - EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Fw = NULL; - UNIT_TEST_SUITE_HANDLE b64EncodeTests; - UNIT_TEST_SUITE_HANDLE b64DecodeTests; - - DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION )); - - // - // Start setting up the test framework for running the tests. - // - Status = InitUnitTestFramework( &Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION ); - if (EFI_ERROR( Status )) { - DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); - goto EXIT; - } - - // - // Populate the B64 Encode Unit Test Suite. - // - Status = CreateUnitTestSuite( &b64EncodeTests, Fw, "b64 Encode binary to Ascii string", "BaseLib.b64Encode", NULL, NULL ); - if (EFI_ERROR( Status )){ - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64EncodeTests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - -// --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest1); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - f", "Test2", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest2); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest3); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest4); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest5); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest6); - AddTestCase( b64EncodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest7); - AddTestCase( b64EncodeTests, "Too small of output buffer", "Error1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeError1); - // - // Populate the B64 Decode Unit Test Suite. - // - Status = CreateUnitTestSuite( &b64DecodeTests, Fw, "b64 Decode Ascii string to binary", "BaseLib.b64Decode", NULL, NULL ); - if (EFI_ERROR( Status )) { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64Decode Tests\n")); - Status = EFI_OUT_OF_RESOURCES; - goto EXIT; - } - - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest1 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - f", "Test2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest2 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest3 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest4 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest5 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest6 ); - AddTestCase(b64DecodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest7 ); - AddTestCase(b64DecodeTests, "Ignore Whitespace test", "Test8", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest8 ); - - AddTestCase(b64DecodeTests, "Not a quantum multiple of 4", "Error1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError1 ); - AddTestCase(b64DecodeTests, "Invalid characters in the string", "Error2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError2 ); - AddTestCase(b64DecodeTests, "Too many padding characters", "Error3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError3 ); - AddTestCase(b64DecodeTests, "Incorrectly placed padding character", "Error4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError4 ); - AddTestCase(b64DecodeTests, "Too small of output buffer", "Error5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError5 ); - - // - // Execute the tests. - // - Status = RunAllTestSuites( Fw ); - -EXIT: - if (Fw) { - FreeUnitTestFramework( Fw ); - } - - return Status; -} - -EFI_STATUS -EFIAPI -BaseLibUnitTestAppEntry ( - IN EFI_HANDLE ImageHandle, - IN EFI_SYSTEM_TABLE *SystemTable - ) - { - return UnitTestingEntry(); - } - -int -main ( - int argc, - char *argv[] - ) -{ - return UnitTestingEntry(); -} +/** @file + Unit tests of Base64 conversion APIs in BaseLib. + + Copyright (C) Microsoft Corporation. + SPDX-License-Identifier: BSD-2-Clause-Patent + +**/ + +#include +#include +#include +#include +#include +#include + +#define UNIT_TEST_APP_NAME "BaseLib Unit Test Application" +#define UNIT_TEST_APP_VERSION "1.0" + +/** + RFC 4648 https://tools.ietf.org/html/rfc4648 test vectors + + BASE64("") = "" + BASE64("f") = "Zg==" + BASE64("fo") = "Zm8=" + BASE64("foo") = "Zm9v" + BASE64("foob") = "Zm9vYg==" + BASE64("fooba") = "Zm9vYmE=" + BASE64("foobar") = "Zm9vYmFy" + + The test vectors are using ascii strings for the binary data + */ + +typedef struct { + CHAR8 *TestInput; + CHAR8 *TestOutput; + EFI_STATUS ExpectedStatus; + VOID *BufferToFree; + UINTN ExpectedSize; +} BASIC_TEST_CONTEXT; + +#define B64_TEST_1 "" +#define BIN_TEST_1 "" + +#define B64_TEST_2 "Zg==" +#define BIN_TEST_2 "f" + +#define B64_TEST_3 "Zm8=" +#define BIN_TEST_3 "fo" + +#define B64_TEST_4 "Zm9v" +#define BIN_TEST_4 "foo" + +#define B64_TEST_5 "Zm9vYg==" +#define BIN_TEST_5 "foob" + +#define B64_TEST_6 "Zm9vYmE=" +#define BIN_TEST_6 "fooba" + +#define B64_TEST_7 "Zm9vYmFy" +#define BIN_TEST_7 "foobar" + +// Adds all white space - also ends the last quantum with only spaces afterwards +#define B64_TEST_8_IN " \t\v Zm9\r\nvYmFy \f " +#define BIN_TEST_8 "foobar" + +// Not a quantum multiple of 4 +#define B64_ERROR_1 "Zm9vymFy=" + +// Invalid characters in the string +#define B64_ERROR_2 "Zm$vymFy" + +// Too many '=' characters +#define B64_ERROR_3 "Z===" + +// Poorly placed '=' +#define B64_ERROR_4 "Zm=vYmFy" + +#define MAX_TEST_STRING_SIZE (200) + +// ------------------------------------------------ Input----------Output-----------Result-------Free--Expected Output Size +static BASIC_TEST_CONTEXT mBasicEncodeTest1 = {BIN_TEST_1, B64_TEST_1, EFI_SUCCESS, NULL, sizeof(B64_TEST_1)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest2 = {BIN_TEST_2, B64_TEST_2, EFI_SUCCESS, NULL, sizeof(B64_TEST_2)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest3 = {BIN_TEST_3, B64_TEST_3, EFI_SUCCESS, NULL, sizeof(B64_TEST_3)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest4 = {BIN_TEST_4, B64_TEST_4, EFI_SUCCESS, NULL, sizeof(B64_TEST_4)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest5 = {BIN_TEST_5, B64_TEST_5, EFI_SUCCESS, NULL, sizeof(B64_TEST_5)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest6 = {BIN_TEST_6, B64_TEST_6, EFI_SUCCESS, NULL, sizeof(B64_TEST_6)}; +static BASIC_TEST_CONTEXT mBasicEncodeTest7 = {BIN_TEST_7, B64_TEST_7, EFI_SUCCESS, NULL, sizeof(B64_TEST_7)}; +static BASIC_TEST_CONTEXT mBasicEncodeError1 = {BIN_TEST_7, B64_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(B64_TEST_7)}; + +static BASIC_TEST_CONTEXT mBasicDecodeTest1 = {B64_TEST_1, BIN_TEST_1, EFI_SUCCESS, NULL, sizeof(BIN_TEST_1)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest2 = {B64_TEST_2, BIN_TEST_2, EFI_SUCCESS, NULL, sizeof(BIN_TEST_2)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest3 = {B64_TEST_3, BIN_TEST_3, EFI_SUCCESS, NULL, sizeof(BIN_TEST_3)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest4 = {B64_TEST_4, BIN_TEST_4, EFI_SUCCESS, NULL, sizeof(BIN_TEST_4)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest5 = {B64_TEST_5, BIN_TEST_5, EFI_SUCCESS, NULL, sizeof(BIN_TEST_5)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest6 = {B64_TEST_6, BIN_TEST_6, EFI_SUCCESS, NULL, sizeof(BIN_TEST_6)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest7 = {B64_TEST_7, BIN_TEST_7, EFI_SUCCESS, NULL, sizeof(BIN_TEST_7)-1}; +static BASIC_TEST_CONTEXT mBasicDecodeTest8 = {B64_TEST_8_IN, BIN_TEST_8, EFI_SUCCESS, NULL, sizeof(BIN_TEST_8)-1}; + +static BASIC_TEST_CONTEXT mBasicDecodeError1 = {B64_ERROR_1, B64_ERROR_1, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError2 = {B64_ERROR_2, B64_ERROR_2, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError3 = {B64_ERROR_3, B64_ERROR_3, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError4 = {B64_ERROR_4, B64_ERROR_4, EFI_INVALID_PARAMETER, NULL, 0}; +static BASIC_TEST_CONTEXT mBasicDecodeError5 = {B64_TEST_7, BIN_TEST_1, EFI_BUFFER_TOO_SMALL, NULL, sizeof(BIN_TEST_7)-1}; + +/** + Simple clean up method to make sure tests clean up even if interrupted and fail + in the middle. +**/ +STATIC +VOID +EFIAPI +CleanUpB64TestContext ( + IN UNIT_TEST_CONTEXT Context + ) +{ + BASIC_TEST_CONTEXT *Btc; + + Btc = (BASIC_TEST_CONTEXT *)Context; + if (Btc != NULL) { + //free string if set + if (Btc->BufferToFree != NULL) { + FreePool (Btc->BufferToFree); + Btc->BufferToFree = NULL; + } + } +} + +/** + Unit test for Base64 encode APIs of BaseLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +STATIC +UNIT_TEST_STATUS +EFIAPI +RfcEncodeTest ( + IN UNIT_TEST_CONTEXT Context + ) +{ + BASIC_TEST_CONTEXT *Btc; + CHAR8 *b64String; + CHAR8 *binString; + UINTN b64StringSize; + EFI_STATUS Status; + UINT8 *BinData; + UINTN BinSize; + CHAR8 *b64WorkString; + UINTN ReturnSize; + INTN CompareStatus; + UINTN indx; + + Btc = (BASIC_TEST_CONTEXT *) Context; + binString = Btc->TestInput; + b64String = Btc->TestOutput; + + // + // Only testing the the translate functionality, so preallocate the proper + // string buffer. + // + + b64StringSize = AsciiStrnSizeS(b64String, MAX_TEST_STRING_SIZE); + BinSize = AsciiStrnLenS(binString, MAX_TEST_STRING_SIZE); + BinData = (UINT8 *) binString; + + b64WorkString = (CHAR8 *) AllocatePool(b64StringSize); + UT_ASSERT_NOT_NULL(b64WorkString); + + Btc->BufferToFree = b64WorkString; + ReturnSize = b64StringSize; + + Status = Base64Encode(BinData, BinSize, b64WorkString, &ReturnSize); + + UT_ASSERT_STATUS_EQUAL(Status, Btc->ExpectedStatus); + + UT_ASSERT_EQUAL(ReturnSize, Btc->ExpectedSize); + + if (!EFI_ERROR (Btc->ExpectedStatus)) { + if (ReturnSize != 0) { + CompareStatus = AsciiStrnCmp (b64String, b64WorkString, ReturnSize); + if (CompareStatus != 0) { + UT_LOG_ERROR ("b64 string compare error - size=%d\n", ReturnSize); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR (" %2.2x", 0xff & b64String[indx]); + } + UT_LOG_ERROR ("\n b64 work string:\n"); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR (" %2.2x", 0xff & b64WorkString[indx]); + } + UT_LOG_ERROR ("\n"); + } + UT_ASSERT_EQUAL (CompareStatus, 0); + } + } + + Btc->BufferToFree = NULL; + FreePool (b64WorkString); + return UNIT_TEST_PASSED; +} + +/** + Unit test for Base64 decode APIs of BaseLib. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ +STATIC +UNIT_TEST_STATUS +EFIAPI +RfcDecodeTest( + IN UNIT_TEST_CONTEXT Context + ) +{ + BASIC_TEST_CONTEXT *Btc; + CHAR8 *b64String; + CHAR8 *binString; + EFI_STATUS Status; + UINTN b64StringLen; + UINTN ReturnSize; + UINT8 *BinData; + UINTN BinSize; + INTN CompareStatus; + UINTN indx; + + Btc = (BASIC_TEST_CONTEXT *)Context; + b64String = Btc->TestInput; + binString = Btc->TestOutput; + + // + // Only testing the the translate functionality + // + + b64StringLen = AsciiStrnLenS (b64String, MAX_TEST_STRING_SIZE); + BinSize = AsciiStrnLenS (binString, MAX_TEST_STRING_SIZE); + + BinData = AllocatePool (BinSize); + Btc->BufferToFree = BinData; + + ReturnSize = BinSize; + Status = Base64Decode (b64String, b64StringLen, BinData, &ReturnSize); + + UT_ASSERT_STATUS_EQUAL (Status, Btc->ExpectedStatus); + + // If an error is not expected, check the results + if (EFI_ERROR (Btc->ExpectedStatus)) { + if (Btc->ExpectedStatus == EFI_BUFFER_TOO_SMALL) { + UT_ASSERT_EQUAL (ReturnSize, Btc->ExpectedSize); + } + } else { + UT_ASSERT_EQUAL (ReturnSize, Btc->ExpectedSize); + if (ReturnSize != 0) { + CompareStatus = CompareMem (binString, BinData, ReturnSize); + if (CompareStatus != 0) { + UT_LOG_ERROR ("bin string compare error - size=%d\n", ReturnSize); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR (" %2.2x", 0xff & binString[indx]); + } + UT_LOG_ERROR ("\nBinData:\n"); + for (indx = 0; indx < ReturnSize; indx++) { + UT_LOG_ERROR (" %2.2x", 0xff & BinData[indx]); + } + UT_LOG_ERROR ("\n"); + } + UT_ASSERT_EQUAL (CompareStatus, 0); + } + } + + Btc->BufferToFree = NULL; + FreePool (BinData); + return UNIT_TEST_PASSED; +} + +/** + Initialze the unit test framework, suite, and unit tests for the + Base64 conversion APIs of BaseLib and run the unit tests. + + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit tests. +**/ +STATIC +EFI_STATUS +EFIAPI +UnitTestingEntry ( + VOID + ) +{ + EFI_STATUS Status; + UNIT_TEST_FRAMEWORK_HANDLE Fw; + UNIT_TEST_SUITE_HANDLE b64EncodeTests; + UNIT_TEST_SUITE_HANDLE b64DecodeTests; + + Fw = NULL; + + DEBUG ((DEBUG_INFO, "%a v%a\n", UNIT_TEST_APP_NAME, UNIT_TEST_APP_VERSION)); + + // + // Start setting up the test framework for running the tests. + // + Status = InitUnitTestFramework (&Fw, UNIT_TEST_APP_NAME, gEfiCallerBaseName, UNIT_TEST_APP_VERSION); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); + goto EXIT; + } + + // + // Populate the B64 Encode Unit Test Suite. + // + Status = CreateUnitTestSuite (&b64EncodeTests, Fw, "b64 Encode binary to Ascii string", "BaseLib.b64Encode", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64EncodeTests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + + // --------------Suite-----------Description--------------Class Name----------Function--------Pre---Post-------------------Context----------- + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest1); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - f", "Test2", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest2); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest3); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest4); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest5); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest6); + AddTestCase (b64EncodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeTest7); + AddTestCase (b64EncodeTests, "Too small of output buffer", "Error1", RfcEncodeTest, NULL, CleanUpB64TestContext, &mBasicEncodeError1); + // + // Populate the B64 Decode Unit Test Suite. + // + Status = CreateUnitTestSuite (&b64DecodeTests, Fw, "b64 Decode Ascii string to binary", "BaseLib.b64Decode", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for b64Decode Tests\n")); + Status = EFI_OUT_OF_RESOURCES; + goto EXIT; + } + + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - Empty", "Test1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest1); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - f", "Test2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest2); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - fo", "Test3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest3); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - foo", "Test4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest4); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - foob", "Test5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest5); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - fooba", "Test6", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest6); + AddTestCase (b64DecodeTests, "RFC 4686 Test Vector - foobar", "Test7", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest7); + AddTestCase (b64DecodeTests, "Ignore Whitespace test", "Test8", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeTest8); + + AddTestCase (b64DecodeTests, "Not a quantum multiple of 4", "Error1", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError1); + AddTestCase (b64DecodeTests, "Invalid characters in the string", "Error2", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError2); + AddTestCase (b64DecodeTests, "Too many padding characters", "Error3", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError3); + AddTestCase (b64DecodeTests, "Incorrectly placed padding character", "Error4", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError4); + AddTestCase (b64DecodeTests, "Too small of output buffer", "Error5", RfcDecodeTest, NULL, CleanUpB64TestContext, &mBasicDecodeError5); + + // + // Execute the tests. + // + Status = RunAllTestSuites (Fw); + +EXIT: + if (Fw) { + FreeUnitTestFramework (Fw); + } + + return Status; +} + +/** + Standard UEFI entry point for target based unit test execution from UEFI Shell. +**/ +EFI_STATUS +EFIAPI +BaseLibUnitTestAppEntry ( + IN EFI_HANDLE ImageHandle, + IN EFI_SYSTEM_TABLE *SystemTable + ) +{ + return UnitTestingEntry (); +} + +/** + Standard POSIX C entry point for host based unit test execution. +**/ +int +main ( + int argc, + char *argv[] + ) +{ + return UnitTestingEntry (); +} diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf index 2dbd3effb87..b31afae6332 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf +++ b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsHost.inf @@ -1,39 +1,32 @@ -## @file -# Copyright (C) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = BaseLibUnitTestsHost - FILE_GUID = 1d005f4c-4dfa-41b5-ab0c-be91fe121459 - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - Base64UnitTest.c - -[Packages] - MdePkg/MdePkg.dec - -[Protocols] - - -[LibraryClasses] - BaseLib - BaseMemoryLib - DebugLib - UnitTestLib - -[Guids] - - - - +## @file +# Unit tests of Base64 conversion APIs in BaseLib that are run from host +# environment. +# +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseLibUnitTestsHost + FILE_GUID = 1d005f4c-4dfa-41b5-ab0c-be91fe121459 + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Base64UnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + DebugLib + UnitTestLib diff --git a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf index 9a2856ec30e..907503898a6 100644 --- a/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf +++ b/MdePkg/Test/UnitTest/Library/BaseLib/BaseLibUnitTestsUefi.inf @@ -1,41 +1,33 @@ -## @file -# Copyright (C) Microsoft Corporation. -# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = BaseLibUnitTestsUefi - FILE_GUID = df5a6fed-8786-4a9d-9d02-eab39497b4a1 - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = BaseLibUnitTestAppEntry - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - Base64UnitTest.c - -[Packages] - MdePkg/MdePkg.dec - -[Protocols] - - -[LibraryClasses] - BaseLib - BaseMemoryLib - UefiApplicationEntryPoint - DebugLib - UnitTestLib - -[Guids] - - - - +## @file +# Unit tests of Base64 conversion APIs in BaseLib that are run from UEFI Shell. +# +# Copyright (C) Microsoft Corporation. +# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = BaseLibUnitTestsUefi + FILE_GUID = df5a6fed-8786-4a9d-9d02-eab39497b4a1 + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = BaseLibUnitTestAppEntry + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + Base64UnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + BaseMemoryLib + UefiApplicationEntryPoint + DebugLib + UnitTestLib diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c index a24b66667e4..be5c0e15d30 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/IA32/SafeIntLibUintnIntnUnitTests.c @@ -3,7 +3,7 @@ SafeIntLib. Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c index 3c4e19d52e9..2b1a2223a0d 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.c @@ -2,7 +2,7 @@ UEFI OS based application for unit testing the SafeIntLib. Copyright (c) Microsoft Corporation.
- Copyright (c) 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -3054,9 +3054,9 @@ DxeEntryPoint ( return UefiTestMain (); } -int +int main ( - int argc, + int argc, char *argv[] ) { diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h index af67d409de0..7957c99a85c 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLib.h @@ -2,7 +2,7 @@ UEFI OS based application for unit testing the SafeIntLib. Copyright (c) Microsoft Corporation.
- Copyright (c) 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf index 7bfeeef4182..302af0aac3b 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibDxe.inf @@ -2,7 +2,7 @@ # DXE Driver that Unit Tests the SafeIntLib # # Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -42,4 +42,4 @@ UnitTestLib [Depex] - TRUE \ No newline at end of file + TRUE diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf index 1ff4074b06b..b490d838169 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibHost.inf @@ -2,7 +2,7 @@ # Host OS based Application that Unit Tests the SafeIntLib # # Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf index a21aca18c13..f3afcfa356e 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibPei.inf @@ -2,7 +2,7 @@ # PEIM that Unit Tests the SafeIntLib # # Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -42,4 +42,4 @@ UnitTestLib [Depex] - TRUE \ No newline at end of file + TRUE diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf index 012d33c9e47..cac4e34d1c1 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibSmm.inf @@ -2,7 +2,7 @@ # SMM Driver that Unit Tests the SafeIntLib # # Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## @@ -42,4 +42,4 @@ UnitTestLib [Depex] - TRUE \ No newline at end of file + TRUE diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf index 19e3148f7f8..bb428d248d1 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/TestBaseSafeIntLibUefiShell.inf @@ -2,7 +2,7 @@ # UEFI Shell based Application that Unit Tests the SafeIntLib # # Copyright (c) Microsoft Corporation.
-# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent ## diff --git a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c index 01fcf1096d2..0fee2981720 100644 --- a/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c +++ b/MdePkg/Test/UnitTest/Library/BaseSafeIntLib/X64/SafeIntLibUintnIntnUnitTests.c @@ -3,7 +3,7 @@ SafeIntLib. Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf index 9b88d646a04..07da7a88e95 100644 --- a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf @@ -1,7 +1,7 @@ ## @file # This module provides Cmocka Library implementation. # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni index 67f03288ca3..acdb72d075e 100644 --- a/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni +++ b/UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.uni @@ -3,7 +3,7 @@ // // This module provides Cmocka Library implementation. // -// Copyright (c) 2019, Intel Corporation. All rights reserved.
+// Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
// // SPDX-License-Identifier: BSD-2-Clause-Patent // diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c index acff80a05b5..0daea007284 100644 --- a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.c @@ -1,8 +1,10 @@ /** @file + Instance of Debug Library based on POSIX APIs -Copyright (c) 2018, Intel Corporation. All rights reserved.
-SPDX-License-Identifier: BSD-2-Clause-Patent + Uses Print Library to produce formatted output strings sent to printf(). + Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
+ SPDX-License-Identifier: BSD-2-Clause-Patent **/ #include diff --git a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf index 87617921e60..5babbca3b04 100644 --- a/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf +++ b/UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf @@ -3,7 +3,7 @@ # # Uses Print Library to produce formatted output strings sent to printf(). # -# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c index 0b1524421f8..1f590524d89 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.c @@ -3,9 +3,8 @@ Uses POSIX APIs malloc() and free() to allocate and free memory. - Copyright (c) 2018, Intel Corporation. All rights reserved.
+ Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include diff --git a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf index 813f9806eac..44ec3fd5172 100644 --- a/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf +++ b/UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf @@ -3,7 +3,7 @@ # # Uses POSIX APIs malloc() and free() to allocate and free memory. # -# Copyright (c) 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2018 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c index 95ad22c7ca9..4ce48bd2330 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.c @@ -1,6 +1,6 @@ /** - Implement UnitTestBootLib using USB Class Boot option. This should be industry standard and should - work on all platforms + Implement UnitTestBootLib using USB Class Boot option. This should be + industry standard and should work on all platforms Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent diff --git a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf index ea69b43b20d..80c4e4f111f 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestBootLibUsbClass/UnitTestBootLibUsbClass.inf @@ -4,7 +4,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] @@ -32,4 +31,4 @@ UefiBootManagerLib [Guids] - gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. + gEfiGlobalVariableGuid ## CONSUMES ## Used to probe boot options and set BootNext. diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c index 0bafa78314a..e48d614976c 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/AssertCmocka.c @@ -1,9 +1,8 @@ /** @file Implement UnitTestLib assert services using cmocka services - Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c index fc94ea3058e..78df086a28d 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/Log.c @@ -3,7 +3,6 @@ Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c index 1830955cca4..d66382e2d3a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTests.c @@ -3,7 +3,6 @@ Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -13,7 +12,6 @@ #include #include - STATIC UNIT_TEST_FRAMEWORK_HANDLE mFrameworkHandle = NULL; UNIT_TEST_FRAMEWORK_HANDLE diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c index 240200b83fb..cb9c881723e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/RunTestsCmocka.c @@ -1,9 +1,8 @@ /** @file UnitTestLib APIs to run unit tests using cmocka - Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -21,7 +20,6 @@ #include #include - STATIC UNIT_TEST_FRAMEWORK_HANDLE mFrameworkHandle = NULL; UNIT_TEST_FRAMEWORK_HANDLE diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 5486f4ed1ad..4ef9fbf9c14 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -3,7 +3,6 @@ Copyright (c) Microsoft Corporation. SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -15,9 +14,9 @@ #include #include -// -// Forward declaration of prototype -// +/// +/// Forward declaration of prototype +/// STATIC VOID UpdateTestFromSave ( diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf index 5f2c810ef2e..96e40e973cf 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.inf @@ -3,7 +3,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf index 15090f84d30..b12af915765 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf @@ -1,9 +1,8 @@ ## @file # Library to support Unit Testing from host environments using Cmocka services. # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c index a45cca0a6b6..e28327652ea 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.c @@ -1,9 +1,8 @@ -/** @file -- UnitTestNullPersistenceLib.c +/** @file This is an instance of the Unit Test Persistence Lib that does nothing. Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -15,7 +14,7 @@ @param[in] FrameworkHandle A pointer to the framework that is being persisted. - @retval TRUE + @retval TRUE @retval FALSE Cache doesn't exist or an error occurred. **/ diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf index 737f9f44462..11757726624 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibNull/UnitTestPersistenceLibNull.inf @@ -3,7 +3,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c index 86dc0f28275..ccca9bfacb7 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.c @@ -5,7 +5,6 @@ Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf index 787048e1eda..c518c4e5ce4 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestPersistenceLibSimpleFileSystem/UnitTestPersistenceLibSimpleFileSystem.inf @@ -7,7 +7,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c index a802afce7db..687a04f55da 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLib.c @@ -1,10 +1,8 @@ /** @file - Implement UnitTestResultReportLib doing plain txt out to console Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c index a511c9f573b..139360ee165 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.c @@ -1,10 +1,8 @@ /** @file - Implement UnitTestResultReportLib doing plain txt out to console Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -22,7 +20,7 @@ ReportPrint ( VA_LIST Marker; CHAR16 String[256]; UINTN Length; - + VA_START (Marker, Format); Length = UnicodeVSPrintAsciiFormat (String, sizeof (String), Format, Marker); if (Length == 0) { @@ -41,7 +39,7 @@ ReportOutput ( CHAR8 AsciiString[128]; UINTN Length; UINTN Index; - + Length = AsciiStrLen (Output); for (Index = 0; Index < Length; Index += (sizeof (AsciiString) - 1)) { AsciiStrCpyS (AsciiString, sizeof (AsciiString), &Output[Index]); diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf index 1679c868c99..4382199fbc7 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibConOut.inf @@ -3,7 +3,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c index 5981fc0f373..743aad2958a 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.c @@ -1,10 +1,8 @@ /** @file - Implement UnitTestResultReportLib doing plain txt out to console Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent - **/ #include @@ -21,7 +19,7 @@ ReportPrint ( VA_LIST Marker; CHAR8 String[256]; UINTN Length; - + VA_START (Marker, Format); Length = AsciiVSPrint (String, sizeof (String), Format, Marker); if (Length == 0) { @@ -40,7 +38,7 @@ ReportOutput ( CHAR8 AsciiString[128]; UINTN Length; UINTN Index; - + Length = AsciiStrLen (Output); for (Index = 0; Index < Length; Index += (sizeof (AsciiString) - 1)) { AsciiStrCpyS (AsciiString, sizeof (AsciiString), &Output[Index]); diff --git a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf index b15f9ec1508..a1c786a700e 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf +++ b/UnitTestFrameworkPkg/Library/UnitTestResultReportLib/UnitTestResultReportLibDebugLib.inf @@ -3,7 +3,6 @@ # # Copyright (c) Microsoft Corporation.
# SPDX-License-Identifier: BSD-2-Clause-Patent -# ## [Defines] diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h index d6819708156..d90bff0e4c1 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestBootLib.h @@ -5,7 +5,7 @@ platform customization will make porting to new code base/platform easier. Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h index 8682a8b895d..af19ba8f539 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestPersistenceLib.h @@ -4,7 +4,7 @@ (eg. a reboot-based test). Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h index 0a75a1faa4c..a417f490dc9 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h +++ b/UnitTestFrameworkPkg/PrivateInclude/Library/UnitTestResultReportLib.h @@ -3,7 +3,7 @@ be easily customized. Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ diff --git a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h index 193d63c8d35..e58b30093e4 100644 --- a/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h +++ b/UnitTestFrameworkPkg/PrivateInclude/UnitTestFrameworkTypes.h @@ -2,7 +2,7 @@ Provides the basic types and common elements of the unit test framework Copyright (c) Microsoft Corporation.
- Copyright (c) 2019, Intel Corporation. All rights reserved.
+ Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
SPDX-License-Identifier: BSD-2-Clause-Patent **/ @@ -12,58 +12,68 @@ #include -///================================================================================================ -///================================================================================================ /// -/// HANDY DEFINITIONS +/// The maximum length of a string stored in the unit test framework /// -///================================================================================================ -///================================================================================================ -#define UNIT_TEST_MAX_STRING_LENGTH (120) +#define UNIT_TEST_MAX_STRING_LENGTH (120) -#define UNIT_TEST_FINGERPRINT_SIZE (sizeof(UINT32)) // Hardcoded to CRC32. +/// +/// The size of a firngerprint used to save/resume execution of a unit test +/// framework. This is the size of a CRC32 value which is 32-bit value. +/// +/// +#define UNIT_TEST_FINGERPRINT_SIZE (sizeof (UINT32)) + +/// +/// The maximum length of a test failure message stored in the unit test +/// framework +/// #define UNIT_TEST_TESTFAILUREMSG_LENGTH (120) +/// +/// FAILURE_TYPE used to record the type of assert that was triggered by a unit +/// test. +/// typedef UINT32 FAILURE_TYPE; -#define FAILURETYPE_NOFAILURE (0) -#define FAILURETYPE_OTHER (1) -#define FAILURETYPE_ASSERTTRUE (2) -#define FAILURETYPE_ASSERTFALSE (3) -#define FAILURETYPE_ASSERTEQUAL (4) -#define FAILURETYPE_ASSERTNOTEQUAL (5) -#define FAILURETYPE_ASSERTNOTEFIERROR (6) -#define FAILURETYPE_ASSERTSTATUSEQUAL (7) -#define FAILURETYPE_ASSERTNOTNULL (8) - +#define FAILURETYPE_NOFAILURE (0) +#define FAILURETYPE_OTHER (1) +#define FAILURETYPE_ASSERTTRUE (2) +#define FAILURETYPE_ASSERTFALSE (3) +#define FAILURETYPE_ASSERTEQUAL (4) +#define FAILURETYPE_ASSERTNOTEQUAL (5) +#define FAILURETYPE_ASSERTNOTEFIERROR (6) +#define FAILURETYPE_ASSERTSTATUSEQUAL (7) +#define FAILURETYPE_ASSERTNOTNULL (8) -///================================================================================================ -///================================================================================================ /// -/// UNIT TEST DATA STRUCTURE DEFINITIONS +/// Unit Test context structure tracked by the unit test framework. /// -///================================================================================================ -///================================================================================================ - typedef struct { - CHAR8 *Description; - CHAR8 *Name; //can't have spaces and should be short - CHAR8 *Log; - FAILURE_TYPE FailureType; - CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; - UNIT_TEST_STATUS Result; - UNIT_TEST_FUNCTION RunTest; - UNIT_TEST_PREREQUISITE Prerequisite; - UNIT_TEST_CLEANUP CleanUp; - UNIT_TEST_CONTEXT Context; - UNIT_TEST_SUITE_HANDLE ParentSuite; + CHAR8 *Description; + CHAR8 *Name; //can't have spaces and should be short + CHAR8 *Log; + FAILURE_TYPE FailureType; + CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + UNIT_TEST_STATUS Result; + UNIT_TEST_FUNCTION RunTest; + UNIT_TEST_PREREQUISITE Prerequisite; + UNIT_TEST_CLEANUP CleanUp; + UNIT_TEST_CONTEXT Context; + UNIT_TEST_SUITE_HANDLE ParentSuite; } UNIT_TEST; +/// +/// Structure used to store the set of unit tests in a unit test suite as a list. +/// typedef struct { - LIST_ENTRY Entry; - UNIT_TEST UT; + LIST_ENTRY Entry; + UNIT_TEST UT; } UNIT_TEST_LIST_ENTRY; +/// +/// Unit Test Suite context structure tracked by the unit test framework. +/// typedef struct { UINTN NumTests; CHAR8 *Title; @@ -75,30 +85,35 @@ typedef struct { UNIT_TEST_FRAMEWORK_HANDLE ParentFramework; } UNIT_TEST_SUITE; +/// +/// Structure used to store the set of unit test suites in a unit test framework +/// as a list. +/// typedef struct { - LIST_ENTRY Entry; - UNIT_TEST_SUITE UTS; + LIST_ENTRY Entry; + UNIT_TEST_SUITE UTS; } UNIT_TEST_SUITE_LIST_ENTRY; +/// +/// Unit Test Framework context structure tracked by the unit test framework. +/// typedef struct { - CHAR8 *Title; - CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename characters. Is used in reporting and serialization. - CHAR8 *VersionString; - CHAR8 *Log; - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; - LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY - EFI_TIME StartTime; - EFI_TIME EndTime; - UNIT_TEST *CurrentTest; - VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. + CHAR8 *Title; + CHAR8 *ShortTitle; // This title should contain NO spaces or non-filename characters. Is used in reporting and serialization. + CHAR8 *VersionString; + CHAR8 *Log; + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; + LIST_ENTRY TestSuiteList; // UNIT_TEST_SUITE_LIST_ENTRY + EFI_TIME StartTime; + EFI_TIME EndTime; + UNIT_TEST *CurrentTest; + VOID *SavedState; // This is an instance of UNIT_TEST_SAVE_HEADER*, if present. } UNIT_TEST_FRAMEWORK; -// -//Structures for the framework to serializing unit test status -// - -typedef struct -{ +/// +/// Serialized version of a unit test +/// +typedef struct { UINT32 Size; // Size of the UNIT_TEST_SAVE_TEST including Log[] UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the test itself. CHAR8 FailureMessage[UNIT_TEST_TESTFAILUREMSG_LENGTH]; @@ -107,24 +122,28 @@ typedef struct CHAR8 Log[]; } UNIT_TEST_SAVE_TEST; -typedef struct -{ - UINT32 Size; // Size of the UNIT_TEST_SAVE_CONTEXT including Data[] - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. - UINT8 Data[]; // Actual data of the context. +/// +/// Serialized version of a unit test context +/// +typedef struct { + UINT32 Size; // Size of the UNIT_TEST_SAVE_CONTEXT including Data[] + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the corresponding test. + UINT8 Data[]; // Actual data of the context. } UNIT_TEST_SAVE_CONTEXT; -typedef struct -{ - UINT8 Version; - UINT32 SaveStateSize; // Size of the entire serialized buffer. - UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. - EFI_TIME StartTime; - UINT32 TestCount; - BOOLEAN HasSavedContext; - // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. - // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. - // CHAR8 Log[]; // NOTE: Not yet implemented!! +/// +/// Serialized version of unit test framework +/// +typedef struct { + UINT8 Version; + UINT32 SaveStateSize; // Size of the entire serialized buffer. + UINT8 Fingerprint[UNIT_TEST_FINGERPRINT_SIZE]; // Fingerprint of the framework that has been saved. + EFI_TIME StartTime; + UINT32 TestCount; + BOOLEAN HasSavedContext; + // UNIT_TEST_SAVE_TEST Tests[]; // Array of structures starts here. + // UNIT_TEST_SAVE_CONTEXT SavedContext[]; // Saved context for the currently running test. + // CHAR8 Log[]; // NOTE: Not yet implemented!! } UNIT_TEST_SAVE_HEADER; /** diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 2c629b6666c..4b676f4687e 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -1,5 +1,6 @@ -/** @file -- SampleUnitTestApp.c -This is a sample EFI Shell application to demostrate the usage of the Unit Test Library. +/** @file + This is a sample to demostrate the usage of the Unit Test Library that + supports the PEI, DXE, SMM, UEFI SHell, and host execution environments. Copyright (c) Microsoft Corporation.
SPDX-License-Identifier: BSD-2-Clause-Patent @@ -12,119 +13,181 @@ This is a sample EFI Shell application to demostrate the usage of the Unit Test #include #include +#define UNIT_TEST_NAME "Sample Unit Test" +#define UNIT_TEST_VERSION "0.1" -#define UNIT_TEST_NAME "Sample Unit Test" -#define UNIT_TEST_VERSION "0.1" - - -BOOLEAN mSampleGlobalTestBoolean = FALSE; -VOID *mSampleGlobalTestPointer = NULL; - - -///================================================================================================ -///================================================================================================ /// -/// HELPER FUNCTIONS +/// Global variables used in unit tests /// -///================================================================================================ -///================================================================================================ +BOOLEAN mSampleGlobalTestBoolean = FALSE; +VOID *mSampleGlobalTestPointer = NULL; + +/** + Sample Unit-Test Prerequisite Function that checks to make sure the global + pointer used in the test is already set to NULL. + Funtions with this prototype are registered to be dispatched by the unit test + framework prior to a given test case. If this prereq function returns + UNIT_TEST_ERROR_PREREQUISITE_NOT_MET, the test case will be skipped. -// -// Anything you think might be helpful that isn't a test itself. -// + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + @retval UNIT_TEST_PASSED Unit test case prerequisites + are met. + @retval UNIT_TEST_ERROR_PREREQUISITE_NOT_MET Test case should be skipped. + +**/ UNIT_TEST_STATUS EFIAPI MakeSureThatPointerIsNull ( - IN UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ) { - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); + UT_ASSERT_EQUAL ((UINTN)mSampleGlobalTestPointer, (UINTN)NULL); return UNIT_TEST_PASSED; -} // ListsShouldHaveTheSameDescriptorSize() +} +/** + Sample Unit-Test Cleanup (after) function that resets the global pointer to + NULL. + + Funtions with this prototype are registered to be dispatched by the + unit test framework after a given test case. This will be called even if the + test case returns an error, but not if the prerequisite fails and the test is + skipped. The purpose of this function is to clean up any global state or + test data. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED Test case cleanup succeeded. + @retval UNIT_TEST_ERROR_CLEANUP_FAILED Test case cleanup failed. +**/ VOID EFIAPI ClearThePointer ( - IN UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ) { mSampleGlobalTestPointer = NULL; -} // ClearThePointer() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST CASES -/// -///================================================================================================ -///================================================================================================ - +} +/** + Sample unit test that verifies the expected result of an unsigned integer + addition operation. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ UNIT_TEST_STATUS EFIAPI OnePlusOneShouldEqualTwo ( - IN UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ) { - UINTN A, B, C; + UINTN A; + UINTN B; + UINTN C; A = 1; B = 1; C = A + B; - UT_ASSERT_EQUAL(C, 2); + UT_ASSERT_EQUAL (C, 2); return UNIT_TEST_PASSED; -} // OnePlusOneShouldEqualTwo() - +} +/** + Sample unit test that verifies that a global BOOLEAN is updatable. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ UNIT_TEST_STATUS EFIAPI GlobalBooleanShouldBeChangeable ( - IN UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ) { mSampleGlobalTestBoolean = TRUE; - UT_ASSERT_TRUE(mSampleGlobalTestBoolean); + UT_ASSERT_TRUE (mSampleGlobalTestBoolean); mSampleGlobalTestBoolean = FALSE; - UT_ASSERT_FALSE(mSampleGlobalTestBoolean); + UT_ASSERT_FALSE (mSampleGlobalTestBoolean); return UNIT_TEST_PASSED; -} // GlobalBooleanShouldBeChangeable() - +} +/** + Sample unit test that logs a warning message and verifies that a global + pointer is updatable. + + @param[in] Context [Optional] An optional paramter that enables: + 1) test-case reuse with varied parameters and + 2) test-case re-entry for Target tests that need a + reboot. This parameter is a VOID* and it is the + responsibility of the test author to ensure that the + contents are well understood by all test cases that may + consume it. + + @retval UNIT_TEST_PASSED The Unit test has completed and the test + case was successful. + @retval UNIT_TEST_ERROR_TEST_FAILED A test case assertion has failed. +**/ UNIT_TEST_STATUS EFIAPI GlobalPointerShouldBeChangeable ( - IN UNIT_TEST_CONTEXT Context + IN UNIT_TEST_CONTEXT Context ) { + // // Example of logging. - UT_LOG_WARNING("About to change a global pointer! Current value is 0x%X\n", mSampleGlobalTestPointer); + // + UT_LOG_WARNING ("About to change a global pointer! Current value is 0x%X\n", mSampleGlobalTestPointer); - mSampleGlobalTestPointer = (VOID*)-1; - UT_ASSERT_EQUAL((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID*)-1)); + mSampleGlobalTestPointer = (VOID *)-1; + UT_ASSERT_EQUAL ((UINTN)mSampleGlobalTestPointer, (UINTN)((VOID *)-1)); return UNIT_TEST_PASSED; -} // GlobalPointerShouldBeChangeable() - - -///================================================================================================ -///================================================================================================ -/// -/// TEST ENGINE -/// -///================================================================================================ -///================================================================================================ - +} /** - UefiTestMain + Initialze the unit test framework, suite, and unit tests for the + sample unit tests and run the unit tests. + @retval EFI_SUCCESS All test cases were dispached. + @retval EFI_OUT_OF_RESOURCES There are not enough resources available to + initialize the unit tests. **/ EFI_STATUS EFIAPI @@ -133,17 +196,19 @@ UefiTestMain ( ) { EFI_STATUS Status; - UNIT_TEST_FRAMEWORK_HANDLE Framework = NULL; - UNIT_TEST_SUITE_HANDLE SimpleMathTests, GlobalVarTests; + UNIT_TEST_FRAMEWORK_HANDLE Framework; + UNIT_TEST_SUITE_HANDLE SimpleMathTests; + UNIT_TEST_SUITE_HANDLE GlobalVarTests; + + Framework = NULL; DEBUG(( DEBUG_INFO, "%a v%a\n", UNIT_TEST_NAME, UNIT_TEST_VERSION )); // // Start setting up the test framework for running the tests. // - Status = InitUnitTestFramework( &Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION ); - if (EFI_ERROR( Status )) - { + Status = InitUnitTestFramework (&Framework, UNIT_TEST_NAME, gEfiCallerBaseName, UNIT_TEST_VERSION); + if (EFI_ERROR (Status)) { DEBUG((DEBUG_ERROR, "Failed in InitUnitTestFramework. Status = %r\n", Status)); goto EXIT; } @@ -151,52 +216,56 @@ UefiTestMain ( // // Populate the SimpleMathTests Unit Test Suite. // - Status = CreateUnitTestSuite( &SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); + Status = CreateUnitTestSuite (&SimpleMathTests, Framework, "Simple Math Tests", "Sample.Math", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for SimpleMathTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL ); + AddTestCase (SimpleMathTests, "Adding 1 to 1 should produce 2", "Addition", OnePlusOneShouldEqualTwo, NULL, NULL, NULL); // // Populate the GlobalVarTests Unit Test Suite. // - Status = CreateUnitTestSuite( &GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL ); - if (EFI_ERROR( Status )) - { - DEBUG((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); + Status = CreateUnitTestSuite (&GlobalVarTests, Framework, "Global Variable Tests", "Sample.Globals", NULL, NULL); + if (EFI_ERROR (Status)) { + DEBUG ((DEBUG_ERROR, "Failed in CreateUnitTestSuite for GlobalVarTests\n")); Status = EFI_OUT_OF_RESOURCES; goto EXIT; } - AddTestCase( GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL ); - AddTestCase( GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL ); + AddTestCase (GlobalVarTests, "You should be able to change a global BOOLEAN", "Boolean", GlobalBooleanShouldBeChangeable, NULL, NULL, NULL); + AddTestCase (GlobalVarTests, "You should be able to change a global pointer", "Pointer", GlobalPointerShouldBeChangeable, MakeSureThatPointerIsNull, ClearThePointer, NULL); // // Execute the tests. // - Status = RunAllTestSuites( Framework ); + Status = RunAllTestSuites (Framework); EXIT: - if (Framework) - { - FreeUnitTestFramework( Framework ); + if (Framework) { + FreeUnitTestFramework (Framework); } return Status; -} // UefiTestMain() +} +/** + Standard PEIM entry point for target based unit test execution from PEI. +**/ EFI_STATUS EFIAPI PeiEntryPoint ( - IN EFI_PEI_FILE_HANDLE FileHandle, - IN CONST EFI_PEI_SERVICES **PeiServices + IN EFI_PEI_FILE_HANDLE FileHandle, + IN CONST EFI_PEI_SERVICES **PeiServices ) { return UefiTestMain (); } +/** + Standard UEFI entry point for target based unit test execution from DXE, SMM, + UEFI Shell. +**/ EFI_STATUS EFIAPI DxeEntryPoint ( @@ -207,6 +276,9 @@ DxeEntryPoint ( return UefiTestMain (); } +/** + Standard POSIX C entry point for host based unit test execution. +**/ int main ( int argc, diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf index 5d4d2991852..e253cf6e16d 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestDxe.inf @@ -1,37 +1,36 @@ -## @file -# Sample UnitTest built for execution in DXE. -# -# Copyright (c) Microsoft Corporation.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - - -[Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestDxe - FILE_GUID = 96BB18BD-FF2B-4B51-B683-0DC9A4BF12CF - MODULE_TYPE = DXE_DRIVER - VERSION_STRING = 1.0 - ENTRY_POINT = DxeEntryPoint - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - SampleUnitTest.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - UefiDriverEntryPoint - BaseLib - DebugLib - UnitTestLib - PrintLib - -[Depex] - TRUE +## @file +# Sample UnitTest built for execution in DXE. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestDxe + FILE_GUID = 96BB18BD-FF2B-4B51-B683-0DC9A4BF12CF + MODULE_TYPE = DXE_DRIVER + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SampleUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + UefiDriverEntryPoint + BaseLib + DebugLib + UnitTestLib + PrintLib + +[Depex] + TRUE diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf index 85dce4c5b61..59a367cc6ed 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf @@ -1,30 +1,30 @@ -## @file -# Sample UnitTest built for execution on a Host/Dev machine. -# -# Copyright (c) Microsoft Corporation.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -## - -[Defines] - INF_VERSION = 0x00010005 - BASE_NAME = SampleUnitTestHost - FILE_GUID = CC0EA77E-BF2D-4134-B419-0C02E15CE08E - MODULE_TYPE = HOST_APPLICATION - VERSION_STRING = 1.0 - -# -# The following information is for reference only and not required by the build tools. -# -# VALID_ARCHITECTURES = IA32 X64 -# - -[Sources] - SampleUnitTest.c - -[Packages] - MdePkg/MdePkg.dec - -[LibraryClasses] - BaseLib - DebugLib - UnitTestLib +## @file +# Sample UnitTest built for execution on a Host/Dev machine. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +## + +[Defines] + INF_VERSION = 0x00010005 + BASE_NAME = SampleUnitTestHost + FILE_GUID = CC0EA77E-BF2D-4134-B419-0C02E15CE08E + MODULE_TYPE = HOST_APPLICATION + VERSION_STRING = 1.0 + +# +# The following information is for reference only and not required by the build tools. +# +# VALID_ARCHITECTURES = IA32 X64 +# + +[Sources] + SampleUnitTest.c + +[Packages] + MdePkg/MdePkg.dec + +[LibraryClasses] + BaseLib + DebugLib + UnitTestLib diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf index 84050380a4f..60f5252c343 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf @@ -5,14 +5,13 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## - [Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestPei - FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 - MODULE_TYPE = PEIM - VERSION_STRING = 1.0 - ENTRY_POINT = PeiEntryPoint + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestPei + FILE_GUID = B9BD9451-3DC8-48EA-A6F0-55753BF186F1 + MODULE_TYPE = PEIM + VERSION_STRING = 1.0 + ENTRY_POINT = PeiEntryPoint # # The following information is for reference only and not required by the build tools. diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf index 56e109236eb..324ad2686e6 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf @@ -5,15 +5,14 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## - [Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestSmm - FILE_GUID = 389B16DB-F622-424C-9000-9E43C69CBF71 - MODULE_TYPE = DXE_SMM_DRIVER - VERSION_STRING = 1.0 - PI_SPECIFICATION_VERSION = 0x0001000A - ENTRY_POINT = DxeEntryPoint + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestSmm + FILE_GUID = 389B16DB-F622-424C-9000-9E43C69CBF71 + MODULE_TYPE = DXE_SMM_DRIVER + VERSION_STRING = 1.0 + PI_SPECIFICATION_VERSION = 0x0001000A + ENTRY_POINT = DxeEntryPoint # # The following information is for reference only and not required by the build tools. diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf index 1691a3498f5..6e39c229d4d 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf @@ -5,14 +5,13 @@ # SPDX-License-Identifier: BSD-2-Clause-Patent ## - [Defines] - INF_VERSION = 0x00010006 - BASE_NAME = SampleUnitTestUefiShell - FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B - MODULE_TYPE = UEFI_APPLICATION - VERSION_STRING = 1.0 - ENTRY_POINT = DxeEntryPoint + INF_VERSION = 0x00010006 + BASE_NAME = SampleUnitTestUefiShell + FILE_GUID = 9E8F461A-17E1-4312-B49C-E66F0A88EA8B + MODULE_TYPE = UEFI_APPLICATION + VERSION_STRING = 1.0 + ENTRY_POINT = DxeEntryPoint # # The following information is for reference only and not required by the build tools. @@ -32,6 +31,3 @@ DebugLib UnitTestLib PrintLib - - - diff --git a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc index 2bb8ff80120..701e7299d76 100644 --- a/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc +++ b/UnitTestFrameworkPkg/Test/UnitTestFrameworkPkgHostTest.dsc @@ -1,32 +1,33 @@ -## @file -# -# Copyright (c) Microsoft Corporation.
-# SPDX-License-Identifier: BSD-2-Clause-Patent -# -## - -[Defines] - PLATFORM_NAME = UnitTestFrameworkPkgHostTest - PLATFORM_GUID = C7F97D6D-54AC-45A9-8197-CC99B20CC7EC - PLATFORM_VERSION = 0.1 - DSC_SPECIFICATION = 0x00010005 - OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg/HostTest - SUPPORTED_ARCHITECTURES = IA32|X64 - BUILD_TARGETS = NOOPT - SKUID_IDENTIFIER = DEFAULT - -!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc - -[Components] - # - # Build HOST_APPLICATION that tests the SampleUnitTest - # - UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf - - # - # Build Libraries - # - UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf - UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf - UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf - UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf +## @file +# UnitTestFrameworkPkg DSC file used to build host-based unit tests. +# +# Copyright (c) Microsoft Corporation.
+# SPDX-License-Identifier: BSD-2-Clause-Patent +# +## + +[Defines] + PLATFORM_NAME = UnitTestFrameworkPkgHostTest + PLATFORM_GUID = C7F97D6D-54AC-45A9-8197-CC99B20CC7EC + PLATFORM_VERSION = 0.1 + DSC_SPECIFICATION = 0x00010005 + OUTPUT_DIRECTORY = Build/UnitTestFrameworkPkg/HostTest + SUPPORTED_ARCHITECTURES = IA32|X64 + BUILD_TARGETS = NOOPT + SKUID_IDENTIFIER = DEFAULT + +!include UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc + +[Components] + # + # Build HOST_APPLICATION that tests the SampleUnitTest + # + UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestHost.inf + + # + # Build Libraries + # + UnitTestFrameworkPkg/Library/CmockaLib/CmockaLib.inf + UnitTestFrameworkPkg/Library/Posix/DebugLibPosix/DebugLibPosix.inf + UnitTestFrameworkPkg/Library/Posix/MemoryAllocationLibPosix/MemoryAllocationLibPosix.inf + UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLibCmocka.inf diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc index e3e42c2acf4..0ad44822738 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkg.dsc @@ -1,7 +1,7 @@ ## @file # UnitTestFrameworkPkg # -# Copyright (c) 2007 - 2018, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# # SPDX-License-Identifier: BSD-2-Clause-Patent # @@ -32,6 +32,3 @@ UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestPei.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestSmm.inf UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTestUefiShell.inf - -[BuildOptions] - *_*_*_CC_FLAGS = -D DISABLE_NEW_DEPRECATED_INTERFACES diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc index 4f7371b0911..cf833b26b46 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgHost.dsc.inc @@ -1,6 +1,7 @@ ## @file +# UnitTestFrameworkPkg DSC include file for host based test DSC # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## diff --git a/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc b/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc index 27e7fbe90cf..c29b056fcac 100644 --- a/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc +++ b/UnitTestFrameworkPkg/UnitTestFrameworkPkgTarget.dsc.inc @@ -1,6 +1,7 @@ ## @file +# UnitTestFrameworkPkg DSC include file for target based test DSC # -# Copyright (c) 2019, Intel Corporation. All rights reserved.
+# Copyright (c) 2019 - 2020, Intel Corporation. All rights reserved.
# SPDX-License-Identifier: BSD-2-Clause-Patent # ## From 007cc2b12bcdfcc6699a918c04b4c4ae85ded6c7 Mon Sep 17 00:00:00 2001 From: Michael D Kinney Date: Wed, 22 Jan 2020 08:46:30 -0800 Subject: [PATCH 383/384] Fix spelling errors Signed-off-by: Michael D Kinney --- UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c | 2 +- .../Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c index 4ef9fbf9c14..e37c78a41d9 100644 --- a/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c +++ b/UnitTestFrameworkPkg/Library/UnitTestLib/UnitTestLib.c @@ -802,7 +802,7 @@ SerializeState ( @retval EFI_OUT_OF_RESOURCES There are not enough resources available to save the framework and context state. @retval EFI_DEVICE_ERROR The framework and context state could not be - saved to a persistent storage devide due to a + saved to a persistent storage device due to a device error. **/ EFI_STATUS diff --git a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c index 4b676f4687e..63017f1abe2 100644 --- a/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c +++ b/UnitTestFrameworkPkg/Test/UnitTest/Sample/SampleUnitTest/SampleUnitTest.c @@ -182,7 +182,7 @@ GlobalPointerShouldBeChangeable ( } /** - Initialze the unit test framework, suite, and unit tests for the + Initialize the unit test framework, suite, and unit tests for the sample unit tests and run the unit tests. @retval EFI_SUCCESS All test cases were dispached. From 7b4972ec98e8e33ca4f7733e3f57b3065d79517f Mon Sep 17 00:00:00 2001 From: Bret Barkelew Date: Wed, 22 Jan 2020 14:54:31 -0800 Subject: [PATCH 384/384] Clean up the way the ASSERT macros work with complex parameters. --- MdePkg/Include/Library/UnitTestLib.h | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/MdePkg/Include/Library/UnitTestLib.h b/MdePkg/Include/Library/UnitTestLib.h index 42b63b90719..74a61caf4cb 100644 --- a/MdePkg/Include/Library/UnitTestLib.h +++ b/MdePkg/Include/Library/UnitTestLib.h @@ -376,7 +376,7 @@ SaveFrameworkState ( @param[in] ValueB Value to be compared for equality (64-bit comparison). **/ #define UT_ASSERT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertEqual ((UINT64)(ValueA), (UINT64)(ValueB), __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -390,7 +390,7 @@ SaveFrameworkState ( @param[in] Length Number of bytes to compare in BufferA and BufferB. **/ #define UT_ASSERT_MEM_EQUAL(BufferA, BufferB, Length) \ - if(!UnitTestAssertMemEqual ((VOID *)(UINTN)BufferA, (VOID *)(UINTN)BufferB, (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #BufferA, #BufferB)) { \ + if(!UnitTestAssertMemEqual ((VOID *)(UINTN)(BufferA), (VOID *)(UINTN)(BufferB), (UINTN)Length, __FUNCTION__, __LINE__, __FILE__, #BufferA, #BufferB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -403,7 +403,7 @@ SaveFrameworkState ( @param[in] ValueB Value to be compared for inequality (64-bit comparison). **/ #define UT_ASSERT_NOT_EQUAL(ValueA, ValueB) \ - if(!UnitTestAssertNotEqual ((UINT64)ValueA, (UINT64)ValueB, __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ + if(!UnitTestAssertNotEqual ((UINT64)(ValueA), (UINT64)(ValueB), __FUNCTION__, __LINE__, __FILE__, #ValueA, #ValueB)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -415,7 +415,7 @@ SaveFrameworkState ( @param[in] Status EFI_STATUS value to check. **/ #define UT_ASSERT_NOT_EFI_ERROR(Status) \ - if(!UnitTestAssertNotEfiError (Status, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertNotEfiError ((Status), __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -428,7 +428,7 @@ SaveFrameworkState ( @param[in] Expected EFI_STATUS values to compare for equality. **/ #define UT_ASSERT_STATUS_EQUAL(Status, Expected) \ - if(!UnitTestAssertStatusEqual (Status, Expected, __FUNCTION__, __LINE__, __FILE__, #Status)) { \ + if(!UnitTestAssertStatusEqual ((Status), (Expected), __FUNCTION__, __LINE__, __FILE__, #Status)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ } @@ -440,7 +440,7 @@ SaveFrameworkState ( @param[in] Pointer Pointer to be checked against NULL. **/ #define UT_ASSERT_NOT_NULL(Pointer) \ - if(!UnitTestAssertNotNull (Pointer, __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ + if(!UnitTestAssertNotNull ((Pointer), __FUNCTION__, __LINE__, __FILE__, #Pointer)) { \ return UNIT_TEST_ERROR_TEST_FAILED; \ }