5.2.8 CalculateCrc32()

Use this service to maintain the checksums in the UEFI System Table, UEFI boot services table, and UEFI runtime services table. A UEFI driver that modifies one of these tables should use this service to update the checksums. A UEFI driver could compute the 32-bit CRC on its own, but the UEFI driver is smaller if it takes advantage of this UEFI boot service. This service can also be used to compute the checksums in Guided Partition Table(GPT) structures.

The following code fragment shows how CalculateCrc32() can be used to calculate and update the 32-bit CRC field in the UEFI System Table header. The EDK II library UefiBootServicesTableLib provides global variables for the UEFI System Table, the UEFI Boot Services Table, and the Image Handle for the currently executing driver. In this example, the global variable for the UEFI System Table called gST and the global variable for the UEFI Boot Services Table called gBS are used to reference the UEFI System Table header and call the UEFI Boot Services CalculateCrc32(). Since the CRC32 field is part of the structure for which the 32-bit CRC is being computed, it must be set to zero before calling CalculateCrc32().

Example 71-Calculate and update 32-bit CRC in UEFI System Table
#include <Uefi.h>
#include <Library/UefiBootServicesTableLib.h>

EFI_STATUS Status;

gST->Hdr.CRC32 = 0;
Status = gBS->CalculateCrc32 (
                &gST->Hdr,
                gST->Hdr.HeaderSize,
                &gST->Hdr.CRC32
                );
if (EFI_ERROR (Status)) {
  return Status;
}

The code fragment below shows how to calculate a 32-bit CRC for an EXAMPLE_DEVICE structure. Since the computed 32-bit CRC is not stored within the EXAMPLE_DEVICE structure, it does not need to be zeroed before calling the CalculateCrc32() service.

Example 72-Calculate and 32-bit CRC for a structure
#include <Uefi.h>
#include <Library/UefiBootServicesTableLib.h>

EFI_STATUS Status;
EXAMPLE_DEVICE Device;
UINT32 Crc;

Status = gBS->CalculateCrc32 (&Device, sizeof (Device), &Crc);
if (EFI_ERROR (Status)) {
  return Status;
}

The CalculateCrc32() service can also be used to verify a 32-bit CRC value. The code fragment below shows how the 32-bit CRC for the UEFI System Table header can be verified. This algorithm preserves the original contents of the UEFI System Table header. It returns TRUE if the 32-bit CRC is good. Otherwise, it returns FALSE.

Example 73-Verify 32-bit CRC in UEFI System Table
#include <Uefi.h>
#include <Library/UefiBootServicesTableLib.h>

EFI_STATUS Status;
UINT32 OriginalCrc32;
UINT32 Crc32;

OriginalCrc32 = gST->Hdr.CRC32;
gST->Hdr.CRC32 = 0;
Status = gBS->CalculateCrc32 (
                &gST->Hdr,
                gST->Hdr.HeaderSize,
                &Crc32
                );
gST->Hdr.CRC32 = OriginalCrc32;
if (EFI_ERROR (Status)) {
  return FALSE;
}
return (Crc32 == OriginalCrc32);