VirtualBox

Ignore:
Timestamp:
Aug 14, 2024 1:16:30 PM (9 months ago)
Author:
vboxsync
svn:sync-xref-src-repo-rev:
164367
Message:

Devices/EFI/FirmwareNew: Merge edk2-stable-202405 and make it build on aarch64, bugref:4643

Location:
trunk/src/VBox/Devices/EFI/FirmwareNew
Files:
46 added
1 deleted
117 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/VBox/Devices/EFI/FirmwareNew

  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.c

    r99404 r105670  
    14841484
    14851485  @param  This                         Indicates a pointer to the calling context.
    1486   @param  MediaId                      ID of the medium to receive data from.
     1486  @param  MediaId                      ID of the medium to receive data from. If there is no
     1487                                       block IO protocol supported by the physical device, the
     1488                                       value of MediaId is undefined.
    14871489  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    14881490                                       of the security protocol command. A Timeout value of 0
     
    16011603
    16021604  @param  This                         Indicates a pointer to the calling context.
    1603   @param  MediaId                      ID of the medium to receive data from.
     1605  @param  MediaId                      ID of the medium to receive data from. If there is no
     1606                                       block IO protocol supported by the physical device, the
     1607                                       value of MediaId is undefined.
    16041608  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    16051609                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaBus.h

    r101291 r105670  
    928928
    929929  @param  This                         Indicates a pointer to the calling context.
    930   @param  MediaId                      ID of the medium to receive data from.
     930  @param  MediaId                      ID of the medium to receive data from. If there is no
     931                                       block IO protocol supported by the physical device, the
     932                                       value of MediaId is undefined.
    931933  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    932934                                       of the security protocol command. A Timeout value of 0
     
    10081010
    10091011  @param  This                         Indicates a pointer to the calling context.
    1010   @param  MediaId                      ID of the medium to receive data from.
     1012  @param  MediaId                      ID of the medium to receive data from. If there is no
     1013                                       block IO protocol supported by the physical device, the
     1014                                       value of MediaId is undefined.
    10111015  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    10121016                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Ata/AtaBusDxe/AtaPassThruExecute.c

    r101291 r105670  
    363363    //
    364364    if ((PhyLogicSectorSupport & BIT12) != 0) {
    365       BlockMedia->BlockSize = (UINT32)(((IdentifyData->logic_sector_size_hi << 16) | IdentifyData->logic_sector_size_lo) * sizeof (UINT16));
     365      BlockMedia->BlockSize = (UINT32)(((UINT32)(IdentifyData->logic_sector_size_hi << 16) | IdentifyData->logic_sector_size_lo) * sizeof (UINT16));
    366366    }
    367367
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2KbdTextIn.c

    r99404 r105670  
    259259  @param Key     The output buffer for key value
    260260
    261   @retval EFI_SUCCESS success to read key stroke
     261  @retval EFI_SUCCESS      success to read key stroke
     262  @retval EFI_UNSUPPORTED  The device does not support the ability to read keystroke data.
    262263**/
    263264EFI_STATUS
     
    434435                                  hardware errors.
    435436    @retval EFI_INVALID_PARAMETER KeyData is NULL.
     437    @retval EFI_UNSUPPORTED       The device does not support the ability to read keystroke data.
    436438
    437439**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Isa/Ps2KeyboardDxe/Ps2Keyboard.h

    r99404 r105670  
    339339
    340340  @retval EFI_SUCCESS success to read key stroke
     341  @retval EFI_UNSUPPORTED  The device does not support the ability to read keystroke data.
    341342**/
    342343EFI_STATUS
     
    442443                            hardware errors.
    443444    @retval EFI_INVALID_PARAMETER - KeyData is NULL.
     445    @retval EFI_UNSUPPORTED       - The device does not support the ability to read
     446                            keystroke data.
    444447
    445448**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.c

    r101291 r105670  
    17001700
    17011701  @param  This                         Indicates a pointer to the calling context.
    1702   @param  MediaId                      ID of the medium to receive data from.
     1702  @param  MediaId                      ID of the medium to receive data from. If there is no
     1703                                       block IO protocol supported by the physical device, the
     1704                                       value of MediaId is undefined.
    17031705  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    17041706                                       of the security protocol command. A Timeout value of 0
     
    18131815
    18141816  @param  This                         Indicates a pointer to the calling context.
    1815   @param  MediaId                      ID of the medium to receive data from.
     1817  @param  MediaId                      ID of the medium to receive data from. If there is no
     1818                                       block IO protocol supported by the physical device, the
     1819                                       value of MediaId is undefined.
    18161820  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    18171821                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/NvmExpressDxe/NvmExpressBlockIo.h

    r99404 r105670  
    290290
    291291  @param  This                         Indicates a pointer to the calling context.
    292   @param  MediaId                      ID of the medium to receive data from.
     292  @param  MediaId                      ID of the medium to receive data from. If there is no
     293                                       block IO protocol supported by the physical device, the
     294                                       value of MediaId is undefined.
    293295  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    294296                                       of the security protocol command. A Timeout value of 0
     
    370372
    371373  @param  This                         Indicates a pointer to the calling context.
    372   @param  MediaId                      ID of the medium to receive data from.
     374  @param  MediaId                      ID of the medium to receive data from. If there is no
     375                                       block IO protocol supported by the physical device, the
     376                                       value of MediaId is undefined.
    373377  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    374378                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/NvmExpressPei/NvmExpressPeiS3.c

    r99404 r105670  
    6363  }
    6464
    65   if (S3InitDevices == NULL) {
    66     return Skip;
    67   }
    68 
    6965  //
    7066  // Only need to initialize the controllers that exist in the device list.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/PciBusDxe/PciIo.c

    r101291 r105670  
    10251025      }
    10261026
    1027       mIoMmuProtocol->SetAttribute (
    1028                         mIoMmuProtocol,
    1029                         PciIoDevice->Handle,
    1030                         *Mapping,
    1031                         IoMmuAttribute
    1032                         );
     1027      Status = mIoMmuProtocol->SetAttribute (
     1028                                 mIoMmuProtocol,
     1029                                 PciIoDevice->Handle,
     1030                                 *Mapping,
     1031                                 IoMmuAttribute
     1032                                 );
    10331033    }
    10341034  }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/PciBusDxe/PciOptionRomSupport.c

    r99404 r105670  
    507507    RomImageSize = RomImageSize + RomPcir->ImageLength * 512;
    508508    RomBarOffset = RomBarOffset + RomPcir->ImageLength * 512;
    509   } while (((Indicator & 0x80) == 0x00) && ((RomBarOffset - RomBar) < RomSize));
     509  } while (((Indicator & 0x80) == 0x00) && ((RomBarOffset - RomBar) < RomSize) && (RomImageSize > 0));
    510510
    511511  //
     
    513513  // of the legacy length and the PCIR Image Length
    514514  //
    515   if (CodeType == PCI_CODE_TYPE_PCAT_IMAGE) {
     515  if ((RomImageSize > 0) && (CodeType == PCI_CODE_TYPE_PCAT_IMAGE)) {
    516516    RomImageSize = MAX (RomImageSize, LegacyImageLength);
    517517  }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/UhciDxe/UhciSched.c

    r99404 r105670  
    198198
    199199/**
    200   Convert the poll rate to the maxium 2^n that is smaller
     200  Convert the poll rate to the maximum 2^n that is smaller
    201201  than Interval.
    202202
     
    214214
    215215  ASSERT (Interval != 0);
     216
     217  //
     218  // To safeguard RELEASE mode wherein ASSERT is effectively not there,
     219  // if inadvertently Interval is still 0 here, treat it the same as 1.
     220  //
     221  if (Interval == 0) {
     222    Interval = 1;
     223  }
    216224
    217225  //
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/UhciDxe/UsbHcMem.c

    r99404 r105670  
    251251
    252252  ASSERT ((Block != NULL));
     253
     254  if (Block == NULL) {
     255    return 0;
     256  }
     257
    253258  //
    254259  // calculate the pci memory address for host memory address.
     
    537542  ASSERT (Block != NULL);
    538543
     544  if (Block == NULL) {
     545    return;
     546  }
     547
    539548  //
    540549  // Release the current memory block if it is empty and not the head
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.c

    r99404 r105670  
    227227  @param  Mem            The pointer to host memory.
    228228  @param  Size           The size of the memory region.
     229  @param  Alignment      Alignment the size to USBHC_MEM_UNIT bytes.
    229230
    230231  @return                The pci memory address
     
    235236  IN USBHC_MEM_POOL  *Pool,
    236237  IN VOID            *Mem,
    237   IN UINTN           Size
     238  IN UINTN           Size,
     239  IN BOOLEAN         Alignment
    238240  )
    239241{
     
    244246  UINTN                 Offset;
    245247
    246   Head      = Pool->Head;
    247   AllocSize = USBHC_MEM_ROUND (Size);
     248  Head = Pool->Head;
     249  if (Alignment) {
     250    AllocSize = USBHC_MEM_ROUND (Size);
     251  } else {
     252    AllocSize = Size;
     253  }
    248254
    249255  if (Mem == NULL) {
     
    276282  @param  Mem            The pointer to pci memory.
    277283  @param  Size           The size of the memory region.
     284  @param  Alignment      Alignment the size to USBHC_MEM_UNIT bytes.
    278285
    279286  @return                The host memory address
     
    284291  IN USBHC_MEM_POOL  *Pool,
    285292  IN VOID            *Mem,
    286   IN UINTN           Size
     293  IN UINTN           Size,
     294  IN BOOLEAN         Alignment
    287295  )
    288296{
     
    293301  UINTN                 Offset;
    294302
    295   Head      = Pool->Head;
    296   AllocSize = USBHC_MEM_ROUND (Size);
     303  Head = Pool->Head;
     304  if (Alignment) {
     305    AllocSize = USBHC_MEM_ROUND (Size);
     306  } else {
     307    AllocSize = Size;
     308  }
    297309
    298310  if (Mem == NULL) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/UsbHcMem.h

    r99404 r105670  
    130130  @param  Mem            The pointer to host memory.
    131131  @param  Size           The size of the memory region.
     132  @param  Alignment      Alignment the size to USBHC_MEM_UNIT bytes.
    132133
    133134  @return                The pci memory address
     
    138139  IN USBHC_MEM_POOL  *Pool,
    139140  IN VOID            *Mem,
    140   IN UINTN           Size
     141  IN UINTN           Size,
     142  IN BOOLEAN         Alignment
    141143  );
    142144
     
    147149  @param  Mem            The pointer to pci memory.
    148150  @param  Size           The size of the memory region.
     151  @param  Alignment      Alignment the size to USBHC_MEM_UNIT bytes.
    149152
    150153  @return                The host memory address
     
    155158  IN USBHC_MEM_POOL  *Pool,
    156159  IN VOID            *Mem,
    157   IN UINTN           Size
     160  IN UINTN           Size,
     161  IN BOOLEAN         Alignment
    158162  );
    159163
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.c

    r101291 r105670  
    22  The XHCI controller driver.
    33
    4 Copyright (c) 2011 - 2022, Intel Corporation. All rights reserved.<BR>
     4(C) Copyright 2023 Hewlett Packard Enterprise Development LP<BR>
     5Copyright (c) 2011 - 2023, Intel Corporation. All rights reserved.<BR>
    56SPDX-License-Identifier: BSD-2-Clause-Patent
    67
     
    8586  0x0
    8687};
     88
     89static UINT64   mXhciPerformanceCounterStartValue;
     90static UINT64   mXhciPerformanceCounterEndValue;
     91static UINT64   mXhciPerformanceCounterFrequency;
     92static BOOLEAN  mXhciPerformanceCounterValuesCached = FALSE;
    8793
    8894/**
     
    820826  *DataLength     = Urb->Completed;
    821827
    822   if ((*TransferResult == EFI_USB_ERR_STALL) || (*TransferResult == EFI_USB_ERR_BABBLE)) {
     828  //
     829  // Based on XHCI spec 4.8.3, software should do the reset endpoint while USB Transaction occur.
     830  //
     831  if ((*TransferResult == EFI_USB_ERR_STALL) || (*TransferResult == EFI_USB_ERR_BABBLE) || (*TransferResult == EDKII_USB_ERR_TRANSACTION)) {
    823832    ASSERT (Status == EFI_DEVICE_ERROR);
    824833    RecoveryStatus = XhcRecoverHaltedEndpoint (Xhc, Urb);
     
    22952304  return EFI_SUCCESS;
    22962305}
     2306
     2307/**
     2308  Converts a time in nanoseconds to a performance counter tick count.
     2309
     2310  @param  Time  The time in nanoseconds to be converted to performance counter ticks.
     2311  @return Time in nanoseconds converted to ticks.
     2312**/
     2313UINT64
     2314XhcConvertTimeToTicks (
     2315  IN UINT64  Time
     2316  )
     2317{
     2318  UINT64  Ticks;
     2319  UINT64  Remainder;
     2320  UINT64  Divisor;
     2321  UINTN   Shift;
     2322
     2323  // Cache the return values to avoid repeated calls to GetPerformanceCounterProperties ()
     2324  if (!mXhciPerformanceCounterValuesCached) {
     2325    mXhciPerformanceCounterFrequency = GetPerformanceCounterProperties (
     2326                                         &mXhciPerformanceCounterStartValue,
     2327                                         &mXhciPerformanceCounterEndValue
     2328                                         );
     2329
     2330    mXhciPerformanceCounterValuesCached = TRUE;
     2331  }
     2332
     2333  // Prevent returning a tick value of 0, unless Time is already 0
     2334  if (0 == mXhciPerformanceCounterFrequency) {
     2335    return Time;
     2336  }
     2337
     2338  // Nanoseconds per second
     2339  Divisor = 1000000000;
     2340
     2341  //
     2342  //           Frequency
     2343  // Ticks = ------------- x Time
     2344  //         1,000,000,000
     2345  //
     2346  Ticks = MultU64x64 (
     2347            DivU64x64Remainder (
     2348              mXhciPerformanceCounterFrequency,
     2349              Divisor,
     2350              &Remainder
     2351              ),
     2352            Time
     2353            );
     2354
     2355  //
     2356  // Ensure (Remainder * Time) will not overflow 64-bit.
     2357  //
     2358  // HighBitSet64 (Remainder) + 1 + HighBitSet64 (Time) + 1 <= 64
     2359  //
     2360  Shift     = MAX (0, HighBitSet64 (Remainder) + HighBitSet64 (Time) - 62);
     2361  Remainder = RShiftU64 (Remainder, (UINTN)Shift);
     2362  Divisor   = RShiftU64 (Divisor, (UINTN)Shift);
     2363  Ticks    += DivU64x64Remainder (MultU64x64 (Remainder, Time), Divisor, NULL);
     2364
     2365  return Ticks;
     2366}
     2367
     2368/**
     2369  Computes and returns the elapsed ticks since PreviousTick. The
     2370  value of PreviousTick is overwritten with the current performance
     2371  counter value.
     2372
     2373  @param  PreviousTick    Pointer to PreviousTick count.
     2374  @return The elapsed ticks since PreviousCount. PreviousCount is
     2375          overwritten with the current performance counter value.
     2376**/
     2377UINT64
     2378XhcGetElapsedTicks (
     2379  IN OUT UINT64  *PreviousTick
     2380  )
     2381{
     2382  UINT64  CurrentTick;
     2383  UINT64  Delta;
     2384
     2385  CurrentTick = GetPerformanceCounter ();
     2386
     2387  //
     2388  // Determine if the counter is counting up or down
     2389  //
     2390  if (mXhciPerformanceCounterStartValue < mXhciPerformanceCounterEndValue) {
     2391    //
     2392    // Counter counts upwards, check for an overflow condition
     2393    //
     2394    if (*PreviousTick > CurrentTick) {
     2395      Delta = (mXhciPerformanceCounterEndValue - *PreviousTick) + CurrentTick;
     2396    } else {
     2397      Delta = CurrentTick - *PreviousTick;
     2398    }
     2399  } else {
     2400    //
     2401    // Counter counts downwards, check for an underflow condition
     2402    //
     2403    if (*PreviousTick < CurrentTick) {
     2404      Delta = (mXhciPerformanceCounterStartValue - CurrentTick) + *PreviousTick;
     2405    } else {
     2406      Delta = *PreviousTick - CurrentTick;
     2407    }
     2408  }
     2409
     2410  //
     2411  // Set PreviousTick to CurrentTick
     2412  //
     2413  *PreviousTick = CurrentTick;
     2414
     2415  return Delta;
     2416}
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/Xhci.h

    r99404 r105670  
    33  Provides some data structure definitions used by the XHCI host controller driver.
    44
     5(C) Copyright 2023 Hewlett Packard Enterprise Development LP<BR>
    56Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
    67Copyright (c) Microsoft Corporation.<BR>
     
    2728#include <Library/DebugLib.h>
    2829#include <Library/ReportStatusCodeLib.h>
     30#include <Library/TimerLib.h>
     31#include <Library/PcdLib.h>
    2932
    3033#include <IndustryStandard/Pci.h>
     
    3740#include "ComponentName.h"
    3841#include "UsbHcMem.h"
     42
     43//
     44// Converts a count from microseconds to nanoseconds
     45//
     46#define XHC_MICROSECOND_TO_NANOSECOND(Time)  (MultU64x32((Time), 1000))
    3947
    4048//
     
    721729  );
    722730
     731/**
     732  Converts a time in nanoseconds to a performance counter tick count.
     733
     734  @param  Time  The time in nanoseconds to be converted to performance counter ticks.
     735  @return Time in nanoseconds converted to ticks.
     736**/
     737UINT64
     738XhcConvertTimeToTicks (
     739  UINT64  Time
     740  );
     741
     742/**
     743  Computes and returns the elapsed ticks since PreviousTick. The
     744  value of PreviousTick is overwritten with the current performance
     745  counter value.
     746
     747  @param  PreviousTick    Pointer to PreviousTick count.
     748  @return The elapsed ticks since PreviousCount. PreviousCount is
     749          overwritten with the current performance counter value.
     750**/
     751UINT64
     752XhcGetElapsedTicks (
     753  IN OUT UINT64  *PreviousTick
     754  );
     755
    723756#endif
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/XhciDxe.inf

    r80721 r105670  
    44#  Control, Bulk, Interrupt and Isochronous requests to those attached usb LS/FS/HS/SS devices.
    55#
     6#  (C) Copyright 2023 Hewlett Packard Enterprise Development LP<BR>
    67#  Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
    78#
     
    4546[Packages]
    4647  MdePkg/MdePkg.dec
     48  MdeModulePkg/MdeModulePkg.dec
    4749
    4850[LibraryClasses]
     
    5557  DebugLib
    5658  ReportStatusCodeLib
     59  TimerLib
     60  PcdLib
    5761
    5862[Guids]
     
    6367  gEfiUsb2HcProtocolGuid                        ## BY_START
    6468
     69[Pcd]
     70  gEfiMdeModulePkgTokenSpaceGuid.PcdDelayXhciHCReset  ## CONSUMES
     71
    6572# [Event]
    6673# EVENT_TYPE_PERIODIC_TIMER       ## CONSUMES
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/XhciReg.c

    r99404 r105670  
    33  The XHCI register operation routines.
    44
     5(C) Copyright 2023 Hewlett Packard Enterprise Development LP<BR>
    56Copyright (c) 2011 - 2017, Intel Corporation. All rights reserved.<BR>
    67SPDX-License-Identifier: BSD-2-Clause-Patent
     
    418419  to become set (or clear).
    419420
    420   @param  Xhc                    The XHCI Instance.
    421   @param  Offset                 The offset of the operation register.
    422   @param  Bit                    The bit of the register to wait for.
    423   @param  WaitToSet              Wait the bit to set or clear.
    424   @param  Timeout                The time to wait before abort (in millisecond, ms).
    425 
    426   @retval EFI_SUCCESS            The bit successfully changed by host controller.
    427   @retval EFI_TIMEOUT            The time out occurred.
    428   @retval EFI_OUT_OF_RESOURCES   Memory for the timer event could not be allocated.
     421  @param  Xhc          The XHCI Instance.
     422  @param  Offset       The offset of the operation register.
     423  @param  Bit          The bit of the register to wait for.
     424  @param  WaitToSet    Wait the bit to set or clear.
     425  @param  Timeout      The time to wait before abort (in millisecond, ms).
     426
     427  @retval EFI_SUCCESS  The bit successfully changed by host controller.
     428  @retval EFI_TIMEOUT  The time out occurred.
    429429
    430430**/
     
    438438  )
    439439{
    440   EFI_STATUS  Status;
    441   EFI_EVENT   TimeoutEvent;
    442 
    443   TimeoutEvent = NULL;
     440  UINT64  TimeoutTicks;
     441  UINT64  ElapsedTicks;
     442  UINT64  TicksDelta;
     443  UINT64  CurrentTick;
    444444
    445445  if (Timeout == 0) {
     
    447447  }
    448448
    449   Status = gBS->CreateEvent (
    450                   EVT_TIMER,
    451                   TPL_CALLBACK,
    452                   NULL,
    453                   NULL,
    454                   &TimeoutEvent
    455                   );
    456 
    457   if (EFI_ERROR (Status)) {
    458     goto DONE;
    459   }
    460 
    461   Status = gBS->SetTimer (
    462                   TimeoutEvent,
    463                   TimerRelative,
    464                   EFI_TIMER_PERIOD_MILLISECONDS (Timeout)
    465                   );
    466 
    467   if (EFI_ERROR (Status)) {
    468     goto DONE;
    469   }
    470 
     449  TimeoutTicks = XhcConvertTimeToTicks (XHC_MICROSECOND_TO_NANOSECOND (Timeout * XHC_1_MILLISECOND));
     450  ElapsedTicks = 0;
     451  CurrentTick  = GetPerformanceCounter ();
    471452  do {
    472453    if (XHC_REG_BIT_IS_SET (Xhc, Offset, Bit) == WaitToSet) {
    473       Status = EFI_SUCCESS;
    474       goto DONE;
     454      return EFI_SUCCESS;
    475455    }
    476456
    477457    gBS->Stall (XHC_1_MICROSECOND);
    478   } while (EFI_ERROR (gBS->CheckEvent (TimeoutEvent)));
    479 
    480   Status = EFI_TIMEOUT;
    481 
    482 DONE:
    483   if (TimeoutEvent != NULL) {
    484     gBS->CloseEvent (TimeoutEvent);
    485   }
    486 
    487   return Status;
     458    TicksDelta = XhcGetElapsedTicks (&CurrentTick);
     459    // Ensure that ElapsedTicks is always incremented to avoid indefinite hangs
     460    if (TicksDelta == 0) {
     461      TicksDelta = XhcConvertTimeToTicks (XHC_MICROSECOND_TO_NANOSECOND (XHC_1_MICROSECOND));
     462    }
     463
     464    ElapsedTicks += TicksDelta;
     465  } while (ElapsedTicks < TimeoutTicks);
     466
     467  return EFI_TIMEOUT;
    488468}
    489469
     
    885865    // The below is a workaround to solve such problem.
    886866    //
    887     gBS->Stall (XHC_1_MILLISECOND);
     867    gBS->Stall (PcdGet16 (PcdDelayXhciHCReset));
    888868    Status = XhcWaitOpRegBit (Xhc, XHC_USBCMD_OFFSET, XHC_USBCMD_RESET, FALSE, Timeout);
    889869
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.c

    r101291 r105670  
    33  XHCI transfer scheduling routines.
    44
     5(C) Copyright 2023 Hewlett Packard Enterprise Development LP<BR>
    56Copyright (c) 2011 - 2020, Intel Corporation. All rights reserved.<BR>
    67Copyright (c) Microsoft Corporation.<BR>
     
    589590  // So divide it to two 32-bytes width register access.
    590591  //
    591   DcbaaPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Dcbaa, Entries);
     592  DcbaaPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Dcbaa, Entries, TRUE);
    592593  XhcWriteOpReg (Xhc, XHC_DCBAAP_OFFSET, XHC_LOW_32BIT (DcbaaPhy));
    593594  XhcWriteOpReg (Xhc, XHC_DCBAAP_OFFSET + 4, XHC_HIGH_32BIT (DcbaaPhy));
     
    608609  //
    609610  CmdRing    = (UINT64)(UINTN)Xhc->CmdRing.RingSeg0;
    610   CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, (VOID *)(UINTN)CmdRing, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER);
     611  CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, (VOID *)(UINTN)CmdRing, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER, TRUE);
    611612  ASSERT ((CmdRingPhy & 0x3F) == 0);
    612613  CmdRingPhy |= XHC_CRCR_RCS;
     
    810811  EventRing->EventRingEnqueue = (TRB_TEMPLATE *)EventRing->EventRingSeg0;
    811812
    812   DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size);
     813  DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size, TRUE);
    813814
    814815  //
     
    830831  ERSTBase->RingTrbSize = EVENT_RING_TRB_NUMBER;
    831832
    832   ERSTPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, ERSTBase, Size);
     833  ERSTPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, ERSTBase, Size, TRUE);
    833834
    834835  //
     
    914915  EndTrb        = (LINK_TRB *)((UINTN)Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1));
    915916  EndTrb->Type  = TRB_TYPE_LINK;
    916   PhyAddr       = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum);
     917  PhyAddr       = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum, TRUE);
    917918  EndTrb->PtrLo = XHC_LOW_32BIT (PhyAddr);
    918919  EndTrb->PtrHi = XHC_HIGH_32BIT (PhyAddr);
     
    10461047      LinkTrb    = (LINK_TRB *)CheckedTrb;
    10471048      PhyAddr    = (EFI_PHYSICAL_ADDRESS)(LinkTrb->PtrLo | LShiftU64 ((UINT64)LinkTrb->PtrHi, 32));
    1048       CheckedTrb = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE));
     1049      CheckedTrb = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE), FALSE);
    10491050      ASSERT (CheckedTrb == Urb->Ring->RingSeg0);
    10501051    }
     
    11551156    //
    11561157    PhyAddr = (EFI_PHYSICAL_ADDRESS)(EvtTrb->TRBPtrLo | LShiftU64 ((UINT64)EvtTrb->TRBPtrHi, 32));
    1157     TRBPtr  = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE));
     1158    TRBPtr  = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE), FALSE);
    11581159
    11591160    //
     
    11921193        goto EXIT;
    11931194
     1195      //
     1196      // Based on XHCI spec 4.8.3, software should do the reset endpoint while USB Transaction occur.
     1197      //
    11941198      case TRB_COMPLETION_USB_TRANSACTION_ERROR:
    1195         CheckedUrb->Result  |= EFI_USB_ERR_TIMEOUT;
     1199        CheckedUrb->Result  |= EDKII_USB_ERR_TRANSACTION;
    11961200        CheckedUrb->Finished = TRUE;
    11971201        DEBUG ((DEBUG_ERROR, "XhcCheckUrbResult: TRANSACTION_ERROR! Completecode = %x\n", EvtTrb->Completecode));
     
    12601264  XhcDequeue = (UINT64)(LShiftU64 ((UINT64)High, 32) | Low);
    12611265
    1262   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE));
     1266  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE), FALSE);
    12631267
    12641268  if ((XhcDequeue & (~0x0F)) != (PhyAddr & (~0x0F))) {
     
    12771281  Execute the transfer by polling the URB. This is a synchronous operation.
    12781282
    1279   @param  Xhc                    The XHCI Instance.
    1280   @param  CmdTransfer            The executed URB is for cmd transfer or not.
    1281   @param  Urb                    The URB to execute.
    1282   @param  Timeout                The time to wait before abort, in millisecond.
    1283 
    1284   @return EFI_DEVICE_ERROR       The transfer failed due to transfer error.
    1285   @return EFI_TIMEOUT            The transfer failed due to time out.
    1286   @return EFI_SUCCESS            The transfer finished OK.
    1287   @retval EFI_OUT_OF_RESOURCES   Memory for the timer event could not be allocated.
     1283  @param  Xhc               The XHCI Instance.
     1284  @param  CmdTransfer       The executed URB is for cmd transfer or not.
     1285  @param  Urb               The URB to execute.
     1286  @param  Timeout           The time to wait before abort, in millisecond.
     1287
     1288  @return EFI_DEVICE_ERROR  The transfer failed due to transfer error.
     1289  @return EFI_TIMEOUT       The transfer failed due to time out.
     1290  @return EFI_SUCCESS       The transfer finished OK.
    12881291
    12891292**/
     
    13001303  UINT8       Dci;
    13011304  BOOLEAN     Finished;
    1302   EFI_EVENT   TimeoutEvent;
     1305  UINT64      TimeoutTicks;
     1306  UINT64      ElapsedTicks;
     1307  UINT64      TicksDelta;
     1308  UINT64      CurrentTick;
    13031309  BOOLEAN     IndefiniteTimeout;
    13041310
    13051311  Status            = EFI_SUCCESS;
    13061312  Finished          = FALSE;
    1307   TimeoutEvent      = NULL;
    13081313  IndefiniteTimeout = FALSE;
    13091314
     
    13231328  if (Timeout == 0) {
    13241329    IndefiniteTimeout = TRUE;
    1325     goto RINGDOORBELL;
    1326   }
    1327 
    1328   Status = gBS->CreateEvent (
    1329                   EVT_TIMER,
    1330                   TPL_CALLBACK,
    1331                   NULL,
    1332                   NULL,
    1333                   &TimeoutEvent
    1334                   );
    1335 
    1336   if (EFI_ERROR (Status)) {
    1337     goto DONE;
    1338   }
    1339 
    1340   Status = gBS->SetTimer (
    1341                   TimeoutEvent,
    1342                   TimerRelative,
    1343                   EFI_TIMER_PERIOD_MILLISECONDS (Timeout)
    1344                   );
    1345 
    1346   if (EFI_ERROR (Status)) {
    1347     goto DONE;
    1348   }
    1349 
    1350 RINGDOORBELL:
     1330  }
     1331
    13511332  XhcRingDoorBell (Xhc, SlotId, Dci);
     1333
     1334  TimeoutTicks = XhcConvertTimeToTicks (
     1335                   XHC_MICROSECOND_TO_NANOSECOND (
     1336                     Timeout * XHC_1_MILLISECOND
     1337                     )
     1338                   );
     1339  ElapsedTicks = 0;
     1340  CurrentTick  = GetPerformanceCounter ();
    13521341
    13531342  do {
     
    13581347
    13591348    gBS->Stall (XHC_1_MICROSECOND);
    1360   } while (IndefiniteTimeout || EFI_ERROR (gBS->CheckEvent (TimeoutEvent)));
    1361 
    1362 DONE:
    1363   if (EFI_ERROR (Status)) {
    1364     Urb->Result = EFI_USB_ERR_NOTEXECUTE;
    1365   } else if (!Finished) {
     1349    TicksDelta = XhcGetElapsedTicks (&CurrentTick);
     1350    // Ensure that ElapsedTicks is always incremented to avoid indefinite hangs
     1351    if (TicksDelta == 0) {
     1352      TicksDelta = XhcConvertTimeToTicks (XHC_MICROSECOND_TO_NANOSECOND (XHC_1_MICROSECOND));
     1353    }
     1354
     1355    ElapsedTicks += TicksDelta;
     1356  } while (IndefiniteTimeout || ElapsedTicks < TimeoutTicks);
     1357
     1358  if (!Finished) {
    13661359    Urb->Result = EFI_USB_ERR_TIMEOUT;
    13671360    Status      = EFI_TIMEOUT;
    13681361  } else if (Urb->Result != EFI_USB_NOERROR) {
    13691362    Status = EFI_DEVICE_ERROR;
    1370   }
    1371 
    1372   if (TimeoutEvent != NULL) {
    1373     gBS->CloseEvent (TimeoutEvent);
    13741363  }
    13751364
     
    21232112
    21242113/**
     2114  Set Command abort
     2115
     2116  @param  Xhc           The XHCI Instance.
     2117  @param  SlotId        The slot id to be disabled.
     2118
     2119**/
     2120VOID
     2121XhcCmdRingCmdAbort (
     2122  IN USB_XHCI_INSTANCE  *Xhc,
     2123  IN UINT8              SlotId
     2124  )
     2125{
     2126  //
     2127  // Set XHC_CRCR_CA bit in XHC_CRCR_OFFSET to abort command.
     2128  //
     2129  DEBUG ((DEBUG_INFO, "Command Ring Control set Command Abort, SlotId: %d\n", SlotId));
     2130  XhcSetOpRegBit (Xhc, XHC_CRCR_OFFSET, XHC_CRCR_CA);
     2131}
     2132
     2133/**
    21252134  Assign and initialize the device slot for a new device.
    21262135
     
    22812290              Xhc->MemPool,
    22822291              ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0,
    2283               sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     2292              sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     2293              TRUE
    22842294              );
    22852295  InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0;
     
    22992309  //    a pointer to the Output Device Context data structure (6.2.1).
    23002310  //
    2301   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT));
     2311  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT), TRUE);
    23022312  //
    23032313  // Fill DCBAA with PCI device address
     
    23142324  gBS->Stall (XHC_RESET_RECOVERY_DELAY);
    23152325  ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr));
    2316   PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT));
     2326  PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT), TRUE);
    23172327  CmdTrbAddr.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    23182328  CmdTrbAddr.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    23322342  } else {
    23332343    DEBUG ((DEBUG_ERROR, "    Slot %d address not assigned successfully. Status = %r\n", SlotId, Status));
     2344    //
     2345    // Software may abort the execution of Address Device Command when command failed
     2346    // due to timeout by following XHCI spec. 4.6.1.2.
     2347    //
     2348    if (Status == EFI_TIMEOUT) {
     2349      XhcCmdRingCmdAbort (Xhc, SlotId);
     2350    }
     2351
    23342352    XhcDisableSlotCmd (Xhc, SlotId);
    23352353  }
     
    24972515              Xhc->MemPool,
    24982516              ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0,
    2499               sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     2517              sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     2518              TRUE
    25002519              );
    25012520  InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0;
     
    25152534  //    a pointer to the Output Device Context data structure (6.2.1).
    25162535  //
    2517   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT_64));
     2536  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT_64), TRUE);
    25182537  //
    25192538  // Fill DCBAA with PCI device address
     
    25302549  gBS->Stall (XHC_RESET_RECOVERY_DELAY);
    25312550  ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr));
    2532   PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64));
     2551  PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    25332552  CmdTrbAddr.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    25342553  CmdTrbAddr.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    25482567  } else {
    25492568    DEBUG ((DEBUG_ERROR, "    Slot %d address not assigned successfully. Status = %r\n", SlotId, Status));
     2569    //
     2570    // Software may abort the execution of Address Device Command when command failed
     2571    // due to timeout by following XHCI spec. 4.6.1.2.
     2572    //
     2573    if (Status == EFI_TIMEOUT) {
     2574      XhcCmdRingCmdAbort (Xhc, SlotId);
     2575    }
     2576
    25502577    XhcDisableSlotCmd64 (Xhc, SlotId);
    25512578  }
     
    29652992                Xhc->MemPool,
    29662993                ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0,
    2967                 sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     2994                sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     2995                TRUE
    29682996                );
    29692997    PhyAddr                      &= ~((EFI_PHYSICAL_ADDRESS)0x0F);
     
    31673195                Xhc->MemPool,
    31683196                ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0,
    3169                 sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     3197                sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     3198                TRUE
    31703199                );
    31713200    PhyAddr                      &= ~((EFI_PHYSICAL_ADDRESS)0x0F);
     
    32493278  //
    32503279  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    3251   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     3280  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    32523281  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    32533282  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    33403369  //
    33413370  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    3342   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     3371  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    33433372  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    33443373  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    35143543  //
    35153544  ZeroMem (&CmdSetTRDeq, sizeof (CmdSetTRDeq));
    3516   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER));
     3545  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER), FALSE);
    35173546  CmdSetTRDeq.PtrLo    = XHC_LOW_32BIT (PhyAddr) | Urb->Ring->RingPCS;
    35183547  CmdSetTRDeq.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    37143743    //
    37153744    ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    3716     PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     3745    PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    37173746    CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    37183747    CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    39203949    //
    39213950    ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    3922     PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     3951    PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    39233952    CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    39243953    CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    39874016
    39884017  ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu));
    3989   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     4018  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    39904019  CmdTrbEvalu.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    39914020  CmdTrbEvalu.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    40484077
    40494078  ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu));
    4050   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     4079  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    40514080  CmdTrbEvalu.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    40524081  CmdTrbEvalu.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    41174146
    41184147  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    4119   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     4148  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    41204149  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    41214150  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    41864215
    41874216  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    4188   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     4217  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    41894218  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    41904219  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciDxe/XhciSched.h

    r99404 r105670  
    8080
    8181//
     82// USB Transfer Results Internal Definition
     83// Based on XHCI spec 4.8.3, software should do the reset endpoint while USB Transaction occur.
     84// Add the error code for USB Transaction error since UEFI spec don't have the related definition.
     85//
     86#define EDKII_USB_ERR_TRANSACTION  0x200
     87
     88//
    8289// The topology string used to present usb device location
    8390//
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.c

    r99404 r105670  
    191191  @param  Mem           The pointer to host memory.
    192192  @param  Size          The size of the memory region.
     193  @param  Alignment     Alignment the size to USBHC_MEM_UNIT bytes.
    193194
    194195  @return               The pci memory address
     
    199200  IN USBHC_MEM_POOL  *Pool,
    200201  IN VOID            *Mem,
    201   IN UINTN           Size
     202  IN UINTN           Size,
     203  IN BOOLEAN         Alignment
    202204  )
    203205{
     
    208210  UINTN                 Offset;
    209211
    210   Head      = Pool->Head;
    211   AllocSize = USBHC_MEM_ROUND (Size);
     212  Head = Pool->Head;
     213  if (Alignment) {
     214    AllocSize = USBHC_MEM_ROUND (Size);
     215  } else {
     216    AllocSize = Size;
     217  }
    212218
    213219  if (Mem == NULL) {
     
    240246  @param  Mem           The pointer to pci memory.
    241247  @param  Size          The size of the memory region.
     248  @param  Alignment     Alignment the size to USBHC_MEM_UNIT bytes.
    242249
    243250  @return               The host memory address
     
    248255  IN USBHC_MEM_POOL  *Pool,
    249256  IN VOID            *Mem,
    250   IN UINTN           Size
     257  IN UINTN           Size,
     258  IN BOOLEAN         Alignment
    251259  )
    252260{
     
    257265  UINTN                 Offset;
    258266
    259   Head      = Pool->Head;
    260   AllocSize = USBHC_MEM_ROUND (Size);
     267  Head = Pool->Head;
     268  if (Alignment) {
     269    AllocSize = USBHC_MEM_ROUND (Size);
     270  } else {
     271    AllocSize = Size;
     272  }
    261273
    262274  if (Mem == NULL) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciPei/UsbHcMem.h

    r99404 r105670  
    6969  @param  Mem           The pointer to host memory.
    7070  @param  Size          The size of the memory region.
     71  @param  Alignment     Alignment the size to USBHC_MEM_UNIT bytes.
    7172
    7273  @return               The pci memory address
     
    7778  IN USBHC_MEM_POOL  *Pool,
    7879  IN VOID            *Mem,
    79   IN UINTN           Size
     80  IN UINTN           Size,
     81  IN BOOLEAN         Alignment
    8082  );
    8183
     
    8688  @param  Mem           The pointer to pci memory.
    8789  @param  Size          The size of the memory region.
     90  @param  Alignment     Alignment the size to USBHC_MEM_UNIT bytes.
    8891
    8992  @return               The host memory address
     
    9497  IN USBHC_MEM_POOL  *Pool,
    9598  IN VOID            *Mem,
    96   IN UINTN           Size
     99  IN UINTN           Size,
     100  IN BOOLEAN         Alignment
    97101  );
    98102
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Pci/XhciPei/XhciSched.c

    r99404 r105670  
    676676    //
    677677    PhyAddr = (EFI_PHYSICAL_ADDRESS)(EvtTrb->TRBPtrLo | LShiftU64 ((UINT64)EvtTrb->TRBPtrHi, 32));
    678     TRBPtr  = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE));
     678    TRBPtr  = (TRB_TEMPLATE *)(UINTN)UsbHcGetHostAddrForPciAddr (Xhc->MemPool, (VOID *)(UINTN)PhyAddr, sizeof (TRB_TEMPLATE), FALSE);
    679679
    680680    //
     
    767767  XhcDequeue = (UINT64)(LShiftU64 ((UINT64)High, 32) | Low);
    768768
    769   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE));
     769  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->EventRing.EventRingDequeue, sizeof (TRB_TEMPLATE), FALSE);
    770770
    771771  if ((XhcDequeue & (~0x0F)) != (PhyAddr & (~0x0F))) {
     
    12141214              Xhc->MemPool,
    12151215              ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0,
    1216               sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     1216              sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     1217              TRUE
    12171218              );
    12181219  InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0;
     
    12321233  //    a pointer to the Output Device Context data structure (6.2.1).
    12331234  //
    1234   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT));
     1235  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT), TRUE);
    12351236  //
    12361237  // Fill DCBAA with PCI device address
     
    12471248  MicroSecondDelay (XHC_RESET_RECOVERY_DELAY);
    12481249  ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr));
    1249   PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT));
     1250  PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT), TRUE);
    12501251  CmdTrbAddr.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    12511252  CmdTrbAddr.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    14281429              Xhc->MemPool,
    14291430              ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[0])->RingSeg0,
    1430               sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     1431              sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     1432              TRUE
    14311433              );
    14321434  InputContext->EP[0].PtrLo = XHC_LOW_32BIT (PhyAddr) | BIT0;
     
    14461448  //    a pointer to the Output Device Context data structure (6.2.1).
    14471449  //
    1448   PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT_64));
     1450  PhyAddr = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, OutputContext, sizeof (DEVICE_CONTEXT_64), TRUE);
    14491451  //
    14501452  // Fill DCBAA with PCI device address
     
    14611463  MicroSecondDelay (XHC_RESET_RECOVERY_DELAY);
    14621464  ZeroMem (&CmdTrbAddr, sizeof (CmdTrbAddr));
    1463   PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64));
     1465  PhyAddr             = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->UsbDevContext[SlotId].InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    14641466  CmdTrbAddr.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    14651467  CmdTrbAddr.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    18831885                  Xhc->MemPool,
    18841886                  ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0,
    1885                   sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     1887                  sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     1888                  TRUE
    18861889                  );
    18871890      PhyAddr                      &= ~((EFI_PHYSICAL_ADDRESS)0x0F);
     
    19021905  //
    19031906  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    1904   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     1907  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    19051908  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    19061909  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    21092112                  Xhc->MemPool,
    21102113                  ((TRANSFER_RING *)(UINTN)Xhc->UsbDevContext[SlotId].EndpointTransferRing[Dci-1])->RingSeg0,
    2111                   sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER
     2114                  sizeof (TRB_TEMPLATE) * TR_RING_TRB_NUMBER,
     2115                  TRUE
    21122116                  );
    21132117
     
    21302134  //
    21312135  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    2132   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     2136  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    21332137  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    21342138  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    21852189
    21862190  ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu));
    2187   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     2191  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    21882192  CmdTrbEvalu.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    21892193  CmdTrbEvalu.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    22402244
    22412245  ZeroMem (&CmdTrbEvalu, sizeof (CmdTrbEvalu));
    2242   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     2246  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    22432247  CmdTrbEvalu.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    22442248  CmdTrbEvalu.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    23092313
    23102314  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    2311   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT));
     2315  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT), TRUE);
    23122316  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    23132317  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    23782382
    23792383  ZeroMem (&CmdTrbCfgEP, sizeof (CmdTrbCfgEP));
    2380   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64));
     2384  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, InputContext, sizeof (INPUT_CONTEXT_64), TRUE);
    23812385  CmdTrbCfgEP.PtrLo    = XHC_LOW_32BIT (PhyAddr);
    23822386  CmdTrbCfgEP.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    25232527  //
    25242528  ZeroMem (&CmdSetTRDeq, sizeof (CmdSetTRDeq));
    2525   PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER));
     2529  PhyAddr              = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Urb->Ring->RingEnqueue, sizeof (CMD_SET_TR_DEQ_POINTER), FALSE);
    25262530  CmdSetTRDeq.PtrLo    = XHC_LOW_32BIT (PhyAddr) | Urb->Ring->RingPCS;
    25272531  CmdSetTRDeq.PtrHi    = XHC_HIGH_32BIT (PhyAddr);
     
    26832687  ZeroMem (Buf, Size);
    26842688
    2685   DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size);
     2689  DequeuePhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size, TRUE);
    26862690
    26872691  EventRing->EventRingSeg0    = Buf;
     
    27082712  ERSTBase->RingTrbSize = EVENT_RING_TRB_NUMBER;
    27092713
    2710   ERSTPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size);
     2714  ERSTPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, Size, TRUE);
    27112715
    27122716  //
     
    28562860  EndTrb        = (LINK_TRB *)((UINTN)Buf + sizeof (TRB_TEMPLATE) * (TrbNum - 1));
    28572861  EndTrb->Type  = TRB_TYPE_LINK;
    2858   PhyAddr       = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum);
     2862  PhyAddr       = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Buf, sizeof (TRB_TEMPLATE) * TrbNum, TRUE);
    28592863  EndTrb->PtrLo = XHC_LOW_32BIT (PhyAddr);
    28602864  EndTrb->PtrHi = XHC_HIGH_32BIT (PhyAddr);
     
    29892993  // So divide it to two 32-bytes width register access.
    29902994  //
    2991   DcbaaPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Dcbaa, Size);
     2995  DcbaaPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Dcbaa, Size, TRUE);
    29922996  XhcPeiWriteOpReg (Xhc, XHC_DCBAAP_OFFSET, XHC_LOW_32BIT (DcbaaPhy));
    29932997  XhcPeiWriteOpReg (Xhc, XHC_DCBAAP_OFFSET + 4, XHC_HIGH_32BIT (DcbaaPhy));
     
    30073011  // So we set RCS as inverted PCS init value to let Command Ring empty
    30083012  //
    3009   CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->CmdRing.RingSeg0, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER);
     3013  CmdRingPhy = UsbHcGetPciAddrForHostAddr (Xhc->MemPool, Xhc->CmdRing.RingSeg0, sizeof (TRB_TEMPLATE) * CMD_RING_TRB_NUMBER, TRUE);
    30103014  ASSERT ((CmdRingPhy & 0x3F) == 0);
    30113015  CmdRingPhy |= XHC_CRCR_RCS;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.c

    r101291 r105670  
    18981898
    18991899  @param  This                         Indicates a pointer to the calling context.
    1900   @param  MediaId                      ID of the medium to receive data from.
     1900  @param  MediaId                      ID of the medium to receive data from. If there is no
     1901                                       block IO protocol supported by the physical device, the
     1902                                       value of MediaId is undefined.
    19011903  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    19021904                                       of the security protocol command. A Timeout value of 0
     
    21202122
    21212123  @param  This                         Indicates a pointer to the calling context.
    2122   @param  MediaId                      ID of the medium to receive data from.
     2124  @param  MediaId                      ID of the medium to receive data from. If there is no
     2125                                       block IO protocol supported by the physical device, the
     2126                                       value of MediaId is undefined.
    21232127  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    21242128                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Scsi/ScsiDiskDxe/ScsiDisk.h

    r101291 r105670  
    678678
    679679  @param  This                         Indicates a pointer to the calling context.
    680   @param  MediaId                      ID of the medium to receive data from.
     680  @param  MediaId                      ID of the medium to receive data from. If there is no
     681                                       block IO protocol supported by the physical device, the
     682                                       value of MediaId is undefined.
    681683  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    682684                                       of the security protocol command. A Timeout value of 0
     
    752754
    753755  @param  This                         Indicates a pointer to the calling context.
    754   @param  MediaId                      ID of the medium to receive data from.
     756  @param  MediaId                      ID of the medium to receive data from. If there is no
     757                                       block IO protocol supported by the physical device, the
     758                                       value of MediaId is undefined.
    755759  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    756760                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.c

    r99404 r105670  
    12681268
    12691269  @param[in]  This                         Indicates a pointer to the calling context.
    1270   @param[in]  MediaId                      ID of the medium to receive data from.
     1270  @param[in]  MediaId                      ID of the medium to receive data from. If there is no
     1271                                           block IO protocol supported by the physical device, the
     1272                                           value of MediaId is undefined.
    12711273  @param[in]  Timeout                      The timeout, in 100ns units, to use for the execution
    12721274                                           of the security protocol command. A Timeout value of 0
     
    14551457
    14561458  @param  This                         Indicates a pointer to the calling context.
    1457   @param  MediaId                      ID of the medium to receive data from.
     1459  @param  MediaId                      ID of the medium to receive data from. If there is no
     1460                                       block IO protocol supported by the physical device, the
     1461                                       value of MediaId is undefined.
    14581462  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    14591463                                       of the security protocol command. A Timeout value of 0
     
    15561560
    15571561  @param  This                         Indicates a pointer to the calling context.
    1558   @param  MediaId                      ID of the medium to receive data from.
     1562  @param  MediaId                      ID of the medium to receive data from. If there is no
     1563                                       block IO protocol supported by the physical device, the
     1564                                       value of MediaId is undefined.
    15591565  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    15601566                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Sd/EmmcDxe/EmmcBlockIo.h

    r99404 r105670  
    251251
    252252  @param[in]  This                         Indicates a pointer to the calling context.
    253   @param[in]  MediaId                      ID of the medium to receive data from.
     253  @param[in]  MediaId                      ID of the medium to receive data from. If there is no
     254                                           block IO protocol supported by the physical device, the
     255                                           value of MediaId is undefined.
    254256  @param[in]  Timeout                      The timeout, in 100ns units, to use for the execution
    255257                                           of the security protocol command. A Timeout value of 0
     
    338340
    339341  @param  This                         Indicates a pointer to the calling context.
    340   @param  MediaId                      ID of the medium to receive data from.
     342  @param  MediaId                      ID of the medium to receive data from. If there is no
     343                                       block IO protocol supported by the physical device, the
     344                                       value of MediaId is undefined.
    341345  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    342346                                       of the security protocol command. A Timeout value of 0
     
    418422
    419423  @param  This                         Indicates a pointer to the calling context.
    420   @param  MediaId                      ID of the medium to receive data from.
     424  @param  MediaId                      ID of the medium to receive data from. If there is no
     425                                       block IO protocol supported by the physical device, the
     426                                       value of MediaId is undefined.
    421427  @param  Timeout                      The timeout, in 100ns units, to use for the execution
    422428                                       of the security protocol command. A Timeout value of 0
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.c

    r99404 r105670  
    693693  @retval EFI_DEVICE_ERROR     The keystroke information was not returned due to
    694694                               hardware errors.
     695  @retval EFI_UNSUPPORTED      The device does not support the ability to read keystroke data.
    695696
    696697**/
     
    976977                                 hardware errors.
    977978  @retval EFI_INVALID_PARAMETER  KeyData is NULL.
     979  @retval EFI_UNSUPPORTED        The device does not support the ability to read keystroke data.
    978980
    979981**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbKbDxe/EfiKey.h

    r99404 r105670  
    413413  @retval EFI_DEVICE_ERROR     The keystroke information was not returned due to
    414414                               hardware errors.
     415  @retval EFI_UNSUPPORTED      The device does not support the ability to read keystroke data.
    415416
    416417**/
     
    467468                                 hardware errors.
    468469  @retval EFI_INVALID_PARAMETER  KeyData is NULL.
     470  @retval EFI_UNSUPPORTED        The device does not support the ability to read keystroke data.
    469471
    470472**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbNetwork/NetworkCommon/PxeFunction.c

    r101291 r105670  
    830830
    831831    Nic->UsbEth->UsbEthFunDescriptor (Nic->UsbEth, &UsbEthFunDescriptor);
    832     if ((UsbEthFunDescriptor.NumberMcFilters << 1) == 0) {
     832    if ((UsbEthFunDescriptor.NumberMcFilters & MAC_FILTERS_MASK) == 0) {
    833833      Nic->RxFilter |= PXE_OPFLAGS_RECEIVE_FILTER_ALL_MULTICAST;
    834834      Nic->UsbEth->SetUsbEthPacketFilter (Nic->UsbEth, Nic->RxFilter);
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcEcm/UsbEcmFunction.c

    r101291 r105670  
    629629  }
    630630
    631   if ((UsbEthFunDescriptor.NumberMcFilters << 1) == 0) {
     631  if ((UsbEthFunDescriptor.NumberMcFilters & MAC_FILTERS_MASK) == 0) {
    632632    return EFI_UNSUPPORTED;
    633633  }
     
    770770  Count = sizeof (gTable)/sizeof (gTable[0]);
    771771
    772   for (Index = 0; (gTable[Index].Src != 0) && (Index < Count); Index++) {
     772  for (Index = 0; (Index < Count) && (gTable[Index].Src != 0); Index++) {
    773773    if (gTable[Index].Src & Value) {
    774774      *CdcFilter |= gTable[Index].Dst;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbNetwork/UsbCdcNcm/UsbNcmFunction.c

    r101291 r105670  
    715715  }
    716716
    717   if ((UsbEthFunDescriptor.NumberMcFilters << 1) == 0) {
     717  if ((UsbEthFunDescriptor.NumberMcFilters & MAC_FILTERS_MASK) == 0) {
    718718    return EFI_UNSUPPORTED;
    719719  }
     
    856856  Count = sizeof (gTable)/sizeof (gTable[0]);
    857857
    858   for (Index = 0; (gTable[Index].Src != 0) && (Index < Count); Index++) {
     858  for (Index = 0; (Index < Count) && (gTable[Index].Src != 0); Index++) {
    859859    if (gTable[Index].Src & Value) {
    860860      *CdcFilter |= gTable[Index].Dst;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndis.c

    r101291 r105670  
    4141
    4242  // Check specific device/RNDIS and CDC-DATA
    43   if (((InterfaceDescriptor.InterfaceClass == 0x2) &&
    44        (InterfaceDescriptor.InterfaceSubClass == 0x2) &&
    45        (InterfaceDescriptor.InterfaceProtocol == 0xFF)) || \
    46       ((InterfaceDescriptor.InterfaceClass == 0xEF) &&
    47        (InterfaceDescriptor.InterfaceSubClass == 0x4) &&
    48        (InterfaceDescriptor.InterfaceProtocol == 0x1)) || \
    49       ((InterfaceDescriptor.InterfaceClass == 0xA) &&
    50        (InterfaceDescriptor.InterfaceSubClass == 0x0) &&
    51        (InterfaceDescriptor.InterfaceProtocol == 0x00))
     43  if (((InterfaceDescriptor.InterfaceClass == USB_CDC_CLASS) &&
     44       (InterfaceDescriptor.InterfaceSubClass == USB_CDC_ACM_SUBCLASS) &&
     45       (InterfaceDescriptor.InterfaceProtocol == USB_VENDOR_PROTOCOL)) || \
     46      ((InterfaceDescriptor.InterfaceClass == USB_MISC_CLASS) &&
     47       (InterfaceDescriptor.InterfaceSubClass == USB_RNDIS_SUBCLASS) &&
     48       (InterfaceDescriptor.InterfaceProtocol == USB_RNDIS_ETHERNET_PROTOCOL)) || \
     49      ((InterfaceDescriptor.InterfaceClass == USB_CDC_DATA_CLASS) &&
     50       (InterfaceDescriptor.InterfaceSubClass == USB_CDC_DATA_SUBCLASS) &&
     51       (InterfaceDescriptor.InterfaceProtocol == USB_NO_CLASS_PROTOCOL))
    5252      )
    5353  {
     
    8080
    8181  // Check for specific device/RNDIS and CDC-DATA
    82   if (((InterfaceDescriptor.InterfaceClass == 0x2) &&
    83        (InterfaceDescriptor.InterfaceSubClass == 0x2) &&
    84        (InterfaceDescriptor.InterfaceProtocol == 0xFF)) || \
    85       ((InterfaceDescriptor.InterfaceClass == 0xEF) &&
    86        (InterfaceDescriptor.InterfaceSubClass == 0x4) &&
    87        (InterfaceDescriptor.InterfaceProtocol == 0x1))
     82  if (((InterfaceDescriptor.InterfaceClass == USB_CDC_CLASS) &&
     83       (InterfaceDescriptor.InterfaceSubClass == USB_CDC_ACM_SUBCLASS) &&
     84       (InterfaceDescriptor.InterfaceProtocol == USB_VENDOR_PROTOCOL)) || \
     85      ((InterfaceDescriptor.InterfaceClass == USB_MISC_CLASS) &&
     86       (InterfaceDescriptor.InterfaceSubClass == USB_RNDIS_SUBCLASS) &&
     87       (InterfaceDescriptor.InterfaceProtocol == USB_RNDIS_ETHERNET_PROTOCOL))
    8888      )
    8989  {
     
    156156
    157157  // Check for CDC-DATA
    158   if ((InterfaceDescriptor.InterfaceClass == 0xA) &&
    159       (InterfaceDescriptor.InterfaceSubClass == 0x0) &&
    160       (InterfaceDescriptor.InterfaceProtocol == 0x0))
     158  if ((InterfaceDescriptor.InterfaceClass == USB_CDC_DATA_CLASS) &&
     159      (InterfaceDescriptor.InterfaceSubClass == USB_CDC_DATA_SUBCLASS) &&
     160      (InterfaceDescriptor.InterfaceProtocol == USB_NO_CLASS_PROTOCOL))
    161161  {
    162162    return TRUE;
     
    189189
    190190  // Check for Rndis
    191   if ((InterfaceDescriptor.InterfaceClass == 0x2) &&
    192       (InterfaceDescriptor.InterfaceSubClass == 0x2) &&
    193       (InterfaceDescriptor.InterfaceProtocol == 0xFF))
     191  if ((InterfaceDescriptor.InterfaceClass == USB_CDC_CLASS) &&
     192      (InterfaceDescriptor.InterfaceSubClass == USB_CDC_ACM_SUBCLASS) &&
     193      (InterfaceDescriptor.InterfaceProtocol == USB_VENDOR_PROTOCOL))
    194194  {
    195195    return TRUE;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Bus/Usb/UsbNetwork/UsbRndis/UsbRndisFunction.c

    r101291 r105670  
    662662  }
    663663
    664   if ((UsbEthFunDescriptor.NumberMcFilters << 1) == 0) {
     664  if ((UsbEthFunDescriptor.NumberMcFilters & MAC_FILTERS_MASK) == 0) {
    665665    return EFI_UNSUPPORTED;
    666666  }
     
    804804  Count = sizeof (gTable)/sizeof (gTable[0]);
    805805
    806   for (Index = 0; (gTable[Index].Src != 0) && (Index < Count); Index++) {
     806  for (Index = 0; (Index < Count) && (gTable[Index].Src != 0); Index++) {
    807807    if (gTable[Index].Src & Value) {
    808808      *CdcFilter |= gTable[Index].Dst;
     
    857857
    858858    Nic->UsbEth->UsbEthFunDescriptor (Nic->UsbEth, &UsbEthFunDescriptor);
    859     if ((UsbEthFunDescriptor.NumberMcFilters << 1) == 0) {
     859    if ((UsbEthFunDescriptor.NumberMcFilters & MAC_FILTERS_MASK) == 0) {
    860860      Nic->RxFilter |= PXE_OPFLAGS_RECEIVE_FILTER_ALL_MULTICAST;
    861861      DEBUG ((DEBUG_INFO, "SetUsbEthPacketFilter Nic %lx Nic->UsbEth %lx ", Nic, Nic->UsbEth));
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/DxeMain.h

    r101291 r105670  
    229229          CR(a, LOADED_IMAGE_PRIVATE_DATA, Info, LOADED_IMAGE_PRIVATE_DATA_SIGNATURE)
    230230
    231 #define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE  SIGNATURE_32 ('I','P','R','C')
    232 
    233 typedef struct {
    234   UINT32                  Signature;
    235   LIST_ENTRY              Link;
    236   EFI_PHYSICAL_ADDRESS    CodeSegmentBase;
    237   UINT64                  CodeSegmentSize;
    238 } IMAGE_PROPERTIES_RECORD_CODE_SECTION;
    239 
    240 #define IMAGE_PROPERTIES_RECORD_SIGNATURE  SIGNATURE_32 ('I','P','R','D')
    241 
    242 typedef struct {
    243   UINT32                  Signature;
    244   LIST_ENTRY              Link;
    245   EFI_PHYSICAL_ADDRESS    ImageBase;
    246   UINT64                  ImageSize;
    247   UINTN                   CodeSegmentCount;
    248   LIST_ENTRY              CodeSegmentList;
    249 } IMAGE_PROPERTIES_RECORD;
    250 
    251231//
    252232// DXE Core Global Variables
     
    296276CoreInitializePool (
    297277  VOID
     278  );
     279
     280VOID
     281CoreSetMemoryTypeInformationRange (
     282  IN EFI_PHYSICAL_ADDRESS  Start,
     283  IN UINT64                Length
    298284  );
    299285
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/DxeMain.inf

    r99404 r105670  
    9595  CpuExceptionHandlerLib
    9696  PcdLib
     97  ImagePropertiesRecordLib
    9798
    9899[Guids]
     
    188189  gEfiMdeModulePkgTokenSpaceGuid.PcdCpuStackGuard                           ## CONSUMES
    189190  gEfiMdeModulePkgTokenSpaceGuid.PcdFwVolDxeMaxEncapsulationDepth           ## CONSUMES
     191  gEfiMdeModulePkgTokenSpaceGuid.PcdImageLargeAddressLoad                   ## CONSUMES
    190192
    191193# [Hob]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/DxeMain/DxeMain.c

    r101291 r105670  
    278278
    279279  //
     280  // Start the Image Services.
     281  //
     282  Status = CoreInitializeImageServices (HobStart);
     283  ASSERT_EFI_ERROR (Status);
     284
     285  //
     286  // Initialize the Global Coherency Domain Services
     287  //
     288  Status = CoreInitializeGcdServices (&HobStart, MemoryBaseAddress, MemoryLength);
     289  ASSERT_EFI_ERROR (Status);
     290
     291  //
    280292  // Allocate the EFI System Table and EFI Runtime Service Table from EfiRuntimeServicesData
    281293  // Use the templates to initialize the contents of the EFI System Table and EFI Runtime Services Table
     
    290302
    291303  //
    292   // Start the Image Services.
    293   //
    294   Status = CoreInitializeImageServices (HobStart);
    295   ASSERT_EFI_ERROR (Status);
    296 
    297   //
    298   // Initialize the Global Coherency Domain Services
    299   //
    300   Status = CoreInitializeGcdServices (&HobStart, MemoryBaseAddress, MemoryLength);
    301   ASSERT_EFI_ERROR (Status);
     304  // Update DXE Core Loaded Image Protocol with allocated UEFI System Table
     305  //
     306  gDxeCoreLoadedImage->SystemTable = gDxeCoreST;
    302307
    303308  //
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/FwVol/FwVol.c

    r99404 r105670  
    660660      FvDevice = AllocateCopyPool (sizeof (FV_DEVICE), &mFvDevice);
    661661      if (FvDevice == NULL) {
     662        CoreFreePool (FwVolHeader);
    662663        return;
    663664      }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/FwVolBlock/FwVolBlock.c

    r99404 r105670  
    552552    FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)AllocateCopyPool (sizeof (FV_MEMMAP_DEVICE_PATH), &mFvMemmapDevicePathTemplate);
    553553    if (FvbDev->DevicePath == NULL) {
     554      FreePool (FvbDev->LbaCache);
    554555      FreePool (FvbDev);
    555556      return EFI_OUT_OF_RESOURCES;
     
    564565    FvbDev->DevicePath = (EFI_DEVICE_PATH_PROTOCOL *)AllocateCopyPool (sizeof (FV_PIWG_DEVICE_PATH), &mFvPIWGDevicePathTemplate);
    565566    if (FvbDev->DevicePath == NULL) {
     567      FreePool (FvbDev->LbaCache);
    566568      FreePool (FvbDev);
    567569      return EFI_OUT_OF_RESOURCES;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Gcd/Gcd.c

    r99404 r105670  
    99**/
    1010
    11 #include <Pi/PrePiDxeCis.h>
    12 #include <Pi/PrePiHob.h>
     11#include <Pi/PiDxeCis.h>
     12#include <Pi/PiHob.h>
    1313#include "DxeMain.h"
    1414#include "Gcd.h"
     
    106106  "PersisMem",  // EfiGcdMemoryTypePersistent
    107107  "MoreRelia",  // EfiGcdMemoryTypeMoreReliable
    108   "Unaccepte",  // EFI_GCD_MEMORY_TYPE_UNACCEPTED
     108  "Unaccepte",  // EfiGcdMemoryTypeUnaccepted
    109109  "Unknown  "   // EfiGcdMemoryTypeMaximum
    110110};
     
    22392239  EFI_HOB_RESOURCE_DESCRIPTOR  *ResourceHob;
    22402240  EFI_HOB_RESOURCE_DESCRIPTOR  *PhitResourceHob;
     2241  EFI_HOB_RESOURCE_DESCRIPTOR  *MemoryTypeInformationResourceHob;
     2242  UINTN                        Count;
    22412243  EFI_PHYSICAL_ADDRESS         BaseAddress;
    22422244  UINT64                       Length;
     
    22902292  // See if a Memory Type Information HOB is available
    22912293  //
    2292   GuidHob = GetFirstGuidHob (&gEfiMemoryTypeInformationGuid);
     2294  MemoryTypeInformationResourceHob = NULL;
     2295  GuidHob                          = GetFirstGuidHob (&gEfiMemoryTypeInformationGuid);
    22932296  if (GuidHob != NULL) {
    22942297    EfiMemoryTypeInformation = GET_GUID_HOB_DATA (GuidHob);
     
    22962299    if ((EfiMemoryTypeInformation != NULL) && (DataSize > 0) && (DataSize <= (EfiMaxMemoryType + 1) * sizeof (EFI_MEMORY_TYPE_INFORMATION))) {
    22972300      CopyMem (&gMemoryTypeInformation, EfiMemoryTypeInformation, DataSize);
     2301
     2302      //
     2303      // Look for Resource Descriptor HOB with a ResourceType of System Memory
     2304      // and an Owner GUID of gEfiMemoryTypeInformationGuid. If more than 1 is
     2305      // found, then set MemoryTypeInformationResourceHob to NULL.
     2306      //
     2307      Count = 0;
     2308      for (Hob.Raw = *HobStart; !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) {
     2309        if (GET_HOB_TYPE (Hob) != EFI_HOB_TYPE_RESOURCE_DESCRIPTOR) {
     2310          continue;
     2311        }
     2312
     2313        ResourceHob = Hob.ResourceDescriptor;
     2314        if (!CompareGuid (&ResourceHob->Owner, &gEfiMemoryTypeInformationGuid)) {
     2315          continue;
     2316        }
     2317
     2318        Count++;
     2319        if (ResourceHob->ResourceType != EFI_RESOURCE_SYSTEM_MEMORY) {
     2320          continue;
     2321        }
     2322
     2323        if ((ResourceHob->ResourceAttribute & MEMORY_ATTRIBUTE_MASK) != TESTED_MEMORY_ATTRIBUTES) {
     2324          continue;
     2325        }
     2326
     2327        if (ResourceHob->ResourceLength >= CalculateTotalMemoryBinSizeNeeded ()) {
     2328          MemoryTypeInformationResourceHob = ResourceHob;
     2329        }
     2330      }
     2331
     2332      if (Count > 1) {
     2333        MemoryTypeInformationResourceHob = NULL;
     2334      }
    22982335    }
    22992336  }
     
    23442381    PhitResourceHob = ResourceHob;
    23452382    Found           = TRUE;
     2383
     2384    //
     2385    // If a Memory Type Information Resource HOB was found and is the same
     2386    // Resource HOB that describes the PHIT HOB, then ignore the Memory Type
     2387    // Information Resource HOB.
     2388    //
     2389    if (MemoryTypeInformationResourceHob == PhitResourceHob) {
     2390      MemoryTypeInformationResourceHob = NULL;
     2391    }
    23462392
    23472393    //
     
    23882434    //
    23892435    // Search all the resource descriptor HOBs from the highest possible addresses down for a memory
    2390     // region that is big enough to initialize the DXE core.  Always skip the PHIT Resource HOB.
    2391     // The max address must be within the physically addressible range for the processor.
     2436    // region that is big enough to initialize the DXE core.  Always skip the PHIT Resource HOB
     2437    // and the Memory Type Information Resource HOB. The max address must be within the physically
     2438    // addressable range for the processor.
    23922439    //
    23932440    HighAddress = MAX_ALLOC_ADDRESS;
     
    23972444      //
    23982445      if (Hob.ResourceDescriptor == PhitResourceHob) {
     2446        continue;
     2447      }
     2448
     2449      //
     2450      // Skip the Resource Descriptor HOB that contains Memory Type Information bins
     2451      //
     2452      if (Hob.ResourceDescriptor == MemoryTypeInformationResourceHob) {
    23992453        continue;
    24002454      }
     
    24652519  } else {
    24662520    Capabilities = CoreConvertResourceDescriptorHobAttributesToCapabilities (EfiGcdMemoryTypeSystemMemory, Attributes);
     2521  }
     2522
     2523  if (MemoryTypeInformationResourceHob != NULL) {
     2524    //
     2525    // If a Memory Type Information Resource HOB was found, then use the address
     2526    // range of the  Memory Type Information Resource HOB as the preferred
     2527    // address range for the Memory Type Information bins.
     2528    //
     2529    CoreSetMemoryTypeInformationRange (
     2530      MemoryTypeInformationResourceHob->PhysicalStart,
     2531      MemoryTypeInformationResourceHob->ResourceLength
     2532      );
    24672533  }
    24682534
     
    26042670          GcdMemoryType = EfiGcdMemoryTypeReserved;
    26052671          break;
    2606         case BZ3937_EFI_RESOURCE_MEMORY_UNACCEPTED:
    2607           GcdMemoryType = EFI_GCD_MEMORY_TYPE_UNACCEPTED;
     2672        case EFI_RESOURCE_MEMORY_UNACCEPTED:
     2673          GcdMemoryType = EfiGcdMemoryTypeUnaccepted;
    26082674          break;
    26092675        case EFI_RESOURCE_IO:
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Hand/DriverSupport.c

    r99404 r105670  
    498498  // Add the Driver Family Override Protocol drivers for ControllerHandle
    499499  //
    500   while (TRUE) {
     500  Status = CoreLocateProtocol (
     501             &gEfiDriverFamilyOverrideProtocolGuid,
     502             NULL,
     503             (VOID **)&DriverFamilyOverride
     504             );
     505  while (!EFI_ERROR (Status) && (DriverFamilyOverride != NULL)) {
    501506    HighestIndex   = DriverBindingHandleCount;
    502507    HighestVersion = 0;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Hand/Handle.c

    r99404 r105670  
    199199
    200200/**
     201  Check if the given device path is already installed.
     202
     203  @param  DevicePath            The given device path
     204
     205  @retval TRUE                  The device path is already installed
     206  @retval FALSE                 The device path is not installed
     207
     208**/
     209BOOLEAN
     210IsDevicePathInstalled (
     211  IN EFI_DEVICE_PATH_PROTOCOL  *DevicePath
     212  )
     213{
     214  UINTN               SourceSize;
     215  UINTN               Size;
     216  BOOLEAN             Found;
     217  LIST_ENTRY          *Link;
     218  PROTOCOL_ENTRY      *ProtEntry;
     219  PROTOCOL_INTERFACE  *Prot;
     220
     221  if (DevicePath == NULL) {
     222    return FALSE;
     223  }
     224
     225  Found      = FALSE;
     226  SourceSize = GetDevicePathSize (DevicePath);
     227  ASSERT (SourceSize >= END_DEVICE_PATH_LENGTH);
     228
     229  CoreAcquireProtocolLock ();
     230  //
     231  // Look up the protocol entry
     232  //
     233  ProtEntry = CoreFindProtocolEntry (&gEfiDevicePathProtocolGuid, FALSE);
     234  if (ProtEntry == NULL) {
     235    goto Done;
     236  }
     237
     238  for (Link = ProtEntry->Protocols.ForwardLink; Link != &ProtEntry->Protocols; Link = Link->ForwardLink) {
     239    //
     240    // Loop on the DevicePathProtocol interfaces
     241    //
     242    Prot = CR (Link, PROTOCOL_INTERFACE, ByProtocol, PROTOCOL_INTERFACE_SIGNATURE);
     243
     244    //
     245    // Check if DevicePath is same as this interface
     246    //
     247    Size = GetDevicePathSize (Prot->Interface);
     248    ASSERT (Size >= END_DEVICE_PATH_LENGTH);
     249    if ((Size == SourceSize) && (CompareMem (DevicePath, Prot->Interface, Size - END_DEVICE_PATH_LENGTH) == 0)) {
     250      Found = TRUE;
     251      break;
     252    }
     253  }
     254
     255Done:
     256  CoreReleaseProtocolLock ();
     257  return Found;
     258}
     259
     260/**
    201261  Removes an event from a register protocol notify list on a protocol.
    202262
     
    511571  )
    512572{
    513   VA_LIST                   Args;
    514   EFI_STATUS                Status;
    515   EFI_GUID                  *Protocol;
    516   VOID                      *Interface;
    517   EFI_TPL                   OldTpl;
    518   UINTN                     Index;
    519   EFI_HANDLE                OldHandle;
    520   EFI_HANDLE                DeviceHandle;
    521   EFI_DEVICE_PATH_PROTOCOL  *DevicePath;
     573  VA_LIST     Args;
     574  EFI_STATUS  Status;
     575  EFI_GUID    *Protocol;
     576  VOID        *Interface;
     577  EFI_TPL     OldTpl;
     578  UINTN       Index;
     579  EFI_HANDLE  OldHandle;
    522580
    523581  if (Handle == NULL) {
     
    549607    // Make sure you are installing on top a device path that has already been added.
    550608    //
    551     if (CompareGuid (Protocol, &gEfiDevicePathProtocolGuid)) {
    552       DeviceHandle = NULL;
    553       DevicePath   = Interface;
    554       Status       = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &DevicePath, &DeviceHandle);
    555       if (!EFI_ERROR (Status) && (DeviceHandle != NULL) && IsDevicePathEnd (DevicePath)) {
    556         Status = EFI_ALREADY_STARTED;
    557         continue;
    558       }
     609    if (CompareGuid (Protocol, &gEfiDevicePathProtocolGuid) &&
     610        IsDevicePathInstalled (Interface))
     611    {
     612      Status = EFI_ALREADY_STARTED;
     613      continue;
    559614    }
    560615
     
    864919
    865920  @param  UserHandle             The handle to obtain the protocol interface on
     921                                 The caller must pass in a valid UserHandle that
     922                                 is checked with CoreValidateHandle().
    866923  @param  Protocol               The GUID of the protocol
    867924
     
    869926
    870927**/
     928STATIC
    871929PROTOCOL_INTERFACE  *
    872930CoreGetProtocolInterface (
     
    875933  )
    876934{
    877   EFI_STATUS          Status;
    878935  PROTOCOL_ENTRY      *ProtEntry;
    879936  PROTOCOL_INTERFACE  *Prot;
    880937  IHANDLE             *Handle;
    881938  LIST_ENTRY          *Link;
    882 
    883   Status = CoreValidateHandle (UserHandle);
    884   if (EFI_ERROR (Status)) {
    885     return NULL;
    886   }
    887939
    888940  Handle = (IHANDLE *)UserHandle;
     
    13391391
    13401392  //
     1393  // Check for invalid UserHandle
     1394  //
     1395  Status = CoreValidateHandle (UserHandle);
     1396  if (EFI_ERROR (Status)) {
     1397    Status = EFI_NOT_FOUND;
     1398    goto Done;
     1399  }
     1400
     1401  //
    13411402  // Look at each protocol interface for a match
    13421403  //
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Hand/Locate.c

    r99404 r105670  
    22  Locate handle functions
    33
    4 Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
     4Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.<BR>
    55SPDX-License-Identifier: BSD-2-Clause-Patent
    66
     
    814814  if (EFI_ERROR (Status)) {
    815815    *NumberHandles = 0;
     816    if (*Buffer != NULL) {
     817      CoreFreePool (*Buffer);
     818      *Buffer = NULL;
     819    }
    816820  }
    817821
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Image/Image.c

    r101291 r105670  
    7878
    7979GLOBAL_REMOVE_IF_UNREFERENCED MACHINE_TYPE_INFO  mMachineTypeInfo[] = {
    80   { EFI_IMAGE_MACHINE_IA32,           L"IA32"    },
    81   { EFI_IMAGE_MACHINE_IA64,           L"IA64"    },
    82   { EFI_IMAGE_MACHINE_X64,            L"X64"     },
    83   { EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM"     },
    84   { EFI_IMAGE_MACHINE_AARCH64,        L"AARCH64" },
    85   { EFI_IMAGE_MACHINE_RISCV64,        L"RISCV64" },
     80  { EFI_IMAGE_MACHINE_IA32,           L"IA32"        },
     81  { EFI_IMAGE_MACHINE_IA64,           L"IA64"        },
     82  { EFI_IMAGE_MACHINE_X64,            L"X64"         },
     83  { EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM"         },
     84  { EFI_IMAGE_MACHINE_AARCH64,        L"AARCH64"     },
     85  { EFI_IMAGE_MACHINE_RISCV64,        L"RISCV64"     },
     86  { EFI_IMAGE_MACHINE_LOONGARCH64,    L"LOONGARCH64" },
    8687};
    8788
     
    219220  Image = &mCorePrivateImage;
    220221
    221   Image->EntryPoint       = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint;
    222   Image->ImageBasePage    = DxeCoreImageBaseAddress;
    223   Image->NumberOfPages    = (UINTN)(EFI_SIZE_TO_PAGES ((UINTN)(DxeCoreImageLength)));
    224   Image->Tpl              = gEfiCurrentTpl;
    225   Image->Info.SystemTable = gDxeCoreST;
    226   Image->Info.ImageBase   = (VOID *)(UINTN)DxeCoreImageBaseAddress;
    227   Image->Info.ImageSize   = DxeCoreImageLength;
     222  Image->EntryPoint     = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint;
     223  Image->ImageBasePage  = DxeCoreImageBaseAddress;
     224  Image->NumberOfPages  = (UINTN)(EFI_SIZE_TO_PAGES ((UINTN)(DxeCoreImageLength)));
     225  Image->Tpl            = gEfiCurrentTpl;
     226  Image->Info.ImageBase = (VOID *)(UINTN)DxeCoreImageBaseAddress;
     227  Image->Info.ImageSize = DxeCoreImageLength;
    228228
    229229  //
     
    681681      }
    682682    } else {
    683       if ((Image->ImageContext.ImageAddress >= 0x100000) || Image->ImageContext.RelocationsStripped) {
     683      if ((PcdGetBool (PcdImageLargeAddressLoad) && ((Image->ImageContext.ImageAddress) >= 0x100000)) ||
     684          Image->ImageContext.RelocationsStripped)
     685      {
    684686        Status = CoreAllocatePages (
    685687                   AllocateAddress,
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Mem/HeapGuard.h

    r101291 r105670  
    470470extern BOOLEAN  mOnGuarding;
    471471
     472//
     473// The heap guard system does not support non-EFI_PAGE_SIZE alignments.
     474// Architectures that require larger RUNTIME_PAGE_ALLOCATION_GRANULARITY
     475// cannot have EfiRuntimeServicesCode, EfiRuntimeServicesData, EfiReservedMemoryType,
     476// and EfiACPIMemoryNVS guarded. OSes do not map guard pages anyway, so this is a
     477// minimal loss. Not guarding prevents alignment mismatches
     478//
     479STATIC_ASSERT (
     480  RUNTIME_PAGE_ALLOCATION_GRANULARITY == EFI_PAGE_SIZE ||
     481  (((FixedPcdGet64 (PcdHeapGuardPageType) & 0x461) == 0) &&
     482   ((FixedPcdGet64 (PcdHeapGuardPoolType) & 0x461) == 0)),
     483  "Unsupported Heap Guard configuration on system with greater than EFI_PAGE_SIZE RUNTIME_PAGE_ALLOCATION_GRANULARITY"
     484  );
     485
    472486#endif
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Mem/Page.c

    r101291 r105670  
    1010#include "Imem.h"
    1111#include "HeapGuard.h"
    12 #include <Pi/PrePiDxeCis.h>
     12#include <Pi/PiDxeCis.h>
    1313
    1414//
     
    7171
    7272EFI_MEMORY_TYPE_INFORMATION  gMemoryTypeInformation[EfiMaxMemoryType + 1] = {
    73   { EfiReservedMemoryType,          0 },
    74   { EfiLoaderCode,                  0 },
    75   { EfiLoaderData,                  0 },
    76   { EfiBootServicesCode,            0 },
    77   { EfiBootServicesData,            0 },
    78   { EfiRuntimeServicesCode,         0 },
    79   { EfiRuntimeServicesData,         0 },
    80   { EfiConventionalMemory,          0 },
    81   { EfiUnusableMemory,              0 },
    82   { EfiACPIReclaimMemory,           0 },
    83   { EfiACPIMemoryNVS,               0 },
    84   { EfiMemoryMappedIO,              0 },
    85   { EfiMemoryMappedIOPortSpace,     0 },
    86   { EfiPalCode,                     0 },
    87   { EfiPersistentMemory,            0 },
    88   { EFI_GCD_MEMORY_TYPE_UNACCEPTED, 0 },
    89   { EfiMaxMemoryType,               0 }
     73  { EfiReservedMemoryType,      0 },
     74  { EfiLoaderCode,              0 },
     75  { EfiLoaderData,              0 },
     76  { EfiBootServicesCode,        0 },
     77  { EfiBootServicesData,        0 },
     78  { EfiRuntimeServicesCode,     0 },
     79  { EfiRuntimeServicesData,     0 },
     80  { EfiConventionalMemory,      0 },
     81  { EfiUnusableMemory,          0 },
     82  { EfiACPIReclaimMemory,       0 },
     83  { EfiACPIMemoryNVS,           0 },
     84  { EfiMemoryMappedIO,          0 },
     85  { EfiMemoryMappedIOPortSpace, 0 },
     86  { EfiPalCode,                 0 },
     87  { EfiPersistentMemory,        0 },
     88  { EfiGcdMemoryTypeUnaccepted, 0 },
     89  { EfiMaxMemoryType,           0 }
    9090};
    9191//
     
    531531
    532532  return;
     533}
     534
     535/**
     536  Sets the preferred memory range to use for the Memory Type Information bins.
     537  This service must be called before fist call to CoreAddMemoryDescriptor().
     538
     539  If the location of the Memory Type Information bins has already been
     540  established or the size of the range provides is smaller than all the
     541  Memory Type Information bins, then the range provides is not used.
     542
     543  @param  Start   The start address of the Memory Type Information range.
     544  @param  Length  The size, in bytes, of the Memory Type Information range.
     545**/
     546VOID
     547CoreSetMemoryTypeInformationRange (
     548  IN EFI_PHYSICAL_ADDRESS  Start,
     549  IN UINT64                Length
     550  )
     551{
     552  EFI_PHYSICAL_ADDRESS  Top;
     553  EFI_MEMORY_TYPE       Type;
     554  UINTN                 Index;
     555  UINTN                 Size;
     556
     557  //
     558  // Return if Memory Type Information bin locations have already been set
     559  //
     560  if (mMemoryTypeInformationInitialized) {
     561    DEBUG ((DEBUG_ERROR, "%a: Ignored. Bins already set.\n", __func__));
     562    return;
     563  }
     564
     565  //
     566  // Return if size of the Memory Type Information bins is greater than Length
     567  //
     568  Size = 0;
     569  for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {
     570    //
     571    // Make sure the memory type in the gMemoryTypeInformation[] array is valid
     572    //
     573    Type = (EFI_MEMORY_TYPE)(gMemoryTypeInformation[Index].Type);
     574    if ((UINT32)Type > EfiMaxMemoryType) {
     575      continue;
     576    }
     577
     578    Size += EFI_PAGES_TO_SIZE (gMemoryTypeInformation[Index].NumberOfPages);
     579  }
     580
     581  if (Size > Length) {
     582    return;
     583  }
     584
     585  //
     586  // Loop through each memory type in the order specified by the
     587  // gMemoryTypeInformation[] array
     588  //
     589  Top = Start + Length;
     590  for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {
     591    //
     592    // Make sure the memory type in the gMemoryTypeInformation[] array is valid
     593    //
     594    Type = (EFI_MEMORY_TYPE)(gMemoryTypeInformation[Index].Type);
     595    if ((UINT32)Type > EfiMaxMemoryType) {
     596      continue;
     597    }
     598
     599    if (gMemoryTypeInformation[Index].NumberOfPages != 0) {
     600      mMemoryTypeStatistics[Type].MaximumAddress = Top - 1;
     601      Top                                       -= EFI_PAGES_TO_SIZE (gMemoryTypeInformation[Index].NumberOfPages);
     602      mMemoryTypeStatistics[Type].BaseAddress    = Top;
     603
     604      //
     605      // If the current base address is the lowest address so far, then update
     606      // the default maximum address
     607      //
     608      if (mMemoryTypeStatistics[Type].BaseAddress < mDefaultMaximumAddress) {
     609        mDefaultMaximumAddress = mMemoryTypeStatistics[Type].BaseAddress - 1;
     610      }
     611
     612      mMemoryTypeStatistics[Type].NumberOfPages   = gMemoryTypeInformation[Index].NumberOfPages;
     613      gMemoryTypeInformation[Index].NumberOfPages = 0;
     614    }
     615  }
     616
     617  //
     618  // If the number of pages reserved for a memory type is 0, then all
     619  // allocations for that type should be in the default range.
     620  //
     621  for (Type = (EFI_MEMORY_TYPE)0; Type < EfiMaxMemoryType; Type++) {
     622    for (Index = 0; gMemoryTypeInformation[Index].Type != EfiMaxMemoryType; Index++) {
     623      if (Type == (EFI_MEMORY_TYPE)gMemoryTypeInformation[Index].Type) {
     624        mMemoryTypeStatistics[Type].InformationIndex = Index;
     625      }
     626    }
     627
     628    mMemoryTypeStatistics[Type].CurrentNumberOfPages = 0;
     629    if (mMemoryTypeStatistics[Type].MaximumAddress == MAX_ALLOC_ADDRESS) {
     630      mMemoryTypeStatistics[Type].MaximumAddress = mDefaultMaximumAddress;
     631    }
     632  }
     633
     634  mMemoryTypeInformationInitialized = TRUE;
    533635}
    534636
     
    12111313    if (Start != 0) {
    12121314      if (Start < mDefaultBaseAddress) {
    1213         mDefaultBaseAddress = Start;
     1315        mDefaultBaseAddress = NeedGuard ? Start - EFI_PAGE_SIZE : Start;
    12141316      }
    12151317
     
    13021404  Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY;
    13031405
    1304   if ((MemoryType == EfiACPIReclaimMemory) ||
     1406  if ((MemoryType == EfiReservedMemoryType) ||
    13051407      (MemoryType == EfiACPIMemoryNVS) ||
    13061408      (MemoryType == EfiRuntimeServicesCode) ||
     
    13081410  {
    13091411    Alignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
     1412  }
     1413
     1414  //
     1415  // The heap guard system does not support non-EFI_PAGE_SIZE alignments.
     1416  // Architectures that require larger RUNTIME_PAGE_ALLOCATION_GRANULARITY
     1417  // will have the runtime memory regions unguarded. OSes do not
     1418  // map guard pages anyway, so this is a minimal loss. Not guarding prevents
     1419  // alignment mismatches
     1420  //
     1421  if (Alignment != EFI_PAGE_SIZE) {
     1422    NeedGuard = FALSE;
    13101423  }
    13111424
     
    15571670  }
    15581671
     1672  if (Entry == NULL) {
     1673    ASSERT (Entry != NULL);
     1674    Status = EFI_NOT_FOUND;
     1675    goto Done;
     1676  }
     1677
    15591678  Alignment = DEFAULT_PAGE_ALLOCATION_GRANULARITY;
    15601679
    1561   ASSERT (Entry != NULL);
    1562   if ((Entry->Type == EfiACPIReclaimMemory) ||
     1680  if ((Entry->Type == EfiReservedMemoryType) ||
    15631681      (Entry->Type == EfiACPIMemoryNVS) ||
    15641682      (Entry->Type == EfiRuntimeServicesCode) ||
     
    19662084    }
    19672085
    1968     if (MergeGcdMapEntry.GcdMemoryType == EFI_GCD_MEMORY_TYPE_UNACCEPTED) {
     2086    if (MergeGcdMapEntry.GcdMemoryType == EfiGcdMemoryTypeUnaccepted) {
    19692087      //
    19702088      // Page Align GCD range is required. When it is converted to EFI_MEMORY_DESCRIPTOR,
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Mem/Pool.c

    r101291 r105670  
    371371  ASSERT_LOCKED (&mPoolMemoryLock);
    372372
    373   if ((PoolType == EfiACPIReclaimMemory) ||
     373  if ((PoolType == EfiReservedMemoryType) ||
    374374      (PoolType == EfiACPIMemoryNVS) ||
    375375      (PoolType == EfiRuntimeServicesCode) ||
     
    379379  } else {
    380380    Granularity = DEFAULT_PAGE_ALLOCATION_GRANULARITY;
     381  }
     382
     383  //
     384  // The heap guard system does not support non-EFI_PAGE_SIZE alignments.
     385  // Architectures that require larger RUNTIME_PAGE_ALLOCATION_GRANULARITY
     386  // will have the runtime memory regions unguarded. OSes do not
     387  // map guard pages anyway, so this is a minimal loss. Not guarding prevents
     388  // alignment mismatches
     389  //
     390  if (Granularity != EFI_PAGE_SIZE) {
     391    NeedGuard = FALSE;
    381392  }
    382393
     
    754765  DEBUG ((DEBUG_POOL, "FreePool: %p (len %lx) %,ld\n", Head->Data, (UINT64)(Head->Size - POOL_OVERHEAD), (UINT64)Pool->Used));
    755766
    756   if ((Head->Type == EfiACPIReclaimMemory) ||
     767  if ((Head->Type == EfiReservedMemoryType) ||
    757768      (Head->Type == EfiACPIMemoryNVS) ||
    758769      (Head->Type == EfiRuntimeServicesCode) ||
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Misc/MemoryAttributesTable.c

    r101291 r105670  
    1515#include <Library/DebugLib.h>
    1616#include <Library/UefiLib.h>
     17#include <Library/ImagePropertiesRecordLib.h>
    1718
    1819#include <Guid/EventGroup.h>
     
    284285  mMemoryAttributesTableEndOfDxe = TRUE;
    285286  InstallMemoryAttributesTable ();
     287
     288  DEBUG_CODE_BEGIN ();
     289  if ( mImagePropertiesPrivateData.ImageRecordCount > 0) {
     290    DEBUG ((DEBUG_INFO, "DXE - Total Runtime Image Count: 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount));
     291    DEBUG ((DEBUG_INFO, "DXE - Dump Runtime Image Records:\n"));
     292    DumpImageRecords (&mImagePropertiesPrivateData.ImageRecordList);
     293  }
     294
     295  DEBUG_CODE_END ();
    286296}
    287297
     
    335345
    336346/**
    337   Converts a number of EFI_PAGEs to a size in bytes.
    338 
    339   NOTE: Do not use EFI_PAGES_TO_SIZE because it handles UINTN only.
    340 
    341   @param  Pages     The number of EFI_PAGES.
    342 
    343   @return  The number of bytes associated with the number of EFI_PAGEs specified
    344            by Pages.
    345 **/
    346 STATIC
    347 UINT64
    348 EfiPagesToSize (
    349   IN UINT64  Pages
    350   )
    351 {
    352   return LShiftU64 (Pages, EFI_PAGE_SHIFT);
    353 }
    354 
    355 /**
    356   Converts a size, in bytes, to a number of EFI_PAGESs.
    357 
    358   NOTE: Do not use EFI_SIZE_TO_PAGES because it handles UINTN only.
    359 
    360   @param  Size      A size in bytes.
    361 
    362   @return  The number of EFI_PAGESs associated with the number of bytes specified
    363            by Size.
    364 
    365 **/
    366 STATIC
    367 UINT64
    368 EfiSizeToPages (
    369   IN UINT64  Size
    370   )
    371 {
    372   return RShiftU64 (Size, EFI_PAGE_SHIFT) + ((((UINTN)Size) & EFI_PAGE_MASK) ? 1 : 0);
    373 }
    374 
    375 /**
    376347  Acquire memory lock on mMemoryAttributesTableLock.
    377348**/
     
    395366{
    396367  CoreReleaseLock (&mMemoryAttributesTableLock);
    397 }
    398 
    399 /**
    400   Sort memory map entries based upon PhysicalStart, from low to high.
    401 
    402   @param  MemoryMap              A pointer to the buffer in which firmware places
    403                                  the current memory map.
    404   @param  MemoryMapSize          Size, in bytes, of the MemoryMap buffer.
    405   @param  DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    406 **/
    407 STATIC
    408 VOID
    409 SortMemoryMap (
    410   IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
    411   IN UINTN                      MemoryMapSize,
    412   IN UINTN                      DescriptorSize
    413   )
    414 {
    415   EFI_MEMORY_DESCRIPTOR  *MemoryMapEntry;
    416   EFI_MEMORY_DESCRIPTOR  *NextMemoryMapEntry;
    417   EFI_MEMORY_DESCRIPTOR  *MemoryMapEnd;
    418   EFI_MEMORY_DESCRIPTOR  TempMemoryMap;
    419 
    420   MemoryMapEntry     = MemoryMap;
    421   NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    422   MemoryMapEnd       = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize);
    423   while (MemoryMapEntry < MemoryMapEnd) {
    424     while (NextMemoryMapEntry < MemoryMapEnd) {
    425       if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) {
    426         CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR));
    427         CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR));
    428         CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof (EFI_MEMORY_DESCRIPTOR));
    429       }
    430 
    431       NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize);
    432     }
    433 
    434     MemoryMapEntry     = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    435     NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    436   }
    437 
    438   return;
    439368}
    440369
     
    472401    do {
    473402      MergeGuardPages (NewMemoryMapEntry, NextMemoryMapEntry->PhysicalStart);
    474       MemoryBlockLength = (UINT64)(EfiPagesToSize (NewMemoryMapEntry->NumberOfPages));
     403      MemoryBlockLength = LShiftU64 (NewMemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT);
    475404      if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) &&
    476405          (NewMemoryMapEntry->Type == NextMemoryMapEntry->Type) &&
     
    535464    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    536465  }
    537 
    538   return;
    539 }
    540 
    541 /**
    542   Return the first image record, whose [ImageBase, ImageSize] covered by [Buffer, Length].
    543 
    544   @param Buffer  Start Address
    545   @param Length  Address length
    546 
    547   @return first image record covered by [buffer, length]
    548 **/
    549 STATIC
    550 IMAGE_PROPERTIES_RECORD *
    551 GetImageRecordByAddress (
    552   IN EFI_PHYSICAL_ADDRESS  Buffer,
    553   IN UINT64                Length
    554   )
    555 {
    556   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    557   LIST_ENTRY               *ImageRecordLink;
    558   LIST_ENTRY               *ImageRecordList;
    559 
    560   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    561 
    562   for (ImageRecordLink = ImageRecordList->ForwardLink;
    563        ImageRecordLink != ImageRecordList;
    564        ImageRecordLink = ImageRecordLink->ForwardLink)
    565   {
    566     ImageRecord = CR (
    567                     ImageRecordLink,
    568                     IMAGE_PROPERTIES_RECORD,
    569                     Link,
    570                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    571                     );
    572 
    573     if ((Buffer <= ImageRecord->ImageBase) &&
    574         (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize))
    575     {
    576       return ImageRecord;
    577     }
    578   }
    579 
    580   return NULL;
    581 }
    582 
    583 /**
    584   Set the memory map to new entries, according to one old entry,
    585   based upon PE code section and data section in image record
    586 
    587   @param  ImageRecord            An image record whose [ImageBase, ImageSize] covered
    588                                  by old memory map entry.
    589   @param  NewRecord              A pointer to several new memory map entries.
    590                                  The caller gurantee the buffer size be 1 +
    591                                  (SplitRecordCount * DescriptorSize) calculated
    592                                  below.
    593   @param  OldRecord              A pointer to one old memory map entry.
    594   @param  DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    595 **/
    596 STATIC
    597 UINTN
    598 SetNewRecord (
    599   IN IMAGE_PROPERTIES_RECORD    *ImageRecord,
    600   IN OUT EFI_MEMORY_DESCRIPTOR  *NewRecord,
    601   IN EFI_MEMORY_DESCRIPTOR      *OldRecord,
    602   IN UINTN                      DescriptorSize
    603   )
    604 {
    605   EFI_MEMORY_DESCRIPTOR                 TempRecord;
    606   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    607   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    608   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    609   LIST_ENTRY                            *ImageRecordCodeSectionList;
    610   UINTN                                 NewRecordCount;
    611   UINT64                                PhysicalEnd;
    612   UINT64                                ImageEnd;
    613 
    614   CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR));
    615   PhysicalEnd    = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages);
    616   NewRecordCount = 0;
    617 
    618   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    619 
    620   ImageRecordCodeSectionLink    = ImageRecordCodeSectionList->ForwardLink;
    621   ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList;
    622   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    623     ImageRecordCodeSection = CR (
    624                                ImageRecordCodeSectionLink,
    625                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    626                                Link,
    627                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    628                                );
    629     ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    630 
    631     if (TempRecord.PhysicalStart <= ImageRecordCodeSection->CodeSegmentBase) {
    632       //
    633       // DATA
    634       //
    635       NewRecord->Type          = TempRecord.Type;
    636       NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    637       NewRecord->VirtualStart  = 0;
    638       NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart);
    639       NewRecord->Attribute     = TempRecord.Attribute | EFI_MEMORY_XP;
    640       if (NewRecord->NumberOfPages != 0) {
    641         NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    642         NewRecordCount++;
    643       }
    644 
    645       //
    646       // CODE
    647       //
    648       NewRecord->Type          = TempRecord.Type;
    649       NewRecord->PhysicalStart = ImageRecordCodeSection->CodeSegmentBase;
    650       NewRecord->VirtualStart  = 0;
    651       NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize);
    652       NewRecord->Attribute     = (TempRecord.Attribute & (~EFI_MEMORY_XP)) | EFI_MEMORY_RO;
    653       if (NewRecord->NumberOfPages != 0) {
    654         NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    655         NewRecordCount++;
    656       }
    657 
    658       TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize));
    659       TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart);
    660       if (TempRecord.NumberOfPages == 0) {
    661         break;
    662       }
    663     }
    664   }
    665 
    666   ImageEnd = ImageRecord->ImageBase + ImageRecord->ImageSize;
    667 
    668   //
    669   // Final DATA
    670   //
    671   if (TempRecord.PhysicalStart < ImageEnd) {
    672     NewRecord->Type          = TempRecord.Type;
    673     NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    674     NewRecord->VirtualStart  = 0;
    675     NewRecord->NumberOfPages = EfiSizeToPages (ImageEnd - TempRecord.PhysicalStart);
    676     NewRecord->Attribute     = TempRecord.Attribute | EFI_MEMORY_XP;
    677     NewRecordCount++;
    678   }
    679 
    680   return NewRecordCount;
    681 }
    682 
    683 /**
    684   Return the max number of new splitted entries, according to one old entry,
    685   based upon PE code section and data section.
    686 
    687   @param  OldRecord              A pointer to one old memory map entry.
    688 
    689   @retval  0 no entry need to be splitted.
    690   @return  the max number of new splitted entries
    691 **/
    692 STATIC
    693 UINTN
    694 GetMaxSplitRecordCount (
    695   IN EFI_MEMORY_DESCRIPTOR  *OldRecord
    696   )
    697 {
    698   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    699   UINTN                    SplitRecordCount;
    700   UINT64                   PhysicalStart;
    701   UINT64                   PhysicalEnd;
    702 
    703   SplitRecordCount = 0;
    704   PhysicalStart    = OldRecord->PhysicalStart;
    705   PhysicalEnd      = OldRecord->PhysicalStart + EfiPagesToSize (OldRecord->NumberOfPages);
    706 
    707   do {
    708     ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart);
    709     if (ImageRecord == NULL) {
    710       break;
    711     }
    712 
    713     SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 1);
    714     PhysicalStart     = ImageRecord->ImageBase + ImageRecord->ImageSize;
    715   } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd));
    716 
    717   if (SplitRecordCount != 0) {
    718     SplitRecordCount--;
    719   }
    720 
    721   return SplitRecordCount;
    722 }
    723 
    724 /**
    725   Split the memory map to new entries, according to one old entry,
    726   based upon PE code section and data section.
    727 
    728   @param  OldRecord              A pointer to one old memory map entry.
    729   @param  NewRecord              A pointer to several new memory map entries.
    730                                  The caller gurantee the buffer size be 1 +
    731                                  (SplitRecordCount * DescriptorSize) calculated
    732                                  below.
    733   @param  MaxSplitRecordCount    The max number of splitted entries
    734   @param  DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    735 
    736   @retval  0 no entry is splitted.
    737   @return  the real number of splitted record.
    738 **/
    739 STATIC
    740 UINTN
    741 SplitRecord (
    742   IN EFI_MEMORY_DESCRIPTOR      *OldRecord,
    743   IN OUT EFI_MEMORY_DESCRIPTOR  *NewRecord,
    744   IN UINTN                      MaxSplitRecordCount,
    745   IN UINTN                      DescriptorSize
    746   )
    747 {
    748   EFI_MEMORY_DESCRIPTOR    TempRecord;
    749   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    750   IMAGE_PROPERTIES_RECORD  *NewImageRecord;
    751   UINT64                   PhysicalStart;
    752   UINT64                   PhysicalEnd;
    753   UINTN                    NewRecordCount;
    754   UINTN                    TotalNewRecordCount;
    755   BOOLEAN                  IsLastRecordData;
    756 
    757   if (MaxSplitRecordCount == 0) {
    758     CopyMem (NewRecord, OldRecord, DescriptorSize);
    759     return 0;
    760   }
    761 
    762   TotalNewRecordCount = 0;
    763 
    764   //
    765   // Override previous record
    766   //
    767   CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR));
    768   PhysicalStart = TempRecord.PhysicalStart;
    769   PhysicalEnd   = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages);
    770 
    771   ImageRecord = NULL;
    772   do {
    773     NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart);
    774     if (NewImageRecord == NULL) {
    775       //
    776       // No more image covered by this range, stop
    777       //
    778       if ((PhysicalEnd > PhysicalStart) && (ImageRecord != NULL)) {
    779         //
    780         // If this is still address in this record, need record.
    781         //
    782         NewRecord        = PREVIOUS_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    783         IsLastRecordData = FALSE;
    784         if ((NewRecord->Attribute & EFI_MEMORY_XP) != 0) {
    785           IsLastRecordData = TRUE;
    786         }
    787 
    788         if (IsLastRecordData) {
    789           //
    790           // Last record is DATA, just merge it.
    791           //
    792           NewRecord->NumberOfPages = EfiSizeToPages (PhysicalEnd - NewRecord->PhysicalStart);
    793         } else {
    794           //
    795           // Last record is CODE, create a new DATA entry.
    796           //
    797           NewRecord                = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    798           NewRecord->Type          = TempRecord.Type;
    799           NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    800           NewRecord->VirtualStart  = 0;
    801           NewRecord->NumberOfPages = TempRecord.NumberOfPages;
    802           NewRecord->Attribute     = TempRecord.Attribute | EFI_MEMORY_XP;
    803           TotalNewRecordCount++;
    804         }
    805       }
    806 
    807       break;
    808     }
    809 
    810     ImageRecord = NewImageRecord;
    811 
    812     //
    813     // Set new record
    814     //
    815     NewRecordCount       = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize);
    816     TotalNewRecordCount += NewRecordCount;
    817     NewRecord            = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize);
    818 
    819     //
    820     // Update PhysicalStart, in order to exclude the image buffer already splitted.
    821     //
    822     PhysicalStart            = ImageRecord->ImageBase + ImageRecord->ImageSize;
    823     TempRecord.PhysicalStart = PhysicalStart;
    824     TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - PhysicalStart);
    825   } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd));
    826 
    827   //
    828   // The logic in function SplitTable() ensures that TotalNewRecordCount will not be zero if the
    829   // code reaches here.
    830   //
    831   ASSERT (TotalNewRecordCount != 0);
    832   return TotalNewRecordCount - 1;
    833 }
    834 
    835 /**
    836   Split the original memory map, and add more entries to describe PE code section and data section.
    837   This function will set EfiRuntimeServicesData to be EFI_MEMORY_XP.
    838   This function will merge entries with same attributes finally.
    839 
    840   NOTE: It assumes PE code/data section are page aligned.
    841   NOTE: It assumes enough entry is prepared for new memory map.
    842 
    843   Split table:
    844    +---------------+
    845    | Record X      |
    846    +---------------+
    847    | Record RtCode |
    848    +---------------+
    849    | Record Y      |
    850    +---------------+
    851    ==>
    852    +---------------+
    853    | Record X      |
    854    +---------------+ ----
    855    | Record RtData |     |
    856    +---------------+     |
    857    | Record RtCode |     |-> PE/COFF1
    858    +---------------+     |
    859    | Record RtData |     |
    860    +---------------+ ----
    861    | Record RtData |     |
    862    +---------------+     |
    863    | Record RtCode |     |-> PE/COFF2
    864    +---------------+     |
    865    | Record RtData |     |
    866    +---------------+ ----
    867    | Record Y      |
    868    +---------------+
    869 
    870   @param  MemoryMapSize          A pointer to the size, in bytes, of the
    871                                  MemoryMap buffer. On input, this is the size of
    872                                  old MemoryMap before split. The actual buffer
    873                                  size of MemoryMap is MemoryMapSize +
    874                                  (AdditionalRecordCount * DescriptorSize) calculated
    875                                  below. On output, it is the size of new MemoryMap
    876                                  after split.
    877   @param  MemoryMap              A pointer to the buffer in which firmware places
    878                                  the current memory map.
    879   @param  DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    880 **/
    881 STATIC
    882 VOID
    883 SplitTable (
    884   IN OUT UINTN                  *MemoryMapSize,
    885   IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
    886   IN UINTN                      DescriptorSize
    887   )
    888 {
    889   INTN   IndexOld;
    890   INTN   IndexNew;
    891   UINTN  MaxSplitRecordCount;
    892   UINTN  RealSplitRecordCount;
    893   UINTN  TotalSplitRecordCount;
    894   UINTN  AdditionalRecordCount;
    895 
    896   AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 1) * mImagePropertiesPrivateData.ImageRecordCount;
    897 
    898   TotalSplitRecordCount = 0;
    899   //
    900   // Let old record point to end of valid MemoryMap buffer.
    901   //
    902   IndexOld = ((*MemoryMapSize) / DescriptorSize) - 1;
    903   //
    904   // Let new record point to end of full MemoryMap buffer.
    905   //
    906   IndexNew = ((*MemoryMapSize) / DescriptorSize) - 1 + AdditionalRecordCount;
    907   for ( ; IndexOld >= 0; IndexOld--) {
    908     MaxSplitRecordCount = GetMaxSplitRecordCount ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize));
    909     //
    910     // Split this MemoryMap record
    911     //
    912     IndexNew            -= MaxSplitRecordCount;
    913     RealSplitRecordCount = SplitRecord (
    914                              (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize),
    915                              (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexNew * DescriptorSize),
    916                              MaxSplitRecordCount,
    917                              DescriptorSize
    918                              );
    919     //
    920     // Adjust IndexNew according to real split.
    921     //
    922     CopyMem (
    923       ((UINT8 *)MemoryMap + (IndexNew + MaxSplitRecordCount - RealSplitRecordCount) * DescriptorSize),
    924       ((UINT8 *)MemoryMap + IndexNew * DescriptorSize),
    925       RealSplitRecordCount * DescriptorSize
    926       );
    927     IndexNew               = IndexNew + MaxSplitRecordCount - RealSplitRecordCount;
    928     TotalSplitRecordCount += RealSplitRecordCount;
    929     IndexNew--;
    930   }
    931 
    932   //
    933   // Move all records to the beginning.
    934   //
    935   CopyMem (
    936     MemoryMap,
    937     (UINT8 *)MemoryMap + (AdditionalRecordCount - TotalSplitRecordCount) * DescriptorSize,
    938     (*MemoryMapSize) + TotalSplitRecordCount * DescriptorSize
    939     );
    940 
    941   *MemoryMapSize = (*MemoryMapSize) + DescriptorSize * TotalSplitRecordCount;
    942 
    943   //
    944   // Sort from low to high (Just in case)
    945   //
    946   SortMemoryMap (MemoryMap, *MemoryMapSize, DescriptorSize);
    947 
    948   //
    949   // Set RuntimeData to XP
    950   //
    951   EnforceMemoryMapAttribute (MemoryMap, *MemoryMapSize, DescriptorSize);
    952 
    953   //
    954   // Merge same type to save entry size
    955   //
    956   MergeMemoryMap (MemoryMap, MemoryMapSize, DescriptorSize);
    957466
    958467  return;
     
    1018527  CoreAcquiremMemoryAttributesTableLock ();
    1019528
    1020   AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 1) * mImagePropertiesPrivateData.ImageRecordCount;
     529  AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 3) * mImagePropertiesPrivateData.ImageRecordCount;
    1021530
    1022531  OldMemoryMapSize = *MemoryMapSize;
     
    1036545      // Split PE code/data
    1037546      //
    1038       SplitTable (MemoryMapSize, MemoryMap, *DescriptorSize);
     547      SplitTable (MemoryMapSize, MemoryMap, *DescriptorSize, &mImagePropertiesPrivateData.ImageRecordList, AdditionalRecordCount);
     548
     549      //
     550      // Set RuntimeData to XP
     551      //
     552      EnforceMemoryMapAttribute (MemoryMap, *MemoryMapSize, *DescriptorSize);
     553
     554      //
     555      // Merge same type to save entry size
     556      //
     557      MergeMemoryMap (MemoryMap, MemoryMapSize, *DescriptorSize);
    1039558    }
    1040559  }
     
    1049568
    1050569/**
    1051   Set MemoryAttributesTable according to PE/COFF image section alignment.
    1052 
    1053   @param  SectionAlignment    PE/COFF section alignment
    1054 **/
    1055 STATIC
    1056 VOID
    1057 SetMemoryAttributesTableSectionAlignment (
    1058   IN UINT32  SectionAlignment
    1059   )
    1060 {
    1061   if (((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) &&
    1062       mMemoryAttributesTableEnable)
    1063   {
    1064     DEBUG ((DEBUG_VERBOSE, "SetMemoryAttributesTableSectionAlignment - Clear\n"));
    1065     mMemoryAttributesTableEnable = FALSE;
    1066   }
    1067 }
    1068 
    1069 /**
    1070   Swap two code sections in image record.
    1071 
    1072   @param  FirstImageRecordCodeSection    first code section in image record
    1073   @param  SecondImageRecordCodeSection   second code section in image record
    1074 **/
    1075 STATIC
    1076 VOID
    1077 SwapImageRecordCodeSection (
    1078   IN IMAGE_PROPERTIES_RECORD_CODE_SECTION  *FirstImageRecordCodeSection,
    1079   IN IMAGE_PROPERTIES_RECORD_CODE_SECTION  *SecondImageRecordCodeSection
    1080   )
    1081 {
    1082   IMAGE_PROPERTIES_RECORD_CODE_SECTION  TempImageRecordCodeSection;
    1083 
    1084   TempImageRecordCodeSection.CodeSegmentBase = FirstImageRecordCodeSection->CodeSegmentBase;
    1085   TempImageRecordCodeSection.CodeSegmentSize = FirstImageRecordCodeSection->CodeSegmentSize;
    1086 
    1087   FirstImageRecordCodeSection->CodeSegmentBase = SecondImageRecordCodeSection->CodeSegmentBase;
    1088   FirstImageRecordCodeSection->CodeSegmentSize = SecondImageRecordCodeSection->CodeSegmentSize;
    1089 
    1090   SecondImageRecordCodeSection->CodeSegmentBase = TempImageRecordCodeSection.CodeSegmentBase;
    1091   SecondImageRecordCodeSection->CodeSegmentSize = TempImageRecordCodeSection.CodeSegmentSize;
    1092 }
    1093 
    1094 /**
    1095   Sort code section in image record, based upon CodeSegmentBase from low to high.
    1096 
    1097   @param  ImageRecord    image record to be sorted
    1098 **/
    1099 VOID
    1100 SortImageRecordCodeSection (
    1101   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    1102   )
    1103 {
    1104   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    1105   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *NextImageRecordCodeSection;
    1106   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    1107   LIST_ENTRY                            *NextImageRecordCodeSectionLink;
    1108   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    1109   LIST_ENTRY                            *ImageRecordCodeSectionList;
    1110 
    1111   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    1112 
    1113   ImageRecordCodeSectionLink     = ImageRecordCodeSectionList->ForwardLink;
    1114   NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    1115   ImageRecordCodeSectionEndLink  = ImageRecordCodeSectionList;
    1116   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    1117     ImageRecordCodeSection = CR (
    1118                                ImageRecordCodeSectionLink,
    1119                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    1120                                Link,
    1121                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    1122                                );
    1123     while (NextImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    1124       NextImageRecordCodeSection = CR (
    1125                                      NextImageRecordCodeSectionLink,
    1126                                      IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    1127                                      Link,
    1128                                      IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    1129                                      );
    1130       if (ImageRecordCodeSection->CodeSegmentBase > NextImageRecordCodeSection->CodeSegmentBase) {
    1131         SwapImageRecordCodeSection (ImageRecordCodeSection, NextImageRecordCodeSection);
    1132       }
    1133 
    1134       NextImageRecordCodeSectionLink = NextImageRecordCodeSectionLink->ForwardLink;
    1135     }
    1136 
    1137     ImageRecordCodeSectionLink     = ImageRecordCodeSectionLink->ForwardLink;
    1138     NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    1139   }
    1140 }
    1141 
    1142 /**
    1143   Check if code section in image record is valid.
    1144 
    1145   @param  ImageRecord    image record to be checked
    1146 
    1147   @retval TRUE  image record is valid
    1148   @retval FALSE image record is invalid
    1149 **/
    1150 BOOLEAN
    1151 IsImageRecordCodeSectionValid (
    1152   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    1153   )
    1154 {
    1155   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    1156   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *LastImageRecordCodeSection;
    1157   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    1158   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    1159   LIST_ENTRY                            *ImageRecordCodeSectionList;
    1160 
    1161   DEBUG ((DEBUG_VERBOSE, "ImageCode SegmentCount - 0x%x\n", ImageRecord->CodeSegmentCount));
    1162 
    1163   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    1164 
    1165   ImageRecordCodeSectionLink    = ImageRecordCodeSectionList->ForwardLink;
    1166   ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList;
    1167   LastImageRecordCodeSection    = NULL;
    1168   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    1169     ImageRecordCodeSection = CR (
    1170                                ImageRecordCodeSectionLink,
    1171                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    1172                                Link,
    1173                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    1174                                );
    1175     if (ImageRecordCodeSection->CodeSegmentSize == 0) {
    1176       return FALSE;
    1177     }
    1178 
    1179     if (ImageRecordCodeSection->CodeSegmentBase < ImageRecord->ImageBase) {
    1180       return FALSE;
    1181     }
    1182 
    1183     if (ImageRecordCodeSection->CodeSegmentBase >= MAX_ADDRESS - ImageRecordCodeSection->CodeSegmentSize) {
    1184       return FALSE;
    1185     }
    1186 
    1187     if ((ImageRecordCodeSection->CodeSegmentBase + ImageRecordCodeSection->CodeSegmentSize) > (ImageRecord->ImageBase + ImageRecord->ImageSize)) {
    1188       return FALSE;
    1189     }
    1190 
    1191     if (LastImageRecordCodeSection != NULL) {
    1192       if ((LastImageRecordCodeSection->CodeSegmentBase + LastImageRecordCodeSection->CodeSegmentSize) > ImageRecordCodeSection->CodeSegmentBase) {
    1193         return FALSE;
    1194       }
    1195     }
    1196 
    1197     LastImageRecordCodeSection = ImageRecordCodeSection;
    1198     ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    1199   }
    1200 
    1201   return TRUE;
    1202 }
    1203 
    1204 /**
    1205   Swap two image records.
    1206 
    1207   @param  FirstImageRecord   first image record.
    1208   @param  SecondImageRecord  second image record.
    1209 **/
    1210 STATIC
    1211 VOID
    1212 SwapImageRecord (
    1213   IN IMAGE_PROPERTIES_RECORD  *FirstImageRecord,
    1214   IN IMAGE_PROPERTIES_RECORD  *SecondImageRecord
    1215   )
    1216 {
    1217   IMAGE_PROPERTIES_RECORD  TempImageRecord;
    1218 
    1219   TempImageRecord.ImageBase        = FirstImageRecord->ImageBase;
    1220   TempImageRecord.ImageSize        = FirstImageRecord->ImageSize;
    1221   TempImageRecord.CodeSegmentCount = FirstImageRecord->CodeSegmentCount;
    1222 
    1223   FirstImageRecord->ImageBase        = SecondImageRecord->ImageBase;
    1224   FirstImageRecord->ImageSize        = SecondImageRecord->ImageSize;
    1225   FirstImageRecord->CodeSegmentCount = SecondImageRecord->CodeSegmentCount;
    1226 
    1227   SecondImageRecord->ImageBase        = TempImageRecord.ImageBase;
    1228   SecondImageRecord->ImageSize        = TempImageRecord.ImageSize;
    1229   SecondImageRecord->CodeSegmentCount = TempImageRecord.CodeSegmentCount;
    1230 
    1231   SwapListEntries (&FirstImageRecord->CodeSegmentList, &SecondImageRecord->CodeSegmentList);
    1232 }
    1233 
    1234 /**
    1235   Sort image record based upon the ImageBase from low to high.
    1236 **/
    1237 STATIC
    1238 VOID
    1239 SortImageRecord (
    1240   VOID
    1241   )
    1242 {
    1243   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    1244   IMAGE_PROPERTIES_RECORD  *NextImageRecord;
    1245   LIST_ENTRY               *ImageRecordLink;
    1246   LIST_ENTRY               *NextImageRecordLink;
    1247   LIST_ENTRY               *ImageRecordEndLink;
    1248   LIST_ENTRY               *ImageRecordList;
    1249 
    1250   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    1251 
    1252   ImageRecordLink     = ImageRecordList->ForwardLink;
    1253   NextImageRecordLink = ImageRecordLink->ForwardLink;
    1254   ImageRecordEndLink  = ImageRecordList;
    1255   while (ImageRecordLink != ImageRecordEndLink) {
    1256     ImageRecord = CR (
    1257                     ImageRecordLink,
    1258                     IMAGE_PROPERTIES_RECORD,
    1259                     Link,
    1260                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    1261                     );
    1262     while (NextImageRecordLink != ImageRecordEndLink) {
    1263       NextImageRecord = CR (
    1264                           NextImageRecordLink,
    1265                           IMAGE_PROPERTIES_RECORD,
    1266                           Link,
    1267                           IMAGE_PROPERTIES_RECORD_SIGNATURE
    1268                           );
    1269       if (ImageRecord->ImageBase > NextImageRecord->ImageBase) {
    1270         SwapImageRecord (ImageRecord, NextImageRecord);
    1271       }
    1272 
    1273       NextImageRecordLink = NextImageRecordLink->ForwardLink;
    1274     }
    1275 
    1276     ImageRecordLink     = ImageRecordLink->ForwardLink;
    1277     NextImageRecordLink = ImageRecordLink->ForwardLink;
    1278   }
    1279 }
    1280 
    1281 /**
    1282570  Insert image record.
    1283571
     
    1289577  )
    1290578{
    1291   VOID                                  *ImageAddress;
    1292   EFI_IMAGE_DOS_HEADER                  *DosHdr;
    1293   UINT32                                PeCoffHeaderOffset;
    1294   UINT32                                SectionAlignment;
    1295   EFI_IMAGE_SECTION_HEADER              *Section;
    1296   EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION   Hdr;
    1297   UINT8                                 *Name;
    1298   UINTN                                 Index;
    1299   IMAGE_PROPERTIES_RECORD               *ImageRecord;
    1300   CHAR8                                 *PdbPointer;
    1301   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
     579  EFI_STATUS               Status;
     580  IMAGE_PROPERTIES_RECORD  *ImageRecord;
     581  CHAR8                    *PdbPointer;
     582  UINT32                   RequiredAlignment;
    1302583
    1303584  DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%x\n", RuntimeImage));
    1304   DEBUG ((DEBUG_VERBOSE, "InsertImageRecord - 0x%016lx - 0x%016lx\n", (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize));
    1305585
    1306586  if (mMemoryAttributesTableEndOfDxe) {
     
    1314594  }
    1315595
    1316   ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE;
    1317 
    1318   DEBUG ((DEBUG_VERBOSE, "ImageRecordCount - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount));
    1319 
    1320   //
    1321   // Step 1: record whole region
    1322   //
    1323   ImageRecord->ImageBase = (EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase;
    1324   ImageRecord->ImageSize = RuntimeImage->ImageSize;
    1325 
    1326   ImageAddress = RuntimeImage->ImageBase;
    1327 
    1328   PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
     596  InitializeListHead (&ImageRecord->Link);
     597  InitializeListHead (&ImageRecord->CodeSegmentList);
     598
     599  PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)RuntimeImage->ImageBase);
    1329600  if (PdbPointer != NULL) {
    1330601    DEBUG ((DEBUG_VERBOSE, "  Image - %a\n", PdbPointer));
    1331602  }
    1332603
    1333   //
    1334   // Check PE/COFF image
    1335   //
    1336   DosHdr             = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
    1337   PeCoffHeaderOffset = 0;
    1338   if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
    1339     PeCoffHeaderOffset = DosHdr->e_lfanew;
    1340   }
    1341 
    1342   Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset);
    1343   if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
    1344     DEBUG ((DEBUG_VERBOSE, "Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature));
    1345     // It might be image in SMM.
     604  RequiredAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
     605  Status            = CreateImagePropertiesRecord (
     606                        RuntimeImage->ImageBase,
     607                        RuntimeImage->ImageSize,
     608                        &RequiredAlignment,
     609                        ImageRecord
     610                        );
     611
     612  if (EFI_ERROR (Status)) {
     613    if (Status == EFI_ABORTED) {
     614      mMemoryAttributesTableEnable = FALSE;
     615    }
     616
     617    Status = EFI_ABORTED;
    1346618    goto Finish;
    1347619  }
    1348620
    1349   //
    1350   // Get SectionAlignment
    1351   //
    1352   if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
    1353     SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment;
    1354   } else {
    1355     SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment;
    1356   }
    1357 
    1358   SetMemoryAttributesTableSectionAlignment (SectionAlignment);
    1359   if ((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) {
    1360     DEBUG ((
    1361       DEBUG_WARN,
    1362       "!!!!!!!!  InsertImageRecord - Section Alignment(0x%x) is not %dK  !!!!!!!!\n",
    1363       SectionAlignment,
    1364       RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10
    1365       ));
    1366     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    1367     if (PdbPointer != NULL) {
    1368       DEBUG ((DEBUG_WARN, "!!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    1369     }
    1370 
    1371     goto Finish;
    1372   }
    1373 
    1374   Section = (EFI_IMAGE_SECTION_HEADER *)(
    1375                                          (UINT8 *)(UINTN)ImageAddress +
    1376                                          PeCoffHeaderOffset +
    1377                                          sizeof (UINT32) +
    1378                                          sizeof (EFI_IMAGE_FILE_HEADER) +
    1379                                          Hdr.Pe32->FileHeader.SizeOfOptionalHeader
    1380                                          );
    1381   ImageRecord->CodeSegmentCount = 0;
    1382   InitializeListHead (&ImageRecord->CodeSegmentList);
    1383   for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
    1384     Name = Section[Index].Name;
    1385     DEBUG ((
    1386       DEBUG_VERBOSE,
    1387       "  Section - '%c%c%c%c%c%c%c%c'\n",
    1388       Name[0],
    1389       Name[1],
    1390       Name[2],
    1391       Name[3],
    1392       Name[4],
    1393       Name[5],
    1394       Name[6],
    1395       Name[7]
    1396       ));
    1397 
    1398     if ((Section[Index].Characteristics & EFI_IMAGE_SCN_CNT_CODE) != 0) {
    1399       DEBUG ((DEBUG_VERBOSE, "  VirtualSize          - 0x%08x\n", Section[Index].Misc.VirtualSize));
    1400       DEBUG ((DEBUG_VERBOSE, "  VirtualAddress       - 0x%08x\n", Section[Index].VirtualAddress));
    1401       DEBUG ((DEBUG_VERBOSE, "  SizeOfRawData        - 0x%08x\n", Section[Index].SizeOfRawData));
    1402       DEBUG ((DEBUG_VERBOSE, "  PointerToRawData     - 0x%08x\n", Section[Index].PointerToRawData));
    1403       DEBUG ((DEBUG_VERBOSE, "  PointerToRelocations - 0x%08x\n", Section[Index].PointerToRelocations));
    1404       DEBUG ((DEBUG_VERBOSE, "  PointerToLinenumbers - 0x%08x\n", Section[Index].PointerToLinenumbers));
    1405       DEBUG ((DEBUG_VERBOSE, "  NumberOfRelocations  - 0x%08x\n", Section[Index].NumberOfRelocations));
    1406       DEBUG ((DEBUG_VERBOSE, "  NumberOfLinenumbers  - 0x%08x\n", Section[Index].NumberOfLinenumbers));
    1407       DEBUG ((DEBUG_VERBOSE, "  Characteristics      - 0x%08x\n", Section[Index].Characteristics));
    1408 
    1409       //
    1410       // Step 2: record code section
    1411       //
    1412       ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection));
    1413       if (ImageRecordCodeSection == NULL) {
    1414         return;
    1415       }
    1416 
    1417       ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE;
    1418 
    1419       ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress;
    1420       ImageRecordCodeSection->CodeSegmentSize = Section[Index].SizeOfRawData;
    1421 
    1422       DEBUG ((DEBUG_VERBOSE, "ImageCode: 0x%016lx - 0x%016lx\n", ImageRecordCodeSection->CodeSegmentBase, ImageRecordCodeSection->CodeSegmentSize));
    1423 
    1424       InsertTailList (&ImageRecord->CodeSegmentList, &ImageRecordCodeSection->Link);
    1425       ImageRecord->CodeSegmentCount++;
    1426     }
    1427   }
    1428 
    1429621  if (ImageRecord->CodeSegmentCount == 0) {
    1430     SetMemoryAttributesTableSectionAlignment (1);
     622    mMemoryAttributesTableEnable = FALSE;
    1431623    DEBUG ((DEBUG_ERROR, "!!!!!!!!  InsertImageRecord - CodeSegmentCount is 0  !!!!!!!!\n"));
    1432     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    1433624    if (PdbPointer != NULL) {
    1434625      DEBUG ((DEBUG_ERROR, "!!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    1435626    }
    1436627
     628    Status = EFI_ABORTED;
    1437629    goto Finish;
    1438630  }
    1439631
    1440   //
    1441   // Final
    1442   //
    1443   SortImageRecordCodeSection (ImageRecord);
    1444632  //
    1445633  // Check overlap all section in ImageBase/Size
     
    1447635  if (!IsImageRecordCodeSectionValid (ImageRecord)) {
    1448636    DEBUG ((DEBUG_ERROR, "IsImageRecordCodeSectionValid - FAIL\n"));
     637    Status = EFI_ABORTED;
    1449638    goto Finish;
    1450639  }
     
    1457646  }
    1458647
    1459   SortImageRecord ();
     648  SortImageRecord (&mImagePropertiesPrivateData.ImageRecordList);
    1460649
    1461650Finish:
     651  if (EFI_ERROR (Status) && (ImageRecord != NULL)) {
     652    DeleteImagePropertiesRecord (ImageRecord);
     653  }
     654
    1462655  return;
    1463 }
    1464 
    1465 /**
    1466   Find image record according to image base and size.
    1467 
    1468   @param  ImageBase    Base of PE image
    1469   @param  ImageSize    Size of PE image
    1470 
    1471   @return image record
    1472 **/
    1473 STATIC
    1474 IMAGE_PROPERTIES_RECORD *
    1475 FindImageRecord (
    1476   IN EFI_PHYSICAL_ADDRESS  ImageBase,
    1477   IN UINT64                ImageSize
    1478   )
    1479 {
    1480   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    1481   LIST_ENTRY               *ImageRecordLink;
    1482   LIST_ENTRY               *ImageRecordList;
    1483 
    1484   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    1485 
    1486   for (ImageRecordLink = ImageRecordList->ForwardLink;
    1487        ImageRecordLink != ImageRecordList;
    1488        ImageRecordLink = ImageRecordLink->ForwardLink)
    1489   {
    1490     ImageRecord = CR (
    1491                     ImageRecordLink,
    1492                     IMAGE_PROPERTIES_RECORD,
    1493                     Link,
    1494                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    1495                     );
    1496 
    1497     if ((ImageBase == ImageRecord->ImageBase) &&
    1498         (ImageSize == ImageRecord->ImageSize))
    1499     {
    1500       return ImageRecord;
    1501     }
    1502   }
    1503 
    1504   return NULL;
    1505656}
    1506657
     
    1515666  )
    1516667{
    1517   IMAGE_PROPERTIES_RECORD               *ImageRecord;
    1518   LIST_ENTRY                            *CodeSegmentListHead;
    1519   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
     668  IMAGE_PROPERTIES_RECORD  *ImageRecord;
    1520669
    1521670  DEBUG ((DEBUG_VERBOSE, "RemoveImageRecord - 0x%x\n", RuntimeImage));
     
    1527676  }
    1528677
    1529   ImageRecord = FindImageRecord ((EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize);
     678  ImageRecord = FindImageRecord ((EFI_PHYSICAL_ADDRESS)(UINTN)RuntimeImage->ImageBase, RuntimeImage->ImageSize, &mImagePropertiesPrivateData.ImageRecordList);
    1530679  if (ImageRecord == NULL) {
    1531680    DEBUG ((DEBUG_ERROR, "!!!!!!!! ImageRecord not found !!!!!!!!\n"));
     
    1533682  }
    1534683
    1535   CodeSegmentListHead = &ImageRecord->CodeSegmentList;
    1536   while (!IsListEmpty (CodeSegmentListHead)) {
    1537     ImageRecordCodeSection = CR (
    1538                                CodeSegmentListHead->ForwardLink,
    1539                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    1540                                Link,
    1541                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    1542                                );
    1543     RemoveEntryList (&ImageRecordCodeSection->Link);
    1544     FreePool (ImageRecordCodeSection);
    1545   }
    1546 
    1547   RemoveEntryList (&ImageRecord->Link);
    1548   FreePool (ImageRecord);
     684  DeleteImagePropertiesRecord (ImageRecord);
     685
    1549686  mImagePropertiesPrivateData.ImageRecordCount--;
    1550687}
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Dxe/Misc/MemoryProtection.c

    r101291 r105670  
    3333#include <Library/DebugLib.h>
    3434#include <Library/UefiLib.h>
     35#include <Library/ImagePropertiesRecordLib.h>
    3536
    3637#include <Guid/EventGroup.h>
     
    6667
    6768STATIC LIST_ENTRY  mProtectedImageRecordList;
    68 
    69 /**
    70   Sort code section in image record, based upon CodeSegmentBase from low to high.
    71 
    72   @param  ImageRecord    image record to be sorted
    73 **/
    74 VOID
    75 SortImageRecordCodeSection (
    76   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    77   );
    78 
    79 /**
    80   Check if code section in image record is valid.
    81 
    82   @param  ImageRecord    image record to be checked
    83 
    84   @retval TRUE  image record is valid
    85   @retval FALSE image record is invalid
    86 **/
    87 BOOLEAN
    88 IsImageRecordCodeSectionValid (
    89   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    90   );
    9169
    9270/**
     
    304282
    305283/**
    306   Return if the PE image section is aligned.
    307 
    308   @param[in]  SectionAlignment    PE/COFF section alignment
    309   @param[in]  MemoryType          PE/COFF image memory type
    310 
    311   @retval TRUE  The PE image section is aligned.
    312   @retval FALSE The PE image section is not aligned.
    313 **/
    314 BOOLEAN
    315 IsMemoryProtectionSectionAligned (
    316   IN UINT32           SectionAlignment,
     284  Return the section alignment requirement for the PE image section type.
     285
     286  @param[in]  MemoryType  PE/COFF image memory type
     287
     288  @retval     The required section alignment for this memory type
     289
     290**/
     291STATIC
     292UINT32
     293GetMemoryProtectionSectionAlignment (
    317294  IN EFI_MEMORY_TYPE  MemoryType
    318295  )
    319296{
    320   UINT32  PageAlignment;
     297  UINT32  SectionAlignment;
    321298
    322299  switch (MemoryType) {
    323300    case EfiRuntimeServicesCode:
    324301    case EfiACPIMemoryNVS:
    325       PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
     302    case EfiReservedMemoryType:
     303      SectionAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
    326304      break;
    327305    case EfiRuntimeServicesData:
    328     case EfiACPIReclaimMemory:
    329306      ASSERT (FALSE);
    330       PageAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
     307      SectionAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
    331308      break;
    332309    case EfiBootServicesCode:
    333310    case EfiLoaderCode:
    334     case EfiReservedMemoryType:
    335       PageAlignment = EFI_PAGE_SIZE;
     311      SectionAlignment = EFI_PAGE_SIZE;
    336312      break;
     313    case EfiACPIReclaimMemory:
    337314    default:
    338315      ASSERT (FALSE);
    339       PageAlignment = EFI_PAGE_SIZE;
     316      SectionAlignment = EFI_PAGE_SIZE;
    340317      break;
    341318  }
    342319
    343   if ((SectionAlignment & (PageAlignment - 1)) != 0) {
    344     return FALSE;
    345   } else {
    346     return TRUE;
    347   }
    348 }
    349 
    350 /**
    351   Free Image record.
    352 
    353   @param[in]  ImageRecord    A UEFI image record
    354 **/
    355 VOID
    356 FreeImageRecord (
    357   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    358   )
    359 {
    360   LIST_ENTRY                            *CodeSegmentListHead;
    361   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    362 
    363   CodeSegmentListHead = &ImageRecord->CodeSegmentList;
    364   while (!IsListEmpty (CodeSegmentListHead)) {
    365     ImageRecordCodeSection = CR (
    366                                CodeSegmentListHead->ForwardLink,
    367                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    368                                Link,
    369                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    370                                );
    371     RemoveEntryList (&ImageRecordCodeSection->Link);
    372     FreePool (ImageRecordCodeSection);
    373   }
    374 
    375   if (ImageRecord->Link.ForwardLink != NULL) {
    376     RemoveEntryList (&ImageRecord->Link);
    377   }
    378 
    379   FreePool (ImageRecord);
     320  return SectionAlignment;
    380321}
    381322
     
    392333  )
    393334{
    394   VOID                                  *ImageAddress;
    395   EFI_IMAGE_DOS_HEADER                  *DosHdr;
    396   UINT32                                PeCoffHeaderOffset;
    397   UINT32                                SectionAlignment;
    398   EFI_IMAGE_SECTION_HEADER              *Section;
    399   EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION   Hdr;
    400   UINT8                                 *Name;
    401   UINTN                                 Index;
    402   IMAGE_PROPERTIES_RECORD               *ImageRecord;
    403   CHAR8                                 *PdbPointer;
    404   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    405   BOOLEAN                               IsAligned;
    406   UINT32                                ProtectionPolicy;
     335  IMAGE_PROPERTIES_RECORD  *ImageRecord;
     336  UINT32                   ProtectionPolicy;
     337  EFI_STATUS               Status;
     338  UINT32                   RequiredAlignment;
    407339
    408340  DEBUG ((DEBUG_INFO, "ProtectUefiImageCommon - 0x%x\n", LoadedImage));
     
    429361  }
    430362
    431   ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE;
    432 
    433   //
    434   // Step 1: record whole region
    435   //
    436   ImageRecord->ImageBase = (EFI_PHYSICAL_ADDRESS)(UINTN)LoadedImage->ImageBase;
    437   ImageRecord->ImageSize = LoadedImage->ImageSize;
    438 
    439   ImageAddress = LoadedImage->ImageBase;
    440 
    441   PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    442   if (PdbPointer != NULL) {
    443     DEBUG ((DEBUG_VERBOSE, "  Image - %a\n", PdbPointer));
    444   }
    445 
    446   //
    447   // Check PE/COFF image
    448   //
    449   DosHdr             = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
    450   PeCoffHeaderOffset = 0;
    451   if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
    452     PeCoffHeaderOffset = DosHdr->e_lfanew;
    453   }
    454 
    455   Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset);
    456   if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
    457     DEBUG ((DEBUG_VERBOSE, "Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature));
    458     // It might be image in SMM.
     363  RequiredAlignment = GetMemoryProtectionSectionAlignment (LoadedImage->ImageCodeType);
     364
     365  Status = CreateImagePropertiesRecord (
     366             LoadedImage->ImageBase,
     367             LoadedImage->ImageSize,
     368             &RequiredAlignment,
     369             ImageRecord
     370             );
     371
     372  if (EFI_ERROR (Status)) {
     373    DEBUG ((DEBUG_ERROR, "%a failed to create image properties record\n", __func__));
     374    FreePool (ImageRecord);
    459375    goto Finish;
    460376  }
    461 
    462   //
    463   // Get SectionAlignment
    464   //
    465   if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
    466     SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment;
    467   } else {
    468     SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment;
    469   }
    470 
    471   IsAligned = IsMemoryProtectionSectionAligned (SectionAlignment, LoadedImage->ImageCodeType);
    472   if (!IsAligned) {
    473     DEBUG ((
    474       DEBUG_VERBOSE,
    475       "!!!!!!!!  ProtectUefiImageCommon - Section Alignment(0x%x) is incorrect  !!!!!!!!\n",
    476       SectionAlignment
    477       ));
    478     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    479     if (PdbPointer != NULL) {
    480       DEBUG ((DEBUG_VERBOSE, "!!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    481     }
    482 
    483     goto Finish;
    484   }
    485 
    486   Section = (EFI_IMAGE_SECTION_HEADER *)(
    487                                          (UINT8 *)(UINTN)ImageAddress +
    488                                          PeCoffHeaderOffset +
    489                                          sizeof (UINT32) +
    490                                          sizeof (EFI_IMAGE_FILE_HEADER) +
    491                                          Hdr.Pe32->FileHeader.SizeOfOptionalHeader
    492                                          );
    493   ImageRecord->CodeSegmentCount = 0;
    494   InitializeListHead (&ImageRecord->CodeSegmentList);
    495   for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
    496     Name = Section[Index].Name;
    497     DEBUG ((
    498       DEBUG_VERBOSE,
    499       "  Section - '%c%c%c%c%c%c%c%c'\n",
    500       Name[0],
    501       Name[1],
    502       Name[2],
    503       Name[3],
    504       Name[4],
    505       Name[5],
    506       Name[6],
    507       Name[7]
    508       ));
    509 
    510     //
    511     // Instead of assuming that a PE/COFF section of type EFI_IMAGE_SCN_CNT_CODE
    512     // can always be mapped read-only, classify a section as a code section only
    513     // if it has the executable attribute set and the writable attribute cleared.
    514     //
    515     // This adheres more closely to the PE/COFF spec, and avoids issues with
    516     // Linux OS loaders that may consist of a single read/write/execute section.
    517     //
    518     if ((Section[Index].Characteristics & (EFI_IMAGE_SCN_MEM_WRITE | EFI_IMAGE_SCN_MEM_EXECUTE)) == EFI_IMAGE_SCN_MEM_EXECUTE) {
    519       DEBUG ((DEBUG_VERBOSE, "  VirtualSize          - 0x%08x\n", Section[Index].Misc.VirtualSize));
    520       DEBUG ((DEBUG_VERBOSE, "  VirtualAddress       - 0x%08x\n", Section[Index].VirtualAddress));
    521       DEBUG ((DEBUG_VERBOSE, "  SizeOfRawData        - 0x%08x\n", Section[Index].SizeOfRawData));
    522       DEBUG ((DEBUG_VERBOSE, "  PointerToRawData     - 0x%08x\n", Section[Index].PointerToRawData));
    523       DEBUG ((DEBUG_VERBOSE, "  PointerToRelocations - 0x%08x\n", Section[Index].PointerToRelocations));
    524       DEBUG ((DEBUG_VERBOSE, "  PointerToLinenumbers - 0x%08x\n", Section[Index].PointerToLinenumbers));
    525       DEBUG ((DEBUG_VERBOSE, "  NumberOfRelocations  - 0x%08x\n", Section[Index].NumberOfRelocations));
    526       DEBUG ((DEBUG_VERBOSE, "  NumberOfLinenumbers  - 0x%08x\n", Section[Index].NumberOfLinenumbers));
    527       DEBUG ((DEBUG_VERBOSE, "  Characteristics      - 0x%08x\n", Section[Index].Characteristics));
    528 
    529       //
    530       // Step 2: record code section
    531       //
    532       ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection));
    533       if (ImageRecordCodeSection == NULL) {
    534         return;
    535       }
    536 
    537       ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE;
    538 
    539       ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress;
    540       ImageRecordCodeSection->CodeSegmentSize = ALIGN_VALUE (Section[Index].SizeOfRawData, SectionAlignment);
    541 
    542       DEBUG ((DEBUG_VERBOSE, "ImageCode: 0x%016lx - 0x%016lx\n", ImageRecordCodeSection->CodeSegmentBase, ImageRecordCodeSection->CodeSegmentSize));
    543 
    544       InsertTailList (&ImageRecord->CodeSegmentList, &ImageRecordCodeSection->Link);
    545       ImageRecord->CodeSegmentCount++;
    546     }
    547   }
    548 
    549   if (ImageRecord->CodeSegmentCount == 0) {
    550     //
    551     // If a UEFI executable consists of a single read+write+exec PE/COFF
    552     // section, that isn't actually an error. The image can be launched
    553     // alright, only image protection cannot be applied to it fully.
    554     //
    555     // One example that elicits this is (some) Linux kernels (with the EFI stub
    556     // of course).
    557     //
    558     DEBUG ((DEBUG_WARN, "!!!!!!!!  ProtectUefiImageCommon - CodeSegmentCount is 0  !!!!!!!!\n"));
    559     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    560     if (PdbPointer != NULL) {
    561       DEBUG ((DEBUG_WARN, "!!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    562     }
    563 
    564     goto Finish;
    565   }
    566 
    567   //
    568   // Final
    569   //
    570   SortImageRecordCodeSection (ImageRecord);
    571   //
    572   // Check overlap all section in ImageBase/Size
    573   //
    574   if (!IsImageRecordCodeSectionValid (ImageRecord)) {
    575     DEBUG ((DEBUG_ERROR, "IsImageRecordCodeSectionValid - FAIL\n"));
    576     goto Finish;
    577   }
    578 
    579   //
    580   // Round up the ImageSize, some CPU arch may return EFI_UNSUPPORTED if ImageSize is not aligned.
    581   // Given that the loader always allocates full pages, we know the space after the image is not used.
    582   //
    583   ImageRecord->ImageSize = ALIGN_VALUE (LoadedImage->ImageSize, EFI_PAGE_SIZE);
    584377
    585378  //
     
    630423          0
    631424          );
    632         FreeImageRecord (ImageRecord);
     425        DeleteImagePropertiesRecord (ImageRecord);
    633426        return;
    634427      }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/DxeIplPeim/Ia32/DxeLoadFunc.c

    r101291 r105670  
    22  Ia32-specific functionality for DxeLoad.
    33
    4 Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
     4Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.<BR>
    55Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
    66
     
    280280    //
    281281    // Compute the top of the stack we were allocated, which is used to load X64 dxe core.
    282     // Pre-allocate a 32 bytes which confroms to x64 calling convention.
     282    // Pre-allocate a 32 bytes which conforms to x64 calling convention.
    283283    //
    284284    // The first four parameters to a function are passed in rcx, rdx, r8 and r9.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/DxeIplPeim/X64/VirtualMemory.c

    r101291 r105670  
    697697  UINTN                                        BigPageAddress;
    698698  VOID                                         *Hob;
    699   BOOLEAN                                      Page5LevelSupport;
     699  BOOLEAN                                      Page5LevelEnabled;
    700700  BOOLEAN                                      Page1GSupport;
    701701  PAGE_TABLE_1G_ENTRY                          *PageDirectory1GEntry;
     
    745745    //
    746746    Cr4.UintN         = AsmReadCr4 ();
    747     Page5LevelSupport = (Cr4.Bits.LA57 != 0);
    748     ASSERT (PcdGetBool (PcdUse5LevelPageTable) == Page5LevelSupport);
     747    Page5LevelEnabled = (Cr4.Bits.LA57 != 0);
     748    if (Page5LevelEnabled) {
     749      ASSERT (PcdGetBool (PcdUse5LevelPageTable));
     750    }
    749751  } else {
    750752    //
    751753    // If cpu runs in 32bit protected mode PEI, Page table Level in DXE is decided by PCD and feature capability.
    752754    //
    753     Page5LevelSupport = FALSE;
     755    Page5LevelEnabled = FALSE;
    754756    if (PcdGetBool (PcdUse5LevelPageTable)) {
    755757      AsmCpuidEx (
     
    762764        );
    763765      if (EcxFlags.Bits.FiveLevelPage != 0) {
    764         Page5LevelSupport = TRUE;
     766        Page5LevelEnabled = TRUE;
    765767      }
    766768    }
    767769  }
    768770
    769   DEBUG ((DEBUG_INFO, "AddressBits=%u 5LevelPaging=%u 1GPage=%u\n", PhysicalAddressBits, Page5LevelSupport, Page1GSupport));
     771  DEBUG ((DEBUG_INFO, "AddressBits=%u 5LevelPaging=%u 1GPage=%u\n", PhysicalAddressBits, Page5LevelEnabled, Page1GSupport));
    770772
    771773  //
     
    775777  //
    776778  ASSERT (PhysicalAddressBits <= 52);
    777   if (!Page5LevelSupport && (PhysicalAddressBits > 48)) {
     779  if (!Page5LevelEnabled && (PhysicalAddressBits > 48)) {
    778780    PhysicalAddressBits = 48;
    779781  }
     
    810812  // Substract the one page occupied by PML5 entries if 5-Level Paging is disabled.
    811813  //
    812   if (!Page5LevelSupport) {
     814  if (!Page5LevelEnabled) {
    813815    TotalPagesNum--;
    814816  }
     
    830832  //
    831833  PageMap = (VOID *)BigPageAddress;
    832   if (Page5LevelSupport) {
     834  if (Page5LevelEnabled) {
    833835    //
    834836    // By architecture only one PageMapLevel5 exists - so lets allocate storage for it.
     
    852854    BigPageAddress    += SIZE_4KB;
    853855
    854     if (Page5LevelSupport) {
     856    if (Page5LevelEnabled) {
    855857      //
    856858      // Make a PML5 Entry
     
    946948  }
    947949
    948   if (Page5LevelSupport) {
     950  if (Page5LevelEnabled) {
    949951    Cr4.UintN     = AsmReadCr4 ();
    950952    Cr4.Bits.LA57 = 1;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Pei/Dispatcher/Dispatcher.c

    r101291 r105670  
    22  EFI PEI Core dispatch services
    33
    4 Copyright (c) 2006 - 2019, Intel Corporation. All rights reserved.<BR>
     4Copyright (c) 2006 - 2024, Intel Corporation. All rights reserved.<BR>
    55(C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
    66SPDX-License-Identifier: BSD-2-Clause-Patent
     
    11851185  PEI_CORE_FV_HANDLE            PeiCoreFvHandle;
    11861186  EFI_PEI_CORE_FV_LOCATION_PPI  *PeiCoreFvLocationPpi;
     1187  EFI_PEI_HOB_POINTERS          Hob;
     1188  EDKII_MIGRATION_INFO          *MigrationInfo;
     1189  TO_MIGRATE_FV_INFO            *ToMigrateFvInfo;
     1190  UINT32                        FvMigrationFlags;
    11871191  EDKII_MIGRATED_FV_INFO        MigratedFvInfo;
     1192  UINTN                         Index;
    11881193
    11891194  ASSERT (Private->PeiMemoryInstalled);
     
    12111216
    12121217  ConvertPeiCorePpiPointers (Private, &PeiCoreFvHandle);
     1218
     1219  Hob.Raw = GetFirstGuidHob (&gEdkiiMigrationInfoGuid);
     1220  if (Hob.Raw != NULL) {
     1221    MigrationInfo = GET_GUID_HOB_DATA (Hob);
     1222  } else {
     1223    MigrationInfo = NULL;
     1224  }
    12131225
    12141226  for (FvIndex = 0; FvIndex < Private->FvCount; FvIndex++) {
     
    12251237        )
    12261238    {
    1227       //
    1228       // Allocate page to save the rebased PEIMs, the PEIMs will get dispatched later.
     1239      if ((MigrationInfo == NULL) || (MigrationInfo->MigrateAll == TRUE)) {
     1240        //
     1241        // Migrate all FVs and copy raw data
     1242        //
     1243        FvMigrationFlags = FLAGS_FV_RAW_DATA_COPY;
     1244      } else {
     1245        for (Index = 0; Index < MigrationInfo->ToMigrateFvCount; Index++) {
     1246          ToMigrateFvInfo = ((TO_MIGRATE_FV_INFO *)(MigrationInfo + 1)) + Index;
     1247          if (ToMigrateFvInfo->FvOrgBaseOnTempRam == (UINT32)(UINTN)FvHeader) {
     1248            //
     1249            // This FV is to migrate
     1250            //
     1251            FvMigrationFlags = ToMigrateFvInfo->FvMigrationFlags;
     1252            break;
     1253          }
     1254        }
     1255
     1256        if (Index == MigrationInfo->ToMigrateFvCount) {
     1257          //
     1258          // This FV is not expected to migrate
     1259          //
     1260          continue;
     1261        }
     1262      }
     1263
     1264      //
     1265      // Allocate pages to save the rebased PEIMs, the PEIMs will get dispatched later.
    12291266      //
    12301267      Status =  PeiServicesAllocatePages (
     
    12351272      ASSERT_EFI_ERROR (Status);
    12361273      MigratedFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvHeaderAddress;
    1237 
    1238       //
    1239       // Allocate pool to save the raw PEIMs, which is used to keep consistent context across
    1240       // multiple boot and PCR0 will keep the same no matter if the address of allocated page is changed.
    1241       //
    1242       Status =  PeiServicesAllocatePages (
    1243                   EfiBootServicesCode,
    1244                   EFI_SIZE_TO_PAGES ((UINTN)FvHeader->FvLength),
    1245                   &FvHeaderAddress
    1246                   );
    1247       ASSERT_EFI_ERROR (Status);
    1248       RawDataFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvHeaderAddress;
     1274      CopyMem (MigratedFvHeader, FvHeader, (UINTN)FvHeader->FvLength);
    12491275
    12501276      DEBUG ((
     
    12571283
    12581284      //
    1259       // Copy the context to the rebased pages and raw pages, and create hob to save the
    1260       // information. The MigratedFvInfo HOB will never be produced when
    1261       // PcdMigrateTemporaryRamFirmwareVolumes is FALSE, because the PCD control the
    1262       // feature.
    1263       //
    1264       CopyMem (MigratedFvHeader, FvHeader, (UINTN)FvHeader->FvLength);
    1265       CopyMem (RawDataFvHeader, MigratedFvHeader, (UINTN)FvHeader->FvLength);
     1285      // Create hob to save MigratedFvInfo, this hob will only be produced when
     1286      // Migration feature PCD PcdMigrateTemporaryRamFirmwareVolumes is set to TRUE.
     1287      //
    12661288      MigratedFvInfo.FvOrgBase  = (UINT32)(UINTN)FvHeader;
    12671289      MigratedFvInfo.FvNewBase  = (UINT32)(UINTN)MigratedFvHeader;
    1268       MigratedFvInfo.FvDataBase = (UINT32)(UINTN)RawDataFvHeader;
     1290      MigratedFvInfo.FvDataBase = 0;
    12691291      MigratedFvInfo.FvLength   = (UINT32)(UINTN)FvHeader->FvLength;
     1292
     1293      //
     1294      // When FLAGS_FV_RAW_DATA_COPY bit is set, copy the context to the raw pages and
     1295      // reset raw data base address in MigratedFvInfo hob.
     1296      //
     1297      if ((FvMigrationFlags & FLAGS_FV_RAW_DATA_COPY) == FLAGS_FV_RAW_DATA_COPY) {
     1298        //
     1299        // Allocate pages to save the raw PEIMs
     1300        //
     1301        Status =  PeiServicesAllocatePages (
     1302                    EfiBootServicesCode,
     1303                    EFI_SIZE_TO_PAGES ((UINTN)FvHeader->FvLength),
     1304                    &FvHeaderAddress
     1305                    );
     1306        ASSERT_EFI_ERROR (Status);
     1307        RawDataFvHeader = (EFI_FIRMWARE_VOLUME_HEADER *)(UINTN)FvHeaderAddress;
     1308        CopyMem (RawDataFvHeader, FvHeader, (UINTN)FvHeader->FvLength);
     1309        MigratedFvInfo.FvDataBase = (UINT32)(UINTN)RawDataFvHeader;
     1310      }
     1311
    12701312      BuildGuidDataHob (&gEdkiiMigratedFvInfoGuid, &MigratedFvInfo, sizeof (MigratedFvInfo));
    12711313
     
    13301372    }
    13311373  }
    1332 
    1333   RemoveFvHobsInTemporaryMemory (Private);
    13341374
    13351375  return Status;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Pei/Memory/MemoryServices.c

    r99404 r105670  
    165165
    166166  Private->FreePhysicalMemoryTop = NewMemPagesBase;
    167 }
    168 
    169 /**
    170   Removes any FV HOBs whose base address is not in PEI installed memory.
    171 
    172   @param[in] Private          Pointer to PeiCore's private data structure.
    173 
    174 **/
    175 VOID
    176 RemoveFvHobsInTemporaryMemory (
    177   IN PEI_CORE_INSTANCE  *Private
    178   )
    179 {
    180   EFI_PEI_HOB_POINTERS     Hob;
    181   EFI_HOB_FIRMWARE_VOLUME  *FirmwareVolumeHob;
    182 
    183   DEBUG ((DEBUG_INFO, "Removing FVs in FV HOB not already migrated to permanent memory.\n"));
    184 
    185   for (Hob.Raw = GetHobList (); !END_OF_HOB_LIST (Hob); Hob.Raw = GET_NEXT_HOB (Hob)) {
    186     if ((GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV) || (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV2) || (GET_HOB_TYPE (Hob) == EFI_HOB_TYPE_FV3)) {
    187       FirmwareVolumeHob = Hob.FirmwareVolume;
    188       DEBUG ((DEBUG_INFO, "  Found FV HOB.\n"));
    189       DEBUG ((
    190         DEBUG_INFO,
    191         "    BA=%016lx  L=%016lx\n",
    192         FirmwareVolumeHob->BaseAddress,
    193         FirmwareVolumeHob->Length
    194         ));
    195       if (
    196           !(
    197             ((EFI_PHYSICAL_ADDRESS)(UINTN)FirmwareVolumeHob->BaseAddress >= Private->PhysicalMemoryBegin) &&
    198             (((EFI_PHYSICAL_ADDRESS)(UINTN)FirmwareVolumeHob->BaseAddress + (FirmwareVolumeHob->Length - 1)) < Private->FreePhysicalMemoryTop)
    199             )
    200           )
    201       {
    202         DEBUG ((DEBUG_INFO, "      Removing FV HOB to an FV in T-RAM (was not migrated).\n"));
    203         Hob.Header->HobType = EFI_HOB_TYPE_UNUSED;
    204       }
    205     }
    206   }
    207167}
    208168
     
    625585
    626586  if ((RUNTIME_PAGE_ALLOCATION_GRANULARITY > DEFAULT_PAGE_ALLOCATION_GRANULARITY) &&
    627       ((MemoryType == EfiACPIReclaimMemory) ||
     587      ((MemoryType == EfiReservedMemoryType) ||
    628588       (MemoryType == EfiACPIMemoryNVS) ||
    629589       (MemoryType == EfiRuntimeServicesCode) ||
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Pei/PeiMain.h

    r99404 r105670  
    10481048
    10491049/**
    1050   Removes any FV HOBs whose base address is not in PEI installed memory.
    1051 
    1052   @param[in] Private          Pointer to PeiCore's private data structure.
    1053 
    1054 **/
    1055 VOID
    1056 RemoveFvHobsInTemporaryMemory (
    1057   IN PEI_CORE_INSTANCE  *Private
    1058   );
    1059 
    1060 /**
    10611050  Migrate the base address in firmware volume allocation HOBs
    10621051  from temporary memory to PEI installed memory.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/Pei/PeiMain.inf

    r89983 r105670  
    7979  gStatusCodeCallbackGuid
    8080  gEdkiiMigratedFvInfoGuid                      ## SOMETIMES_PRODUCES     ## HOB
     81  gEdkiiMigrationInfoGuid                       ## SOMETIMES_CONSUMES     ## HOB
    8182
    8283[Ppis]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/PiSmmCore/MemoryAttributesTable.c

    r99404 r105670  
    1515#include <Library/DebugLib.h>
    1616#include <Library/PcdLib.h>
     17#include <Library/ImagePropertiesRecordLib.h>
    1718
    1819#include <Library/PeCoffLib.h>
     
    2526#define PREVIOUS_MEMORY_DESCRIPTOR(MemoryDescriptor, Size) \
    2627  ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)(MemoryDescriptor) - (Size)))
    27 
    28 #define IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE  SIGNATURE_32 ('I','P','R','C')
    29 
    30 typedef struct {
    31   UINT32                  Signature;
    32   LIST_ENTRY              Link;
    33   EFI_PHYSICAL_ADDRESS    CodeSegmentBase;
    34   UINT64                  CodeSegmentSize;
    35 } IMAGE_PROPERTIES_RECORD_CODE_SECTION;
    36 
    37 #define IMAGE_PROPERTIES_RECORD_SIGNATURE  SIGNATURE_32 ('I','P','R','D')
    38 
    39 typedef struct {
    40   UINT32                  Signature;
    41   LIST_ENTRY              Link;
    42   EFI_PHYSICAL_ADDRESS    ImageBase;
    43   UINT64                  ImageSize;
    44   UINTN                   CodeSegmentCount;
    45   LIST_ENTRY              CodeSegmentList;
    46 } IMAGE_PROPERTIES_RECORD;
    4728
    4829#define IMAGE_PROPERTIES_PRIVATE_DATA_SIGNATURE  SIGNATURE_32 ('I','P','P','D')
     
    6950// Below functions are for MemoryMap
    7051//
    71 
    72 /**
    73   Converts a number of EFI_PAGEs to a size in bytes.
    74 
    75   NOTE: Do not use EFI_PAGES_TO_SIZE because it handles UINTN only.
    76 
    77   @param[in]  Pages     The number of EFI_PAGES.
    78 
    79   @return  The number of bytes associated with the number of EFI_PAGEs specified
    80            by Pages.
    81 **/
    82 STATIC
    83 UINT64
    84 EfiPagesToSize (
    85   IN UINT64  Pages
    86   )
    87 {
    88   return LShiftU64 (Pages, EFI_PAGE_SHIFT);
    89 }
    90 
    91 /**
    92   Converts a size, in bytes, to a number of EFI_PAGESs.
    93 
    94   NOTE: Do not use EFI_SIZE_TO_PAGES because it handles UINTN only.
    95 
    96   @param[in]  Size      A size in bytes.
    97 
    98   @return  The number of EFI_PAGESs associated with the number of bytes specified
    99            by Size.
    100 
    101 **/
    102 STATIC
    103 UINT64
    104 EfiSizeToPages (
    105   IN UINT64  Size
    106   )
    107 {
    108   return RShiftU64 (Size, EFI_PAGE_SHIFT) + ((((UINTN)Size) & EFI_PAGE_MASK) ? 1 : 0);
    109 }
    110 
    111 /**
    112   Sort memory map entries based upon PhysicalStart, from low to high.
    113 
    114   @param[in,out]  MemoryMap         A pointer to the buffer in which firmware places
    115                                     the current memory map.
    116   @param[in]      MemoryMapSize     Size, in bytes, of the MemoryMap buffer.
    117   @param[in]      DescriptorSize    Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    118 **/
    119 STATIC
    120 VOID
    121 SortMemoryMap (
    122   IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
    123   IN UINTN                      MemoryMapSize,
    124   IN UINTN                      DescriptorSize
    125   )
    126 {
    127   EFI_MEMORY_DESCRIPTOR  *MemoryMapEntry;
    128   EFI_MEMORY_DESCRIPTOR  *NextMemoryMapEntry;
    129   EFI_MEMORY_DESCRIPTOR  *MemoryMapEnd;
    130   EFI_MEMORY_DESCRIPTOR  TempMemoryMap;
    131 
    132   MemoryMapEntry     = MemoryMap;
    133   NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    134   MemoryMapEnd       = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + MemoryMapSize);
    135   while (MemoryMapEntry < MemoryMapEnd) {
    136     while (NextMemoryMapEntry < MemoryMapEnd) {
    137       if (MemoryMapEntry->PhysicalStart > NextMemoryMapEntry->PhysicalStart) {
    138         CopyMem (&TempMemoryMap, MemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR));
    139         CopyMem (MemoryMapEntry, NextMemoryMapEntry, sizeof (EFI_MEMORY_DESCRIPTOR));
    140         CopyMem (NextMemoryMapEntry, &TempMemoryMap, sizeof (EFI_MEMORY_DESCRIPTOR));
    141       }
    142 
    143       NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (NextMemoryMapEntry, DescriptorSize);
    144     }
    145 
    146     MemoryMapEntry     = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    147     NextMemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    148   }
    149 
    150   return;
    151 }
    15252
    15353/**
     
    18484
    18585    do {
    186       MemoryBlockLength = (UINT64)(EfiPagesToSize (MemoryMapEntry->NumberOfPages));
     86      MemoryBlockLength = LShiftU64 (MemoryMapEntry->NumberOfPages, EFI_PAGE_SHIFT);
    18787      if (((UINTN)NextMemoryMapEntry < (UINTN)MemoryMapEnd) &&
    18888          (MemoryMapEntry->Type == NextMemoryMapEntry->Type) &&
     
    251151    MemoryMapEntry = NEXT_MEMORY_DESCRIPTOR (MemoryMapEntry, DescriptorSize);
    252152  }
    253 
    254   return;
    255 }
    256 
    257 /**
    258   Return the first image record, whose [ImageBase, ImageSize] covered by [Buffer, Length].
    259 
    260   @param[in] Buffer  Start Address
    261   @param[in] Length  Address length
    262 
    263   @return first image record covered by [buffer, length]
    264 **/
    265 STATIC
    266 IMAGE_PROPERTIES_RECORD *
    267 GetImageRecordByAddress (
    268   IN EFI_PHYSICAL_ADDRESS  Buffer,
    269   IN UINT64                Length
    270   )
    271 {
    272   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    273   LIST_ENTRY               *ImageRecordLink;
    274   LIST_ENTRY               *ImageRecordList;
    275 
    276   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    277 
    278   for (ImageRecordLink = ImageRecordList->ForwardLink;
    279        ImageRecordLink != ImageRecordList;
    280        ImageRecordLink = ImageRecordLink->ForwardLink)
    281   {
    282     ImageRecord = CR (
    283                     ImageRecordLink,
    284                     IMAGE_PROPERTIES_RECORD,
    285                     Link,
    286                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    287                     );
    288 
    289     if ((Buffer <= ImageRecord->ImageBase) &&
    290         (Buffer + Length >= ImageRecord->ImageBase + ImageRecord->ImageSize))
    291     {
    292       return ImageRecord;
    293     }
    294   }
    295 
    296   return NULL;
    297 }
    298 
    299 /**
    300   Set the memory map to new entries, according to one old entry,
    301   based upon PE code section and data section in image record
    302 
    303   @param[in]       ImageRecord            An image record whose [ImageBase, ImageSize] covered
    304                                           by old memory map entry.
    305   @param[in, out]  NewRecord              A pointer to several new memory map entries.
    306                                           The caller guarantee the buffer size be 1 +
    307                                           (SplitRecordCount * DescriptorSize) calculated
    308                                           below.
    309   @param[in]       OldRecord              A pointer to one old memory map entry.
    310   @param[in]       DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    311 **/
    312 STATIC
    313 UINTN
    314 SetNewRecord (
    315   IN IMAGE_PROPERTIES_RECORD    *ImageRecord,
    316   IN OUT EFI_MEMORY_DESCRIPTOR  *NewRecord,
    317   IN EFI_MEMORY_DESCRIPTOR      *OldRecord,
    318   IN UINTN                      DescriptorSize
    319   )
    320 {
    321   EFI_MEMORY_DESCRIPTOR                 TempRecord;
    322   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    323   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    324   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    325   LIST_ENTRY                            *ImageRecordCodeSectionList;
    326   UINTN                                 NewRecordCount;
    327   UINT64                                PhysicalEnd;
    328   UINT64                                ImageEnd;
    329 
    330   CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR));
    331   PhysicalEnd    = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages);
    332   NewRecordCount = 0;
    333 
    334   //
    335   // Always create a new entry for non-PE image record
    336   //
    337   if (ImageRecord->ImageBase > TempRecord.PhysicalStart) {
    338     NewRecord->Type          = TempRecord.Type;
    339     NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    340     NewRecord->VirtualStart  = 0;
    341     NewRecord->NumberOfPages = EfiSizeToPages (ImageRecord->ImageBase - TempRecord.PhysicalStart);
    342     NewRecord->Attribute     = TempRecord.Attribute;
    343     NewRecord                = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    344     NewRecordCount++;
    345     TempRecord.PhysicalStart = ImageRecord->ImageBase;
    346     TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart);
    347   }
    348 
    349   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    350 
    351   ImageRecordCodeSectionLink    = ImageRecordCodeSectionList->ForwardLink;
    352   ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList;
    353   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    354     ImageRecordCodeSection = CR (
    355                                ImageRecordCodeSectionLink,
    356                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    357                                Link,
    358                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    359                                );
    360     ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    361 
    362     if (TempRecord.PhysicalStart <= ImageRecordCodeSection->CodeSegmentBase) {
    363       //
    364       // DATA
    365       //
    366       NewRecord->Type          = EfiRuntimeServicesData;
    367       NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    368       NewRecord->VirtualStart  = 0;
    369       NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentBase - NewRecord->PhysicalStart);
    370       NewRecord->Attribute     = TempRecord.Attribute | EFI_MEMORY_XP;
    371       if (NewRecord->NumberOfPages != 0) {
    372         NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    373         NewRecordCount++;
    374       }
    375 
    376       //
    377       // CODE
    378       //
    379       NewRecord->Type          = EfiRuntimeServicesCode;
    380       NewRecord->PhysicalStart = ImageRecordCodeSection->CodeSegmentBase;
    381       NewRecord->VirtualStart  = 0;
    382       NewRecord->NumberOfPages = EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize);
    383       NewRecord->Attribute     = (TempRecord.Attribute & (~EFI_MEMORY_XP)) | EFI_MEMORY_RO;
    384       if (NewRecord->NumberOfPages != 0) {
    385         NewRecord = NEXT_MEMORY_DESCRIPTOR (NewRecord, DescriptorSize);
    386         NewRecordCount++;
    387       }
    388 
    389       TempRecord.PhysicalStart = ImageRecordCodeSection->CodeSegmentBase + EfiPagesToSize (EfiSizeToPages (ImageRecordCodeSection->CodeSegmentSize));
    390       TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - TempRecord.PhysicalStart);
    391       if (TempRecord.NumberOfPages == 0) {
    392         break;
    393       }
    394     }
    395   }
    396 
    397   ImageEnd = ImageRecord->ImageBase + ImageRecord->ImageSize;
    398 
    399   //
    400   // Final DATA
    401   //
    402   if (TempRecord.PhysicalStart < ImageEnd) {
    403     NewRecord->Type          = EfiRuntimeServicesData;
    404     NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    405     NewRecord->VirtualStart  = 0;
    406     NewRecord->NumberOfPages = EfiSizeToPages (ImageEnd - TempRecord.PhysicalStart);
    407     NewRecord->Attribute     = TempRecord.Attribute | EFI_MEMORY_XP;
    408     NewRecordCount++;
    409   }
    410 
    411   return NewRecordCount;
    412 }
    413 
    414 /**
    415   Return the max number of new splitted entries, according to one old entry,
    416   based upon PE code section and data section.
    417 
    418   @param[in]  OldRecord              A pointer to one old memory map entry.
    419 
    420   @retval  0 no entry need to be splitted.
    421   @return  the max number of new splitted entries
    422 **/
    423 STATIC
    424 UINTN
    425 GetMaxSplitRecordCount (
    426   IN EFI_MEMORY_DESCRIPTOR  *OldRecord
    427   )
    428 {
    429   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    430   UINTN                    SplitRecordCount;
    431   UINT64                   PhysicalStart;
    432   UINT64                   PhysicalEnd;
    433 
    434   SplitRecordCount = 0;
    435   PhysicalStart    = OldRecord->PhysicalStart;
    436   PhysicalEnd      = OldRecord->PhysicalStart + EfiPagesToSize (OldRecord->NumberOfPages);
    437 
    438   do {
    439     ImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart);
    440     if (ImageRecord == NULL) {
    441       break;
    442     }
    443 
    444     SplitRecordCount += (2 * ImageRecord->CodeSegmentCount + 2);
    445     PhysicalStart     = ImageRecord->ImageBase + ImageRecord->ImageSize;
    446   } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd));
    447 
    448   return SplitRecordCount;
    449 }
    450 
    451 /**
    452   Split the memory map to new entries, according to one old entry,
    453   based upon PE code section and data section.
    454 
    455   @param[in]       OldRecord              A pointer to one old memory map entry.
    456   @param[in, out]  NewRecord              A pointer to several new memory map entries.
    457                                           The caller guarantee the buffer size be 1 +
    458                                           (SplitRecordCount * DescriptorSize) calculated
    459                                           below.
    460   @param[in]       MaxSplitRecordCount    The max number of splitted entries
    461   @param[in]       DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    462 
    463   @retval  0 no entry is splitted.
    464   @return  the real number of splitted record.
    465 **/
    466 STATIC
    467 UINTN
    468 SplitRecord (
    469   IN EFI_MEMORY_DESCRIPTOR      *OldRecord,
    470   IN OUT EFI_MEMORY_DESCRIPTOR  *NewRecord,
    471   IN UINTN                      MaxSplitRecordCount,
    472   IN UINTN                      DescriptorSize
    473   )
    474 {
    475   EFI_MEMORY_DESCRIPTOR    TempRecord;
    476   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    477   IMAGE_PROPERTIES_RECORD  *NewImageRecord;
    478   UINT64                   PhysicalStart;
    479   UINT64                   PhysicalEnd;
    480   UINTN                    NewRecordCount;
    481   UINTN                    TotalNewRecordCount;
    482 
    483   if (MaxSplitRecordCount == 0) {
    484     CopyMem (NewRecord, OldRecord, DescriptorSize);
    485     return 0;
    486   }
    487 
    488   TotalNewRecordCount = 0;
    489 
    490   //
    491   // Override previous record
    492   //
    493   CopyMem (&TempRecord, OldRecord, sizeof (EFI_MEMORY_DESCRIPTOR));
    494   PhysicalStart = TempRecord.PhysicalStart;
    495   PhysicalEnd   = TempRecord.PhysicalStart + EfiPagesToSize (TempRecord.NumberOfPages);
    496 
    497   ImageRecord = NULL;
    498   do {
    499     NewImageRecord = GetImageRecordByAddress (PhysicalStart, PhysicalEnd - PhysicalStart);
    500     if (NewImageRecord == NULL) {
    501       //
    502       // No more image covered by this range, stop
    503       //
    504       if (PhysicalEnd > PhysicalStart) {
    505         //
    506         // Always create a new entry for non-PE image record
    507         //
    508         NewRecord->Type          = TempRecord.Type;
    509         NewRecord->PhysicalStart = TempRecord.PhysicalStart;
    510         NewRecord->VirtualStart  = 0;
    511         NewRecord->NumberOfPages = TempRecord.NumberOfPages;
    512         NewRecord->Attribute     = TempRecord.Attribute;
    513         TotalNewRecordCount++;
    514       }
    515 
    516       break;
    517     }
    518 
    519     ImageRecord = NewImageRecord;
    520 
    521     //
    522     // Set new record
    523     //
    524     NewRecordCount       = SetNewRecord (ImageRecord, NewRecord, &TempRecord, DescriptorSize);
    525     TotalNewRecordCount += NewRecordCount;
    526     NewRecord            = (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)NewRecord + NewRecordCount * DescriptorSize);
    527 
    528     //
    529     // Update PhysicalStart, in order to exclude the image buffer already splitted.
    530     //
    531     PhysicalStart            = ImageRecord->ImageBase + ImageRecord->ImageSize;
    532     TempRecord.PhysicalStart = PhysicalStart;
    533     TempRecord.NumberOfPages = EfiSizeToPages (PhysicalEnd - PhysicalStart);
    534   } while ((ImageRecord != NULL) && (PhysicalStart < PhysicalEnd));
    535 
    536   return TotalNewRecordCount - 1;
    537 }
    538 
    539 /**
    540   Split the original memory map, and add more entries to describe PE code section and data section.
    541   This function will set EfiRuntimeServicesData to be EFI_MEMORY_XP.
    542   This function will merge entries with same attributes finally.
    543 
    544   NOTE: It assumes PE code/data section are page aligned.
    545   NOTE: It assumes enough entry is prepared for new memory map.
    546 
    547   Split table:
    548    +---------------+
    549    | Record X      |
    550    +---------------+
    551    | Record RtCode |
    552    +---------------+
    553    | Record Y      |
    554    +---------------+
    555    ==>
    556    +---------------+
    557    | Record X      |
    558    +---------------+
    559    | Record RtCode |
    560    +---------------+ ----
    561    | Record RtData |     |
    562    +---------------+     |
    563    | Record RtCode |     |-> PE/COFF1
    564    +---------------+     |
    565    | Record RtData |     |
    566    +---------------+ ----
    567    | Record RtCode |
    568    +---------------+ ----
    569    | Record RtData |     |
    570    +---------------+     |
    571    | Record RtCode |     |-> PE/COFF2
    572    +---------------+     |
    573    | Record RtData |     |
    574    +---------------+ ----
    575    | Record RtCode |
    576    +---------------+
    577    | Record Y      |
    578    +---------------+
    579 
    580   @param[in, out]  MemoryMapSize          A pointer to the size, in bytes, of the
    581                                           MemoryMap buffer. On input, this is the size of
    582                                           old MemoryMap before split. The actual buffer
    583                                           size of MemoryMap is MemoryMapSize +
    584                                           (AdditionalRecordCount * DescriptorSize) calculated
    585                                           below. On output, it is the size of new MemoryMap
    586                                           after split.
    587   @param[in, out]  MemoryMap              A pointer to the buffer in which firmware places
    588                                           the current memory map.
    589   @param[in]       DescriptorSize         Size, in bytes, of an individual EFI_MEMORY_DESCRIPTOR.
    590 **/
    591 STATIC
    592 VOID
    593 SplitTable (
    594   IN OUT UINTN                  *MemoryMapSize,
    595   IN OUT EFI_MEMORY_DESCRIPTOR  *MemoryMap,
    596   IN UINTN                      DescriptorSize
    597   )
    598 {
    599   INTN   IndexOld;
    600   INTN   IndexNew;
    601   UINTN  MaxSplitRecordCount;
    602   UINTN  RealSplitRecordCount;
    603   UINTN  TotalSplitRecordCount;
    604   UINTN  AdditionalRecordCount;
    605 
    606   AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 2) * mImagePropertiesPrivateData.ImageRecordCount;
    607 
    608   TotalSplitRecordCount = 0;
    609   //
    610   // Let old record point to end of valid MemoryMap buffer.
    611   //
    612   IndexOld = ((*MemoryMapSize) / DescriptorSize) - 1;
    613   //
    614   // Let new record point to end of full MemoryMap buffer.
    615   //
    616   IndexNew = ((*MemoryMapSize) / DescriptorSize) - 1 + AdditionalRecordCount;
    617   for ( ; IndexOld >= 0; IndexOld--) {
    618     MaxSplitRecordCount = GetMaxSplitRecordCount ((EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize));
    619     //
    620     // Split this MemoryMap record
    621     //
    622     IndexNew            -= MaxSplitRecordCount;
    623     RealSplitRecordCount = SplitRecord (
    624                              (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexOld * DescriptorSize),
    625                              (EFI_MEMORY_DESCRIPTOR *)((UINT8 *)MemoryMap + IndexNew * DescriptorSize),
    626                              MaxSplitRecordCount,
    627                              DescriptorSize
    628                              );
    629     //
    630     // Adjust IndexNew according to real split.
    631     //
    632     if (MaxSplitRecordCount != RealSplitRecordCount) {
    633       CopyMem (
    634         ((UINT8 *)MemoryMap + (IndexNew + MaxSplitRecordCount - RealSplitRecordCount) * DescriptorSize),
    635         ((UINT8 *)MemoryMap + IndexNew * DescriptorSize),
    636         (RealSplitRecordCount + 1) * DescriptorSize
    637         );
    638     }
    639 
    640     IndexNew               = IndexNew + MaxSplitRecordCount - RealSplitRecordCount;
    641     TotalSplitRecordCount += RealSplitRecordCount;
    642     IndexNew--;
    643   }
    644 
    645   //
    646   // Move all records to the beginning.
    647   //
    648   CopyMem (
    649     MemoryMap,
    650     (UINT8 *)MemoryMap + (AdditionalRecordCount - TotalSplitRecordCount) * DescriptorSize,
    651     (*MemoryMapSize) + TotalSplitRecordCount * DescriptorSize
    652     );
    653 
    654   *MemoryMapSize = (*MemoryMapSize) + DescriptorSize * TotalSplitRecordCount;
    655 
    656   //
    657   // Sort from low to high (Just in case)
    658   //
    659   SortMemoryMap (MemoryMap, *MemoryMapSize, DescriptorSize);
    660 
    661   //
    662   // Set RuntimeData to XP
    663   //
    664   EnforceMemoryMapAttribute (MemoryMap, *MemoryMapSize, DescriptorSize);
    665 
    666   //
    667   // Merge same type to save entry size
    668   //
    669   MergeMemoryMap (MemoryMap, MemoryMapSize, DescriptorSize);
    670153
    671154  return;
     
    730213  }
    731214
    732   AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 2) * mImagePropertiesPrivateData.ImageRecordCount;
     215  AdditionalRecordCount = (2 * mImagePropertiesPrivateData.CodeSegmentCountMax + 3) * mImagePropertiesPrivateData.ImageRecordCount;
    733216
    734217  OldMemoryMapSize = *MemoryMapSize;
     
    748231      //
    749232      ASSERT (MemoryMap != NULL);
    750       SplitTable (MemoryMapSize, MemoryMap, *DescriptorSize);
     233      SplitTable (MemoryMapSize, MemoryMap, *DescriptorSize, &mImagePropertiesPrivateData.ImageRecordList, AdditionalRecordCount);
     234
     235      //
     236      // Set RuntimeData to XP
     237      //
     238      EnforceMemoryMapAttribute (MemoryMap, *MemoryMapSize, *DescriptorSize);
     239
     240      //
     241      // Merge same type to save entry size
     242      //
     243      MergeMemoryMap (MemoryMap, MemoryMapSize, *DescriptorSize);
    751244    }
    752245  }
     
    760253
    761254/**
    762   Set MemoryProtectionAttribute according to PE/COFF image section alignment.
    763 
    764   @param[in]  SectionAlignment    PE/COFF section alignment
    765 **/
    766 STATIC
    767 VOID
    768 SetMemoryAttributesTableSectionAlignment (
    769   IN UINT32  SectionAlignment
    770   )
    771 {
    772   if (((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) &&
    773       ((mMemoryProtectionAttribute & EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA) != 0))
    774   {
    775     DEBUG ((DEBUG_VERBOSE, "SMM SetMemoryAttributesTableSectionAlignment - Clear\n"));
    776     mMemoryProtectionAttribute &= ~((UINT64)EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA);
    777   }
    778 }
    779 
    780 /**
    781   Swap two code sections in image record.
    782 
    783   @param[in]  FirstImageRecordCodeSection    first code section in image record
    784   @param[in]  SecondImageRecordCodeSection   second code section in image record
    785 **/
    786 STATIC
    787 VOID
    788 SwapImageRecordCodeSection (
    789   IN IMAGE_PROPERTIES_RECORD_CODE_SECTION  *FirstImageRecordCodeSection,
    790   IN IMAGE_PROPERTIES_RECORD_CODE_SECTION  *SecondImageRecordCodeSection
    791   )
    792 {
    793   IMAGE_PROPERTIES_RECORD_CODE_SECTION  TempImageRecordCodeSection;
    794 
    795   TempImageRecordCodeSection.CodeSegmentBase = FirstImageRecordCodeSection->CodeSegmentBase;
    796   TempImageRecordCodeSection.CodeSegmentSize = FirstImageRecordCodeSection->CodeSegmentSize;
    797 
    798   FirstImageRecordCodeSection->CodeSegmentBase = SecondImageRecordCodeSection->CodeSegmentBase;
    799   FirstImageRecordCodeSection->CodeSegmentSize = SecondImageRecordCodeSection->CodeSegmentSize;
    800 
    801   SecondImageRecordCodeSection->CodeSegmentBase = TempImageRecordCodeSection.CodeSegmentBase;
    802   SecondImageRecordCodeSection->CodeSegmentSize = TempImageRecordCodeSection.CodeSegmentSize;
    803 }
    804 
    805 /**
    806   Sort code section in image record, based upon CodeSegmentBase from low to high.
    807 
    808   @param[in]  ImageRecord    image record to be sorted
    809 **/
    810 STATIC
    811 VOID
    812 SortImageRecordCodeSection (
    813   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    814   )
    815 {
    816   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    817   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *NextImageRecordCodeSection;
    818   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    819   LIST_ENTRY                            *NextImageRecordCodeSectionLink;
    820   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    821   LIST_ENTRY                            *ImageRecordCodeSectionList;
    822 
    823   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    824 
    825   ImageRecordCodeSectionLink     = ImageRecordCodeSectionList->ForwardLink;
    826   NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    827   ImageRecordCodeSectionEndLink  = ImageRecordCodeSectionList;
    828   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    829     ImageRecordCodeSection = CR (
    830                                ImageRecordCodeSectionLink,
    831                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    832                                Link,
    833                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    834                                );
    835     while (NextImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    836       NextImageRecordCodeSection = CR (
    837                                      NextImageRecordCodeSectionLink,
    838                                      IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    839                                      Link,
    840                                      IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    841                                      );
    842       if (ImageRecordCodeSection->CodeSegmentBase > NextImageRecordCodeSection->CodeSegmentBase) {
    843         SwapImageRecordCodeSection (ImageRecordCodeSection, NextImageRecordCodeSection);
    844       }
    845 
    846       NextImageRecordCodeSectionLink = NextImageRecordCodeSectionLink->ForwardLink;
    847     }
    848 
    849     ImageRecordCodeSectionLink     = ImageRecordCodeSectionLink->ForwardLink;
    850     NextImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    851   }
    852 }
    853 
    854 /**
    855   Check if code section in image record is valid.
    856 
    857   @param[in]  ImageRecord    image record to be checked
    858 
    859   @retval TRUE  image record is valid
    860   @retval FALSE image record is invalid
    861 **/
    862 STATIC
    863 BOOLEAN
    864 IsImageRecordCodeSectionValid (
    865   IN IMAGE_PROPERTIES_RECORD  *ImageRecord
    866   )
    867 {
    868   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
    869   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *LastImageRecordCodeSection;
    870   LIST_ENTRY                            *ImageRecordCodeSectionLink;
    871   LIST_ENTRY                            *ImageRecordCodeSectionEndLink;
    872   LIST_ENTRY                            *ImageRecordCodeSectionList;
    873 
    874   DEBUG ((DEBUG_VERBOSE, "SMM ImageCode SegmentCount - 0x%x\n", ImageRecord->CodeSegmentCount));
    875 
    876   ImageRecordCodeSectionList = &ImageRecord->CodeSegmentList;
    877 
    878   ImageRecordCodeSectionLink    = ImageRecordCodeSectionList->ForwardLink;
    879   ImageRecordCodeSectionEndLink = ImageRecordCodeSectionList;
    880   LastImageRecordCodeSection    = NULL;
    881   while (ImageRecordCodeSectionLink != ImageRecordCodeSectionEndLink) {
    882     ImageRecordCodeSection = CR (
    883                                ImageRecordCodeSectionLink,
    884                                IMAGE_PROPERTIES_RECORD_CODE_SECTION,
    885                                Link,
    886                                IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE
    887                                );
    888     if (ImageRecordCodeSection->CodeSegmentSize == 0) {
    889       return FALSE;
    890     }
    891 
    892     if (ImageRecordCodeSection->CodeSegmentBase < ImageRecord->ImageBase) {
    893       return FALSE;
    894     }
    895 
    896     if (ImageRecordCodeSection->CodeSegmentBase >= MAX_ADDRESS - ImageRecordCodeSection->CodeSegmentSize) {
    897       return FALSE;
    898     }
    899 
    900     if ((ImageRecordCodeSection->CodeSegmentBase + ImageRecordCodeSection->CodeSegmentSize) > (ImageRecord->ImageBase + ImageRecord->ImageSize)) {
    901       return FALSE;
    902     }
    903 
    904     if (LastImageRecordCodeSection != NULL) {
    905       if ((LastImageRecordCodeSection->CodeSegmentBase + LastImageRecordCodeSection->CodeSegmentSize) > ImageRecordCodeSection->CodeSegmentBase) {
    906         return FALSE;
    907       }
    908     }
    909 
    910     LastImageRecordCodeSection = ImageRecordCodeSection;
    911     ImageRecordCodeSectionLink = ImageRecordCodeSectionLink->ForwardLink;
    912   }
    913 
    914   return TRUE;
    915 }
    916 
    917 /**
    918   Swap two image records.
    919 
    920   @param[in]  FirstImageRecord   first image record.
    921   @param[in]  SecondImageRecord  second image record.
    922 **/
    923 STATIC
    924 VOID
    925 SwapImageRecord (
    926   IN IMAGE_PROPERTIES_RECORD  *FirstImageRecord,
    927   IN IMAGE_PROPERTIES_RECORD  *SecondImageRecord
    928   )
    929 {
    930   IMAGE_PROPERTIES_RECORD  TempImageRecord;
    931 
    932   TempImageRecord.ImageBase        = FirstImageRecord->ImageBase;
    933   TempImageRecord.ImageSize        = FirstImageRecord->ImageSize;
    934   TempImageRecord.CodeSegmentCount = FirstImageRecord->CodeSegmentCount;
    935 
    936   FirstImageRecord->ImageBase        = SecondImageRecord->ImageBase;
    937   FirstImageRecord->ImageSize        = SecondImageRecord->ImageSize;
    938   FirstImageRecord->CodeSegmentCount = SecondImageRecord->CodeSegmentCount;
    939 
    940   SecondImageRecord->ImageBase        = TempImageRecord.ImageBase;
    941   SecondImageRecord->ImageSize        = TempImageRecord.ImageSize;
    942   SecondImageRecord->CodeSegmentCount = TempImageRecord.CodeSegmentCount;
    943 
    944   SwapListEntries (&FirstImageRecord->CodeSegmentList, &SecondImageRecord->CodeSegmentList);
    945 }
    946 
    947 /**
    948   Sort image record based upon the ImageBase from low to high.
    949 **/
    950 STATIC
    951 VOID
    952 SortImageRecord (
    953   VOID
    954   )
    955 {
    956   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    957   IMAGE_PROPERTIES_RECORD  *NextImageRecord;
    958   LIST_ENTRY               *ImageRecordLink;
    959   LIST_ENTRY               *NextImageRecordLink;
    960   LIST_ENTRY               *ImageRecordEndLink;
    961   LIST_ENTRY               *ImageRecordList;
    962 
    963   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    964 
    965   ImageRecordLink     = ImageRecordList->ForwardLink;
    966   NextImageRecordLink = ImageRecordLink->ForwardLink;
    967   ImageRecordEndLink  = ImageRecordList;
    968   while (ImageRecordLink != ImageRecordEndLink) {
    969     ImageRecord = CR (
    970                     ImageRecordLink,
    971                     IMAGE_PROPERTIES_RECORD,
    972                     Link,
    973                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    974                     );
    975     while (NextImageRecordLink != ImageRecordEndLink) {
    976       NextImageRecord = CR (
    977                           NextImageRecordLink,
    978                           IMAGE_PROPERTIES_RECORD,
    979                           Link,
    980                           IMAGE_PROPERTIES_RECORD_SIGNATURE
    981                           );
    982       if (ImageRecord->ImageBase > NextImageRecord->ImageBase) {
    983         SwapImageRecord (ImageRecord, NextImageRecord);
    984       }
    985 
    986       NextImageRecordLink = NextImageRecordLink->ForwardLink;
    987     }
    988 
    989     ImageRecordLink     = ImageRecordLink->ForwardLink;
    990     NextImageRecordLink = ImageRecordLink->ForwardLink;
    991   }
    992 }
    993 
    994 /**
    995   Dump image record.
    996 **/
    997 STATIC
    998 VOID
    999 DumpImageRecord (
    1000   VOID
    1001   )
    1002 {
    1003   IMAGE_PROPERTIES_RECORD  *ImageRecord;
    1004   LIST_ENTRY               *ImageRecordLink;
    1005   LIST_ENTRY               *ImageRecordList;
    1006   UINTN                    Index;
    1007 
    1008   ImageRecordList = &mImagePropertiesPrivateData.ImageRecordList;
    1009 
    1010   for (ImageRecordLink = ImageRecordList->ForwardLink, Index = 0;
    1011        ImageRecordLink != ImageRecordList;
    1012        ImageRecordLink = ImageRecordLink->ForwardLink, Index++)
    1013   {
    1014     ImageRecord = CR (
    1015                     ImageRecordLink,
    1016                     IMAGE_PROPERTIES_RECORD,
    1017                     Link,
    1018                     IMAGE_PROPERTIES_RECORD_SIGNATURE
    1019                     );
    1020     DEBUG ((DEBUG_VERBOSE, "SMM  Image[%d]: 0x%016lx - 0x%016lx\n", Index, ImageRecord->ImageBase, ImageRecord->ImageSize));
    1021   }
    1022 }
    1023 
    1024 /**
    1025255  Insert image record.
    1026256
     
    1032262  )
    1033263{
    1034   VOID                                  *ImageAddress;
    1035   EFI_IMAGE_DOS_HEADER                  *DosHdr;
    1036   UINT32                                PeCoffHeaderOffset;
    1037   UINT32                                SectionAlignment;
    1038   EFI_IMAGE_SECTION_HEADER              *Section;
    1039   EFI_IMAGE_OPTIONAL_HEADER_PTR_UNION   Hdr;
    1040   UINT8                                 *Name;
    1041   UINTN                                 Index;
    1042   IMAGE_PROPERTIES_RECORD               *ImageRecord;
    1043   CHAR8                                 *PdbPointer;
    1044   IMAGE_PROPERTIES_RECORD_CODE_SECTION  *ImageRecordCodeSection;
     264  EFI_STATUS               Status;
     265  IMAGE_PROPERTIES_RECORD  *ImageRecord;
     266  CHAR8                    *PdbPointer;
     267  UINT32                   RequiredAlignment;
    1045268
    1046269  DEBUG ((DEBUG_VERBOSE, "SMM InsertImageRecord - 0x%x\n", DriverEntry));
    1047   DEBUG ((DEBUG_VERBOSE, "SMM InsertImageRecord - 0x%016lx - 0x%08x\n", DriverEntry->ImageBuffer, DriverEntry->NumberOfPage));
    1048270
    1049271  ImageRecord = AllocatePool (sizeof (*ImageRecord));
     
    1052274  }
    1053275
    1054   ImageRecord->Signature = IMAGE_PROPERTIES_RECORD_SIGNATURE;
    1055 
    1056   DEBUG ((DEBUG_VERBOSE, "SMM ImageRecordCount - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount));
    1057 
    1058   //
    1059   // Step 1: record whole region
    1060   //
    1061   ImageRecord->ImageBase = DriverEntry->ImageBuffer;
    1062   ImageRecord->ImageSize = EfiPagesToSize (DriverEntry->NumberOfPage);
    1063 
    1064   ImageAddress = (VOID *)(UINTN)DriverEntry->ImageBuffer;
    1065 
    1066   PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
     276  InitializeListHead (&ImageRecord->Link);
     277  InitializeListHead (&ImageRecord->CodeSegmentList);
     278
     279  PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)DriverEntry->ImageBuffer);
    1067280  if (PdbPointer != NULL) {
    1068281    DEBUG ((DEBUG_VERBOSE, "SMM   Image - %a\n", PdbPointer));
    1069282  }
    1070283
    1071   //
    1072   // Check PE/COFF image
    1073   //
    1074   DosHdr             = (EFI_IMAGE_DOS_HEADER *)(UINTN)ImageAddress;
    1075   PeCoffHeaderOffset = 0;
    1076   if (DosHdr->e_magic == EFI_IMAGE_DOS_SIGNATURE) {
    1077     PeCoffHeaderOffset = DosHdr->e_lfanew;
    1078   }
    1079 
    1080   Hdr.Pe32 = (EFI_IMAGE_NT_HEADERS32 *)((UINT8 *)(UINTN)ImageAddress + PeCoffHeaderOffset);
    1081   if (Hdr.Pe32->Signature != EFI_IMAGE_NT_SIGNATURE) {
    1082     DEBUG ((DEBUG_VERBOSE, "SMM Hdr.Pe32->Signature invalid - 0x%x\n", Hdr.Pe32->Signature));
     284  RequiredAlignment = RUNTIME_PAGE_ALLOCATION_GRANULARITY;
     285  Status            = CreateImagePropertiesRecord (
     286                        (VOID *)(UINTN)DriverEntry->ImageBuffer,
     287                        LShiftU64 (DriverEntry->NumberOfPage, EFI_PAGE_SHIFT),
     288                        &RequiredAlignment,
     289                        ImageRecord
     290                        );
     291
     292  if (EFI_ERROR (Status)) {
     293    if (Status == EFI_ABORTED) {
     294      mMemoryProtectionAttribute &=
     295        ~((UINT64)EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA);
     296    }
     297
    1083298    goto Finish;
    1084299  }
    1085300
    1086   //
    1087   // Get SectionAlignment
    1088   //
    1089   if (Hdr.Pe32->OptionalHeader.Magic == EFI_IMAGE_NT_OPTIONAL_HDR32_MAGIC) {
    1090     SectionAlignment = Hdr.Pe32->OptionalHeader.SectionAlignment;
    1091   } else {
    1092     SectionAlignment = Hdr.Pe32Plus->OptionalHeader.SectionAlignment;
    1093   }
    1094 
    1095   SetMemoryAttributesTableSectionAlignment (SectionAlignment);
    1096   if ((SectionAlignment & (RUNTIME_PAGE_ALLOCATION_GRANULARITY - 1)) != 0) {
    1097     DEBUG ((
    1098       DEBUG_WARN,
    1099       "SMM !!!!!!!!  InsertImageRecord - Section Alignment(0x%x) is not %dK  !!!!!!!!\n",
    1100       SectionAlignment,
    1101       RUNTIME_PAGE_ALLOCATION_GRANULARITY >> 10
    1102       ));
    1103     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    1104     if (PdbPointer != NULL) {
    1105       DEBUG ((DEBUG_WARN, "SMM !!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    1106     }
    1107 
    1108     goto Finish;
    1109   }
    1110 
    1111   Section = (EFI_IMAGE_SECTION_HEADER *)(
    1112                                          (UINT8 *)(UINTN)ImageAddress +
    1113                                          PeCoffHeaderOffset +
    1114                                          sizeof (UINT32) +
    1115                                          sizeof (EFI_IMAGE_FILE_HEADER) +
    1116                                          Hdr.Pe32->FileHeader.SizeOfOptionalHeader
    1117                                          );
    1118   ImageRecord->CodeSegmentCount = 0;
    1119   InitializeListHead (&ImageRecord->CodeSegmentList);
    1120   for (Index = 0; Index < Hdr.Pe32->FileHeader.NumberOfSections; Index++) {
    1121     Name = Section[Index].Name;
    1122     DEBUG ((
    1123       DEBUG_VERBOSE,
    1124       "SMM   Section - '%c%c%c%c%c%c%c%c'\n",
    1125       Name[0],
    1126       Name[1],
    1127       Name[2],
    1128       Name[3],
    1129       Name[4],
    1130       Name[5],
    1131       Name[6],
    1132       Name[7]
    1133       ));
    1134 
    1135     if ((Section[Index].Characteristics & EFI_IMAGE_SCN_CNT_CODE) != 0) {
    1136       DEBUG ((DEBUG_VERBOSE, "SMM   VirtualSize          - 0x%08x\n", Section[Index].Misc.VirtualSize));
    1137       DEBUG ((DEBUG_VERBOSE, "SMM   VirtualAddress       - 0x%08x\n", Section[Index].VirtualAddress));
    1138       DEBUG ((DEBUG_VERBOSE, "SMM   SizeOfRawData        - 0x%08x\n", Section[Index].SizeOfRawData));
    1139       DEBUG ((DEBUG_VERBOSE, "SMM   PointerToRawData     - 0x%08x\n", Section[Index].PointerToRawData));
    1140       DEBUG ((DEBUG_VERBOSE, "SMM   PointerToRelocations - 0x%08x\n", Section[Index].PointerToRelocations));
    1141       DEBUG ((DEBUG_VERBOSE, "SMM   PointerToLinenumbers - 0x%08x\n", Section[Index].PointerToLinenumbers));
    1142       DEBUG ((DEBUG_VERBOSE, "SMM   NumberOfRelocations  - 0x%08x\n", Section[Index].NumberOfRelocations));
    1143       DEBUG ((DEBUG_VERBOSE, "SMM   NumberOfLinenumbers  - 0x%08x\n", Section[Index].NumberOfLinenumbers));
    1144       DEBUG ((DEBUG_VERBOSE, "SMM   Characteristics      - 0x%08x\n", Section[Index].Characteristics));
    1145 
    1146       //
    1147       // Step 2: record code section
    1148       //
    1149       ImageRecordCodeSection = AllocatePool (sizeof (*ImageRecordCodeSection));
    1150       if (ImageRecordCodeSection == NULL) {
    1151         return;
    1152       }
    1153 
    1154       ImageRecordCodeSection->Signature = IMAGE_PROPERTIES_RECORD_CODE_SECTION_SIGNATURE;
    1155 
    1156       ImageRecordCodeSection->CodeSegmentBase = (UINTN)ImageAddress + Section[Index].VirtualAddress;
    1157       ImageRecordCodeSection->CodeSegmentSize = Section[Index].SizeOfRawData;
    1158 
    1159       DEBUG ((DEBUG_VERBOSE, "SMM ImageCode: 0x%016lx - 0x%016lx\n", ImageRecordCodeSection->CodeSegmentBase, ImageRecordCodeSection->CodeSegmentSize));
    1160 
    1161       InsertTailList (&ImageRecord->CodeSegmentList, &ImageRecordCodeSection->Link);
    1162       ImageRecord->CodeSegmentCount++;
    1163     }
    1164   }
    1165 
    1166301  if (ImageRecord->CodeSegmentCount == 0) {
    1167     SetMemoryAttributesTableSectionAlignment (1);
     302    mMemoryProtectionAttribute &=
     303      ~((UINT64)EFI_MEMORY_ATTRIBUTES_RUNTIME_MEMORY_PROTECTION_NON_EXECUTABLE_PE_DATA);
    1168304    DEBUG ((DEBUG_ERROR, "SMM !!!!!!!!  InsertImageRecord - CodeSegmentCount is 0  !!!!!!!!\n"));
    1169     PdbPointer = PeCoffLoaderGetPdbPointer ((VOID *)(UINTN)ImageAddress);
    1170305    if (PdbPointer != NULL) {
    1171306      DEBUG ((DEBUG_ERROR, "SMM !!!!!!!!  Image - %a  !!!!!!!!\n", PdbPointer));
    1172307    }
    1173308
     309    Status = EFI_ABORTED;
    1174310    goto Finish;
    1175311  }
    1176312
    1177   //
    1178   // Final
    1179   //
    1180   SortImageRecordCodeSection (ImageRecord);
    1181313  //
    1182314  // Check overlap all section in ImageBase/Size
     
    1184316  if (!IsImageRecordCodeSectionValid (ImageRecord)) {
    1185317    DEBUG ((DEBUG_ERROR, "SMM IsImageRecordCodeSectionValid - FAIL\n"));
     318    Status = EFI_ABORTED;
    1186319    goto Finish;
    1187320  }
     
    1194327  }
    1195328
    1196   SortImageRecord ();
     329  SortImageRecord (&mImagePropertiesPrivateData.ImageRecordList);
    1197330
    1198331Finish:
     332  if (EFI_ERROR (Status) && (ImageRecord != NULL)) {
     333    DeleteImagePropertiesRecord (ImageRecord);
     334  }
     335
    1199336  return;
    1200337}
     
    1360497  }
    1361498
    1362   DEBUG ((DEBUG_VERBOSE, "SMM Total Image Count - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount));
    1363   DEBUG ((DEBUG_VERBOSE, "SMM Dump ImageRecord:\n"));
    1364   DumpImageRecord ();
     499  DEBUG_CODE_BEGIN ();
     500  if ( mImagePropertiesPrivateData.ImageRecordCount > 0) {
     501    DEBUG ((DEBUG_INFO, "SMM - Total Runtime Image Count - 0x%x\n", mImagePropertiesPrivateData.ImageRecordCount));
     502    DEBUG ((DEBUG_INFO, "SMM - Dump Runtime Image Records:\n"));
     503    DumpImageRecords (&mImagePropertiesPrivateData.ImageRecordList);
     504  }
     505
     506  DEBUG_CODE_END ();
    1365507
    1366508  PublishMemoryAttributesTable ();
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/PiSmmCore/PiSmmCore.h

    r99404 r105670  
    9494  VOID                            *Context;    // for profile
    9595  UINTN                           ContextSize; // for profile
     96  BOOLEAN                         ToRemove;    // To remove this SMI_HANDLER later
    9697} SMI_HANDLER;
    9798
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/PiSmmCore/PiSmmCore.inf

    r99404 r105670  
    6262  SmmMemLib
    6363  SafeIntLib
     64  ImagePropertiesRecordLib
    6465
    6566[Protocols]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/PiSmmCore/Smi.c

    r101291 r105670  
    88
    99#include "PiSmmCore.h"
     10
     11//
     12// mSmiManageCallingDepth is used to track the depth of recursive calls of SmiManage.
     13//
     14UINTN  mSmiManageCallingDepth = 0;
    1015
    1116LIST_ENTRY  mSmiEntryList = INITIALIZE_LIST_HEAD_VARIABLE (mSmiEntryList);
     
    7883
    7984  return SmiEntry;
     85}
     86
     87/**
     88  Remove SmiHandler and free the memory it used.
     89  If SmiEntry is empty, remove SmiEntry and free the memory it used.
     90
     91  @param  SmiHandler Points to SMI handler.
     92  @param  SmiEntry   Points to SMI Entry or NULL for root SMI handlers.
     93
     94  @retval TRUE        SmiEntry is removed.
     95  @retval FALSE       SmiEntry is not removed.
     96**/
     97BOOLEAN
     98RemoveSmiHandler (
     99  IN SMI_HANDLER  *SmiHandler,
     100  IN SMI_ENTRY    *SmiEntry
     101  )
     102{
     103  ASSERT (SmiHandler->ToRemove);
     104  RemoveEntryList (&SmiHandler->Link);
     105  FreePool (SmiHandler);
     106
     107  //
     108  // Remove the SMI_ENTRY if all handlers have been removed.
     109  //
     110  if (SmiEntry != NULL) {
     111    if (IsListEmpty (&SmiEntry->SmiHandlers)) {
     112      RemoveEntryList (&SmiEntry->AllEntries);
     113      FreePool (SmiEntry);
     114      return TRUE;
     115    }
     116  }
     117
     118  return FALSE;
    80119}
    81120
     
    105144  LIST_ENTRY   *Link;
    106145  LIST_ENTRY   *Head;
     146  LIST_ENTRY   *EntryLink;
    107147  SMI_ENTRY    *SmiEntry;
    108148  SMI_HANDLER  *SmiHandler;
    109   BOOLEAN      SuccessReturn;
     149  EFI_STATUS   ReturnStatus;
     150  BOOLEAN      WillReturn;
    110151  EFI_STATUS   Status;
    111152
    112153  PERF_FUNCTION_BEGIN ();
    113 
    114   Status        = EFI_NOT_FOUND;
    115   SuccessReturn = FALSE;
     154  mSmiManageCallingDepth++;
     155  Status       = EFI_NOT_FOUND;
     156  ReturnStatus = Status;
    116157  if (HandlerType == NULL) {
    117158    //
     
    153194        if (HandlerType != NULL) {
    154195          PERF_FUNCTION_END ();
    155           return EFI_INTERRUPT_PENDING;
     196          ReturnStatus = EFI_INTERRUPT_PENDING;
     197          WillReturn   = TRUE;
     198        } else {
     199          //
     200          // If any other handler's result sets ReturnStatus as EFI_SUCCESS, the return status
     201          // will be EFI_SUCCESS.
     202          //
     203          if (ReturnStatus != EFI_SUCCESS) {
     204            ReturnStatus = Status;
     205          }
    156206        }
    157207
     
    166216        if (HandlerType != NULL) {
    167217          PERF_FUNCTION_END ();
    168           return EFI_SUCCESS;
     218          WillReturn = TRUE;
    169219        }
    170220
    171         SuccessReturn = TRUE;
     221        ReturnStatus = EFI_SUCCESS;
    172222        break;
    173223
     
    177227        // then the function will return EFI_SUCCESS.
    178228        //
    179         SuccessReturn = TRUE;
     229        ReturnStatus = EFI_SUCCESS;
    180230        break;
    181231
     
    185235        // then EFI_WARN_INTERRUPT_SOURCE_PENDING will be returned.
    186236        //
     237        if (ReturnStatus != EFI_SUCCESS) {
     238          ReturnStatus = Status;
     239        }
     240
    187241        break;
    188242
     
    194248        break;
    195249    }
    196   }
    197 
    198   if (SuccessReturn) {
    199     Status = EFI_SUCCESS;
     250
     251    if (WillReturn) {
     252      break;
     253    }
     254  }
     255
     256  ASSERT (mSmiManageCallingDepth > 0);
     257  mSmiManageCallingDepth--;
     258
     259  //
     260  // SmiHandlerUnRegister() calls from SMI handlers are deferred till this point.
     261  // Before returned from SmiManage, delete the SmiHandler which is
     262  // marked as ToRemove.
     263  // Note that SmiManage can be called recursively.
     264  //
     265  if (mSmiManageCallingDepth == 0) {
     266    //
     267    // Go through all SmiHandler in root SMI handlers
     268    //
     269    for ( Link = GetFirstNode (&mRootSmiEntry.SmiHandlers)
     270          ; !IsNull (&mRootSmiEntry.SmiHandlers, Link);
     271          )
     272    {
     273      //
     274      // SmiHandler might be removed in below, so cache the next link in Link
     275      //
     276      SmiHandler = CR (Link, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE);
     277      Link       = GetNextNode (&mRootSmiEntry.SmiHandlers, Link);
     278      if (SmiHandler->ToRemove) {
     279        //
     280        // Remove SmiHandler if the ToRemove is set.
     281        //
     282        RemoveSmiHandler (SmiHandler, NULL);
     283      }
     284    }
     285
     286    //
     287    // Go through all SmiHandler in non-root SMI handlers
     288    //
     289    for ( EntryLink = GetFirstNode (&mSmiEntryList)
     290          ; !IsNull (&mSmiEntryList, EntryLink);
     291          )
     292    {
     293      //
     294      // SmiEntry might be removed in below, so cache the next link in EntryLink
     295      //
     296      SmiEntry  = CR (EntryLink, SMI_ENTRY, AllEntries, SMI_ENTRY_SIGNATURE);
     297      EntryLink = GetNextNode (&mSmiEntryList, EntryLink);
     298      for ( Link = GetFirstNode (&SmiEntry->SmiHandlers)
     299            ; !IsNull (&SmiEntry->SmiHandlers, Link);
     300            )
     301      {
     302        //
     303        // SmiHandler might be removed in below, so cache the next link in Link
     304        //
     305        SmiHandler = CR (Link, SMI_HANDLER, Link, SMI_HANDLER_SIGNATURE);
     306        Link       = GetNextNode (&SmiEntry->SmiHandlers, Link);
     307        if (SmiHandler->ToRemove) {
     308          if (RemoveSmiHandler (SmiHandler, SmiEntry)) {
     309            break;
     310          }
     311        }
     312      }
     313    }
    200314  }
    201315
    202316  PERF_FUNCTION_END ();
    203   return Status;
     317  return ReturnStatus;
    204318}
    205319
     
    239353  SmiHandler->Handler    = Handler;
    240354  SmiHandler->CallerAddr = (UINTN)RETURN_ADDRESS (0);
     355  SmiHandler->ToRemove   = FALSE;
    241356
    242357  if (HandlerType == NULL) {
     
    319434  }
    320435
    321   if ((EFI_HANDLE)SmiHandler != DispatchHandle) {
     436  if (SmiHandler == NULL) {
    322437    return EFI_INVALID_PARAMETER;
    323438  }
    324439
     440  ASSERT ((EFI_HANDLE)SmiHandler == DispatchHandle);
     441  SmiHandler->ToRemove = TRUE;
     442
     443  if (mSmiManageCallingDepth > 0) {
     444    //
     445    // This function is called from SmiManage()
     446    // Do not delete or remove SmiHandler or SmiEntry now.
     447    // SmiManage will handle it later
     448    //
     449    return EFI_SUCCESS;
     450  }
     451
    325452  SmiEntry = SmiHandler->SmiEntry;
    326453
    327   RemoveEntryList (&SmiHandler->Link);
    328   FreePool (SmiHandler);
    329 
    330   if (SmiEntry == NULL) {
    331     //
    332     // This is root SMI handler
    333     //
    334     return EFI_SUCCESS;
    335   }
    336 
    337   if (IsListEmpty (&SmiEntry->SmiHandlers)) {
    338     //
    339     // No handler registered for this interrupt now, remove the SMI_ENTRY
    340     //
    341     RemoveEntryList (&SmiEntry->AllEntries);
    342 
    343     FreePool (SmiEntry);
    344   }
    345 
     454  //
     455  // For root SMI handler, use NULL for SmiEntry
     456  //
     457  RemoveSmiHandler (SmiHandler, (SmiEntry == &mRootSmiEntry) ? NULL : SmiEntry);
    346458  return EFI_SUCCESS;
    347459}
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/RuntimeDxe/Runtime.c

    r99404 r105670  
    118118  @retval  EFI_NOT_FOUND            The pointer pointed to by Address was not found to be part
    119119                                    of the current memory map. This is normally fatal.
    120   @retval  EFI_INVALID_PARAMETER    One of the parameters has an invalid value.
     120  @retval  EFI_INVALID_PARAMETER    1) Address is NULL.
     121                                    2) *Address is NULL and DebugDisposition does
     122                                    not have the EFI_OPTIONAL_PTR bit set.
     123  @retval  EFI_UNSUPPORTED          This call is not supported by this platform at the time the call is made.
     124                                    The platform should describe this runtime service as unsupported at runtime
     125                                    via an EFI_RT_PROPERTIES_TABLE configuration table.
    121126
    122127**/
     
    228233  @retval  EFI_NOT_FOUND          A virtual address was supplied for an address that is not found
    229234                                  in the memory map.
     235  @retval  EFI_UNSUPPORTED        This call is not supported by this platform at the time the call is made.
     236                                  The platform should describe this runtime service as unsupported at runtime
     237                                  via an EFI_RT_PROPERTIES_TABLE configuration table.
    230238
    231239**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Core/RuntimeDxe/Runtime.h

    r99404 r105670  
    6060  @retval  EFI_NOT_FOUND            The pointer pointed to by Address was not found to be part
    6161                                    of the current memory map. This is normally fatal.
    62   @retval  EFI_INVALID_PARAMETER    One of the parameters has an invalid value.
     62  @retval  EFI_INVALID_PARAMETER    1) Address is NULL.
     63                                    2) *Address is NULL and DebugDisposition does
     64                                    not have the EFI_OPTIONAL_PTR bit set.
     65  @retval  EFI_UNSUPPORTED          This call is not supported by this platform at the time the call is made.
     66                                    The platform should describe this runtime service as unsupported at runtime
     67                                    via an EFI_RT_PROPERTIES_TABLE configuration table.
    6368
    6469**/
     
    8792  @retval  EFI_NOT_FOUND          A virtual address was supplied for an address that is not found
    8893                                  in the memory map.
     94  @retval  EFI_UNSUPPORTED        This call is not supported by this platform at the time the call is made.
     95                                  The platform should describe this runtime service as unsupported at runtime
     96                                  via an EFI_RT_PROPERTIES_TABLE configuration table.
    8997
    9098**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Guid/AcpiS3Context.h

    r99404 r105670  
    22  Definitions for data structures used in S3 resume.
    33
    4 Copyright (c) 2011 - 2018, Intel Corporation. All rights reserved.<BR>
     4Copyright (c) 2011 - 2023, Intel Corporation. All rights reserved.<BR>
    55
    66SPDX-License-Identifier: BSD-2-Clause-Patent
     
    3131  EFI_PHYSICAL_ADDRESS    ReturnContext2;
    3232  EFI_PHYSICAL_ADDRESS    ReturnStackPointer;
     33  EFI_PHYSICAL_ADDRESS    MpService2Ppi;
    3334  EFI_PHYSICAL_ADDRESS    Smst;
    3435} SMM_S3_RESUME_STATE;
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Guid/MemoryTypeInformation.h

    r99404 r105670  
    11/** @file
    22  This file defines:
    3   * Memory Type Information GUID for HOB and Variable.
     3  * Memory Type Information GUID for Guided HOB and Variable.
    44  * Memory Type Information Variable Name.
    55  * Memory Type Information GUID HOB data structure.
    66
    7   The memory type information HOB and variable can
    8   be used to store the information for each memory type in Variable or HOB.
     7  The memory type information HOB and variable can be used to store information
     8  for each memory type in Variable or HOB.
    99
    10 Copyright (c) 2006 - 2018, Intel Corporation. All rights reserved.<BR>
    11 SPDX-License-Identifier: BSD-2-Clause-Patent
     10  The Memory Type Information GUID can also be optionally used as the Owner
     11  field of a Resource Descriptor HOB to provide the preferred memory range
     12  for the memory types described in the Memory Type Information GUID HOB.
     13
     14  Copyright (c) 2006, Intel Corporation. All rights reserved.<BR>
     15  SPDX-License-Identifier: BSD-2-Clause-Patent
    1216
    1317**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Guid/MigratedFvInfo.h

    r99404 r105670  
    1010#define __EDKII_MIGRATED_FV_INFO_GUID_H__
    1111
     12//
     13// FLAGS_FV_RAW_DATA_COPY indicates FV raw data will be copied to permanent memory
     14// or not. When FV is migrated to permanent memory, it will be rebased and raw
     15// data will be lost. This bit can be configured as below values:
     16// 0: FV raw data will not be used in later phase, and the copy will be skipped to
     17//    optimize boot performance.
     18// 1: FV raw data will be copied to permanent memory for later phase use (such as
     19//    FV measurement).
     20//
     21#define FLAGS_FV_RAW_DATA_COPY  BIT0
     22
     23///
     24/// In real use cases, not all FVs need migrate to permanent memory before TempRam tears
     25/// down. EDKII_MIGRATION_INFO hob should be published by platform to indicate which
     26/// FVs need migration to optimize boot performance. If this hob is not detected by Pei
     27/// Core, all FVs on TempRam will be migrated and FV raw data will also be copied.
     28/// Only one EDKII_MIGRATION_INFO hob should be published by platform, and this hob will
     29/// take effect only when migration feature is enabled by PCD.
     30///
     31typedef struct {
     32  UINT32    FvOrgBaseOnTempRam;        // Original FV address on Temporary Ram
     33  //
     34  // FV Migration Flags:
     35  // Bit0: Indicate to copy FV raw data or not
     36  // Others: Reserved bits
     37  //
     38  UINT32    FvMigrationFlags;
     39} TO_MIGRATE_FV_INFO;
     40
     41typedef struct {
     42  BOOLEAN    MigrateAll;                    // Migrate all FVs and also copy FV raw data
     43  //
     44  // ToMigrateFvCount and ToMigrateFvInfo array indicate which FVs need be migrated, and
     45  // these info should be ignored when MigrateAll field is set to TRUE.
     46  //
     47  UINT32     ToMigrateFvCount;
     48  // TO_MIGRATE_FV_INFO    ToMigrateFvInfo[];
     49} EDKII_MIGRATION_INFO;
     50
    1251typedef struct {
    1352  UINT32    FvOrgBase;         // original FV address
    1453  UINT32    FvNewBase;         // new FV address
    15   UINT32    FvDataBase;        // original FV data
     54  UINT32    FvDataBase;        // original FV data, 0 means raw data is not copied
    1655  UINT32    FvLength;          // Fv Length
    1756} EDKII_MIGRATED_FV_INFO;
    1857
     58extern EFI_GUID  gEdkiiMigrationInfoGuid;
    1959extern EFI_GUID  gEdkiiMigratedFvInfoGuid;
    2060
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Guid/VarCheckPolicyMmi.h

    r99404 r105670  
    3333} VAR_CHECK_POLICY_COMM_DUMP_PARAMS;
    3434
     35typedef union {
     36  VARIABLE_POLICY_ENTRY                VariablePolicy;
     37  VARIABLE_LOCK_ON_VAR_STATE_POLICY    LockOnVarStatePolicy;
     38} VAR_CHECK_POLICY_OUTPUT_POLICY_ENTRY;
     39
     40typedef struct _VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS {
     41  EFI_GUID                                InputVendorGuid;
     42  UINT32                                  InputVariableNameSize;
     43  UINT32                                  OutputVariableNameSize;
     44  VAR_CHECK_POLICY_OUTPUT_POLICY_ENTRY    OutputPolicyEntry;
     45  CHAR16                                  InputVariableName[1];
     46} VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS;
     47
    3548#pragma pack(pop)
     49
     50#define   VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END \
     51            (OFFSET_OF(VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS, InputVariableName))
    3652
    3753// Make sure that we will hold at least the headers.
     
    4157                                                      sizeof(VAR_CHECK_POLICY_COMM_HEADER) + \
    4258                                                      sizeof(VAR_CHECK_POLICY_COMM_DUMP_PARAMS)))
     59
     60#define   VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE  (VAR_CHECK_POLICY_MM_COMM_BUFFER_SIZE - \
     61                                                      (OFFSET_OF(EFI_MM_COMMUNICATE_HEADER, Data) + \
     62                                                        sizeof(VAR_CHECK_POLICY_COMM_HEADER) + \
     63                                                        OFFSET_OF(VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS, InputVariableName)))
     64
    4365STATIC_ASSERT (
    4466  VAR_CHECK_POLICY_MM_DUMP_BUFFER_SIZE < VAR_CHECK_POLICY_MM_COMM_BUFFER_SIZE,
     
    4668  );
    4769
    48 #define   VAR_CHECK_POLICY_COMMAND_DISABLE     0x0001
    49 #define   VAR_CHECK_POLICY_COMMAND_IS_ENABLED  0x0002
    50 #define   VAR_CHECK_POLICY_COMMAND_REGISTER    0x0003
    51 #define   VAR_CHECK_POLICY_COMMAND_DUMP        0x0004
    52 #define   VAR_CHECK_POLICY_COMMAND_LOCK        0x0005
     70STATIC_ASSERT (
     71  VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE < VAR_CHECK_POLICY_MM_COMM_BUFFER_SIZE,
     72  "an integer underflow may have occurred calculating VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE"
     73  );
     74
     75#define   VAR_CHECK_POLICY_COMMAND_DISABLE                  0x0001
     76#define   VAR_CHECK_POLICY_COMMAND_IS_ENABLED               0x0002
     77#define   VAR_CHECK_POLICY_COMMAND_REGISTER                 0x0003
     78#define   VAR_CHECK_POLICY_COMMAND_DUMP                     0x0004
     79#define   VAR_CHECK_POLICY_COMMAND_LOCK                     0x0005
     80#define   VAR_CHECK_POLICY_COMMAND_GET_INFO                 0x0006
     81#define   VAR_CHECK_POLICY_COMMAND_GET_LOCK_VAR_STATE_INFO  0x0007
    5382
    5483#endif // _VAR_CHECK_POLICY_MMI_COMMON_H_
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Library/IpmiCommandLib.h

    r99404 r105670  
    248248  OUT IPMI_GET_CHANNEL_INFO_RESPONSE  *GetChannelInfoResponse,
    249249  OUT UINT32                          *GetChannelInfoResponseSize
     250  );
     251
     252/**
     253  This function gets system interface capability
     254
     255  @param[in]  InterfaceCapabilityRequest    Get system interface capability request.
     256  @param[out] InterfaceCapabilityResponse   The response of system interface capability.
     257
     258  @retval EFI_SUCCESS            Command is sent successfully.
     259  @retval Other                  Failure.
     260
     261**/
     262EFI_STATUS
     263EFIAPI
     264IpmiGetSystemInterfaceCapability (
     265  IN  IPMI_GET_SYSTEM_INTERFACE_CAPABILITIES_REQUEST   *InterfaceCapabilityRequest,
     266  OUT IPMI_GET_SYSTEM_INTERFACE_CAPABILITIES_RESPONSE  *InterfaceCapabilityResponse
    250267  );
    251268
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Library/VariablePolicyLib.h

    r99404 r105670  
    104104
    105105/**
     106  This function will return variable policy information for a UEFI variable with a
     107  registered variable policy.
     108
     109  @param[in]      VariableName                          The name of the variable to use for the policy search.
     110  @param[in]      VendorGuid                            The vendor GUID of the variable to use for the policy search.
     111  @param[in,out]  VariablePolicyVariableNameBufferSize  On input, the size, in bytes, of the VariablePolicyVariableName
     112                                                        buffer.
     113
     114                                                        On output, the size, in bytes, needed to store the variable
     115                                                        policy variable name.
     116
     117                                                        If testing for the VariablePolicyVariableName buffer size
     118                                                        needed, set this value to zero so EFI_BUFFER_TOO_SMALL is
     119                                                        guaranteed to be returned if the variable policy variable name
     120                                                        is found.
     121  @param[out]     VariablePolicy                        Pointer to a buffer where the policy entry will be written
     122                                                        if found.
     123  @param[out]     VariablePolicyVariableName            Pointer to a buffer where the variable name used for the
     124                                                        variable policy will be written if a variable name is
     125                                                        registered.
     126
     127                                                        If the variable policy is not associated with a variable name
     128                                                        (e.g. applied to variable vendor namespace) and this parameter
     129                                                        is given, this parameter will not be modified and
     130                                                        VariablePolicyVariableNameBufferSize will be set to zero to
     131                                                        indicate a name was not present.
     132
     133                                                        If the pointer given is not NULL,
     134                                                        VariablePolicyVariableNameBufferSize must be non-NULL.
     135
     136  @retval     EFI_SUCCESS             A variable policy entry was found and returned successfully.
     137  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     138  @retval     EFI_BUFFER_TOO_SMALL    The VariablePolicyVariableName buffer value is too small for the size needed.
     139                                      The buffer should now point to the size needed.
     140  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     141  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     142                                      VariablePolicyVariableName is non-NULL and VariablePolicyVariableNameBufferSize
     143                                      is NULL.
     144  @retval     EFI_NOT_FOUND           A variable policy was not found for the given UEFI variable name and vendor GUID.
     145
     146**/
     147EFI_STATUS
     148EFIAPI
     149GetVariablePolicyInfo (
     150  IN      CONST CHAR16           *VariableName,
     151  IN      CONST EFI_GUID         *VendorGuid,
     152  IN OUT  UINTN                  *VariablePolicyVariableNameBufferSize OPTIONAL,
     153  OUT     VARIABLE_POLICY_ENTRY  *VariablePolicy,
     154  OUT     CHAR16                 *VariablePolicyVariableName OPTIONAL
     155  );
     156
     157/**
     158  This function will return the Lock on Variable State policy information for the policy
     159  associated with the given UEFI variable.
     160
     161  @param[in]      VariableName                              The name of the variable to use for the policy search.
     162  @param[in]      VendorGuid                                The vendor GUID of the variable to use for the policy
     163                                                            search.
     164  @param[in,out]  VariableLockPolicyVariableNameBufferSize  On input, the size, in bytes, of the
     165                                                            VariableLockPolicyVariableName buffer.
     166
     167                                                            On output, the size, in bytes, needed to store the variable
     168                                                            policy variable name.
     169
     170                                                            If testing for the VariableLockPolicyVariableName buffer
     171                                                            size needed, set this value to zero so EFI_BUFFER_TOO_SMALL
     172                                                            is guaranteed to be returned if the variable policy variable
     173                                                            name is found.
     174  @param[out]     VariablePolicy                            Pointer to a buffer where the policy entry will be written
     175                                                            if found.
     176  @param[out]     VariableLockPolicyVariableName            Pointer to a buffer where the variable name used for the
     177                                                            variable lock on variable state policy will be written if
     178                                                            a variable name is registered.
     179
     180                                                            If the lock on variable policy is not associated with a
     181                                                            variable name (e.g. applied to variable vendor namespace)
     182                                                            and this parameter is given, this parameter will not be
     183                                                            modified and VariableLockPolicyVariableNameBufferSize will
     184                                                            be set to zero to indicate a name was not present.
     185
     186                                                            If the pointer given is not NULL,
     187                                                            VariableLockPolicyVariableNameBufferSize must be non-NULL.
     188
     189  @retval     EFI_SUCCESS             A Lock on Variable State variable policy entry was found and returned
     190                                      successfully.
     191  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     192  @retval     EFI_BUFFER_TOO_SMALL    The VariableLockPolicyVariableName buffer is too small for the size needed.
     193                                      The buffer should now point to the size needed.
     194  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     195  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     196                                      VariableLockPolicyVariableName is non-NULL and
     197                                      VariableLockPolicyVariableNameBufferSize is NULL.
     198  @retval     EFI_NOT_FOUND           A Lock on Variable State variable policy was not found for the given UEFI
     199                                      variable name and vendor GUID.
     200
     201**/
     202EFI_STATUS
     203EFIAPI
     204GetLockOnVariableStateVariablePolicyInfo (
     205  IN      CONST CHAR16                       *VariableName,
     206  IN      CONST EFI_GUID                     *VendorGuid,
     207  IN OUT  UINTN                              *VariableLockPolicyVariableNameBufferSize OPTIONAL,
     208  OUT     VARIABLE_LOCK_ON_VAR_STATE_POLICY  *VariablePolicy,
     209  OUT     CHAR16                             *VariableLockPolicyVariableName OPTIONAL
     210  );
     211
     212/**
    106213  This API function returns whether or not the policy engine is
    107214  currently being enforced.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Protocol/UsbEthernetProtocol.h

    r101291 r105670  
    2525#define USB_VENDOR_PROTOCOL    0xFF
    2626
     27#define USB_MISC_CLASS               0xEF
     28#define USB_RNDIS_SUBCLASS           0x04
     29#define USB_RNDIS_ETHERNET_PROTOCOL  0x01
     30
    2731// Type Values for the DescriptorType Field
    2832#define CS_INTERFACE  0x24
     
    4246#define NETWORK_CONNECTED   0x01
    4347#define NETWORK_DISCONNECT  0x00
     48
     49#define MAC_FILTERS_MASK  0x7FFF
    4450
    4551// USB Header functional Descriptor
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Include/Protocol/VariablePolicy.h

    r99404 r105670  
    1010#define __EDKII_VARIABLE_POLICY_PROTOCOL__
    1111
    12 #define EDKII_VARIABLE_POLICY_PROTOCOL_REVISION  0x0000000000010000
     12#define EDKII_VARIABLE_POLICY_PROTOCOL_REVISION  0x0000000000020000
     13
     14/*
     15  Rev 0x0000000000010000:
     16    - Initial protocol definition
     17
     18  Rev 0x0000000000020000:
     19    - Add GetVariablePolicyInfo() API
     20    - Add GetLockOnVariableStateVariablePolicyInfo() API
     21
     22*/
    1323
    1424#define EDKII_VARIABLE_POLICY_PROTOCOL_GUID \
     
    142152  );
    143153
     154/**
     155  This function will return variable policy information for a UEFI variable with a
     156  registered variable policy.
     157
     158  @param[in]      VariableName                          The name of the variable to use for the policy search.
     159  @param[in]      VendorGuid                            The vendor GUID of the variable to use for the policy search.
     160  @param[in,out]  VariablePolicyVariableNameBufferSize  On input, the size, in bytes, of the VariablePolicyVariableName
     161                                                        buffer.
     162
     163                                                        On output, the size, in bytes, needed to store the variable
     164                                                        policy variable name.
     165
     166                                                        If testing for the VariablePolicyVariableName buffer size
     167                                                        needed, set this value to zero so EFI_BUFFER_TOO_SMALL is
     168                                                        guaranteed to be returned if the variable policy variable name
     169                                                        is found.
     170  @param[out]     VariablePolicy                        Pointer to a buffer where the policy entry will be written
     171                                                        if found.
     172  @param[out]     VariablePolicyVariableName            Pointer to a buffer where the variable name used for the
     173                                                        variable policy will be written if a variable name is
     174                                                        registered.
     175
     176                                                        If the variable policy is not associated with a variable name
     177                                                        (e.g. applied to variable vendor namespace) and this parameter
     178                                                        is given, this parameter will not be modified and
     179                                                        VariablePolicyVariableNameBufferSize will be set to zero to
     180                                                        indicate a name was not present.
     181
     182                                                        If the pointer given is not NULL,
     183                                                        VariablePolicyVariableNameBufferSize must be non-NULL.
     184
     185  @retval     EFI_SUCCESS             A variable policy entry was found and returned successfully.
     186  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     187  @retval     EFI_BUFFER_TOO_SMALL    The VariablePolicyVariableName buffer value is too small for the size needed.
     188                                      The buffer should now point to the size needed.
     189  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     190  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     191                                      VariablePolicyVariableName is non-NULL and VariablePolicyVariableNameBufferSize
     192                                      is NULL.
     193  @retval     EFI_NOT_FOUND           A variable policy was not found for the given UEFI variable name and vendor GUID.
     194
     195**/
     196typedef
     197EFI_STATUS
     198(EFIAPI *GET_VARIABLE_POLICY_INFO)(
     199  IN      CONST CHAR16                *VariableName,
     200  IN      CONST EFI_GUID              *VendorGuid,
     201  IN OUT  UINTN                       *VariablePolicyVariableNameBufferSize OPTIONAL,
     202  OUT     VARIABLE_POLICY_ENTRY       *VariablePolicy,
     203  OUT     CHAR16                      *VariablePolicyVariableName OPTIONAL
     204  );
     205
     206/**
     207  This function will return the Lock on Variable State policy information for the policy
     208  associated with the given UEFI variable.
     209
     210  @param[in]      VariableName                              The name of the variable to use for the policy search.
     211  @param[in]      VendorGuid                                The vendor GUID of the variable to use for the policy
     212                                                            search.
     213  @param[in,out]  VariableLockPolicyVariableNameBufferSize  On input, the size, in bytes, of the
     214                                                            VariableLockPolicyVariableName buffer.
     215
     216                                                            On output, the size, in bytes, needed to store the variable
     217                                                            policy variable name.
     218
     219                                                            If testing for the VariableLockPolicyVariableName buffer
     220                                                            size needed, set this value to zero so EFI_BUFFER_TOO_SMALL
     221                                                            is guaranteed to be returned if the variable policy variable
     222                                                            name is found.
     223  @param[out]     VariablePolicy                            Pointer to a buffer where the policy entry will be written
     224                                                            if found.
     225  @param[out]     VariableLockPolicyVariableName            Pointer to a buffer where the variable name used for the
     226                                                            variable lock on variable state policy will be written if
     227                                                            a variable name is registered.
     228
     229                                                            If the lock on variable policy is not associated with a
     230                                                            variable name (e.g. applied to variable vendor namespace)
     231                                                            and this parameter is given, this parameter will not be
     232                                                            modified and VariableLockPolicyVariableNameBufferSize will
     233                                                            be set to zero to indicate a name was not present.
     234
     235                                                            If the pointer given is not NULL,
     236                                                            VariableLockPolicyVariableNameBufferSize must be non-NULL.
     237
     238  @retval     EFI_SUCCESS             A Lock on Variable State variable policy entry was found and returned
     239                                      successfully.
     240  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     241  @retval     EFI_BUFFER_TOO_SMALL    The VariableLockPolicyVariableName buffer is too small for the size needed.
     242                                      The buffer should now point to the size needed.
     243  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     244  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     245                                      VariableLockPolicyVariableName is non-NULL and
     246                                      VariableLockPolicyVariableNameBufferSize is NULL.
     247  @retval     EFI_NOT_FOUND           A Lock on Variable State variable policy was not found for the given UEFI
     248                                      variable name and vendor GUID.
     249
     250**/
     251typedef
     252EFI_STATUS
     253(EFIAPI *GET_LOCK_ON_VARIABLE_STATE_VARIABLE_POLICY_INFO)(
     254  IN      CONST CHAR16                        *VariableName,
     255  IN      CONST EFI_GUID                      *VendorGuid,
     256  IN OUT  UINTN                               *VariableLockPolicyVariableNameBufferSize OPTIONAL,
     257  OUT     VARIABLE_LOCK_ON_VAR_STATE_POLICY   *VariablePolicy,
     258  OUT     CHAR16                              *VariableLockPolicyVariableName OPTIONAL
     259  );
     260
    144261typedef struct {
    145   UINT64                        Revision;
    146   DISABLE_VARIABLE_POLICY       DisableVariablePolicy;
    147   IS_VARIABLE_POLICY_ENABLED    IsVariablePolicyEnabled;
    148   REGISTER_VARIABLE_POLICY      RegisterVariablePolicy;
    149   DUMP_VARIABLE_POLICY          DumpVariablePolicy;
    150   LOCK_VARIABLE_POLICY          LockVariablePolicy;
     262  UINT64                                             Revision;
     263  DISABLE_VARIABLE_POLICY                            DisableVariablePolicy;
     264  IS_VARIABLE_POLICY_ENABLED                         IsVariablePolicyEnabled;
     265  REGISTER_VARIABLE_POLICY                           RegisterVariablePolicy;
     266  DUMP_VARIABLE_POLICY                               DumpVariablePolicy;
     267  LOCK_VARIABLE_POLICY                               LockVariablePolicy;
     268  GET_VARIABLE_POLICY_INFO                           GetVariablePolicyInfo;
     269  GET_LOCK_ON_VARIABLE_STATE_VARIABLE_POLICY_INFO    GetLockOnVariableStateVariablePolicyInfo;
    151270} _EDKII_VARIABLE_POLICY_PROTOCOL;
    152271
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/BootMaintenanceManagerUiLib/UpdatePage.c

    r99404 r105670  
    528528        )
    529529    {
    530       CheckFlags         |= EFI_IFR_CHECKBOX_DEFAULT;
    531       ConsoleCheck[Index] = TRUE;
    532     } else {
     530      CheckFlags |= EFI_IFR_CHECKBOX_DEFAULT;
     531
     532      if (Index < MAX_MENU_NUMBER) {
     533        ConsoleCheck[Index] = TRUE;
     534      }
     535    } else if (Index < MAX_MENU_NUMBER) {
    533536      ConsoleCheck[Index] = FALSE;
    534537    }
     
    623626
    624627  NewMenuEntry = NULL;
    625   for (OptionIndex = 0; (OptionOrder[OptionIndex] != 0 && OptionIndex < MAX_MENU_NUMBER); OptionIndex++) {
     628  for (OptionIndex = 0; (OptionIndex < MAX_MENU_NUMBER && OptionOrder[OptionIndex] != 0); OptionIndex++) {
    626629    BootOptionFound = FALSE;
    627630    for (Index = 0; Index < OptionMenu->MenuNumber; Index++) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/DebugAgentLibNull/DebugAgentLibNull.c

    r99404 r105670  
    2525  environment.
    2626
     27  If InitFlag is DEBUG_AGENT_INIT_SMM, Context must point to a BOOLEAN if it's not
     28  NULL, which indicates SMM Debug Agent supported or not.
     29
    2730  @param[in] InitFlag     Init flag is used to decide the initialize process.
    2831  @param[in] Context      Context needed according to InitFlag; it was optional.
     
    3942  )
    4043{
     44  switch (InitFlag) {
     45    case DEBUG_AGENT_INIT_SMM:
     46      if (Context != NULL) {
     47        *(BOOLEAN *)Context = FALSE;
     48      }
     49
     50      return;
     51  }
     52
    4153  if (Function != NULL) {
    4254    Function (Context);
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleLib.c

    r99404 r105670  
    4242#include <Protocol/DevicePath.h>
    4343
    44 EFI_SYSTEM_RESOURCE_TABLE  *mEsrtTable             = NULL;
    45 BOOLEAN                    mIsVirtualAddrConverted = FALSE;
     44EFI_SYSTEM_RESOURCE_TABLE  *mEsrtTable = NULL;
    4645
    4746BOOLEAN    mDxeCapsuleLibEndOfDxe      = FALSE;
     
    13951394
    13961395  EsrtGuidFound = FALSE;
    1397   if (mIsVirtualAddrConverted) {
    1398     if (mEsrtTable != NULL) {
    1399       EsrtEntry = (EFI_SYSTEM_RESOURCE_ENTRY *)(mEsrtTable + 1);
    1400       for (Index = 0; Index < mEsrtTable->FwResourceCount; Index++, EsrtEntry++) {
    1401         if (CompareGuid (&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) {
    1402           EsrtGuidFound = TRUE;
    1403           break;
    1404         }
     1396  if (mEsrtTable != NULL) {
     1397    EsrtEntry = (EFI_SYSTEM_RESOURCE_ENTRY *)(mEsrtTable + 1);
     1398    for (Index = 0; Index < mEsrtTable->FwResourceCount; Index++, EsrtEntry++) {
     1399      if (CompareGuid (&EsrtEntry->FwClass, &CapsuleHeader->CapsuleGuid)) {
     1400        EsrtGuidFound = TRUE;
     1401        break;
    14051402      }
    14061403    }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/DxeCapsuleLibFmp/DxeCapsuleRuntime.c

    r99404 r105670  
    2222
    2323extern EFI_SYSTEM_RESOURCE_TABLE  *mEsrtTable;
    24 extern BOOLEAN                    mIsVirtualAddrConverted;
    2524EFI_EVENT                         mDxeRuntimeCapsuleLibVirtualAddressChangeEvent = NULL;
    2625EFI_EVENT                         mDxeRuntimeCapsuleLibReadyToBootEvent          = NULL;
     
    4140{
    4241  gRT->ConvertPointer (EFI_OPTIONAL_PTR, (VOID **)&mEsrtTable);
    43   mIsVirtualAddrConverted = TRUE;
    4442}
    4543
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/DxeCorePerformanceLib/DxeCorePerformanceLib.c

    r99404 r105670  
    1111  Performance Protocol is installed at the very beginning of DXE phase.
    1212
    13 Copyright (c) 2006 - 2021, Intel Corporation. All rights reserved.<BR>
     13Copyright (c) 2006 - 2023, Intel Corporation. All rights reserved.<BR>
    1414(C) Copyright 2016 Hewlett Packard Enterprise Development LP<BR>
    1515SPDX-License-Identifier: BSD-2-Clause-Patent
     
    7474BOOLEAN  mLockInsertRecord     = FALSE;
    7575CHAR8    *mDevicePathString    = NULL;
     76UINTN    mSmmBootRecordOffset  = 0;
    7677
    7778EFI_DEVICE_PATH_TO_TEXT_PROTOCOL  *mDevicePathToText = NULL;
     
    237238  UINTN                                    SmmBootRecordDataSize;
    238239  UINTN                                    ReservedMemSize;
     240  UINTN                                    SmmBootRecordDataRetrieved;
    239241
    240242  //
     
    298300
    299301          //
    300           // Get all boot records
     302          // Get boot records starting from mSmmBootRecordOffset
    301303          //
    302           SmmCommData->Function = SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET;
    303           SmmBootRecordDataSize = SmmCommData->BootRecordSize;
    304           SmmBootRecordData     = AllocateZeroPool (SmmBootRecordDataSize);
     304          SmmCommData->Function         = SMM_FPDT_FUNCTION_GET_BOOT_RECORD_DATA_BY_OFFSET;
     305          SmmCommData->BootRecordOffset = mSmmBootRecordOffset;
     306          SmmBootRecordDataSize         = SmmCommData->BootRecordSize - mSmmBootRecordOffset;
     307          SmmBootRecordData             = AllocateZeroPool (SmmBootRecordDataSize);
     308          SmmBootRecordDataRetrieved    = 0;
    305309          ASSERT (SmmBootRecordData  != NULL);
    306           SmmCommData->BootRecordOffset = 0;
    307           SmmCommData->BootRecordData   = (VOID *)((UINTN)SmmCommMemRegion->PhysicalStart + SMM_BOOT_RECORD_COMM_SIZE);
    308           SmmCommData->BootRecordSize   = ReservedMemSize - SMM_BOOT_RECORD_COMM_SIZE;
    309           while (SmmCommData->BootRecordOffset < SmmBootRecordDataSize) {
     310          SmmCommData->BootRecordData = (VOID *)((UINTN)SmmCommMemRegion->PhysicalStart + SMM_BOOT_RECORD_COMM_SIZE);
     311          SmmCommData->BootRecordSize = ReservedMemSize - SMM_BOOT_RECORD_COMM_SIZE;
     312          while (SmmBootRecordDataRetrieved < SmmBootRecordDataSize) {
    310313            Status = Communication->Communicate (Communication, SmmBootRecordCommBuffer, &CommSize);
    311314            ASSERT_EFI_ERROR (Status);
    312315            ASSERT_EFI_ERROR (SmmCommData->ReturnStatus);
    313             if (SmmCommData->BootRecordOffset + SmmCommData->BootRecordSize > SmmBootRecordDataSize) {
    314               CopyMem ((UINT8 *)SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmBootRecordDataSize - SmmCommData->BootRecordOffset);
     316            if (SmmBootRecordDataRetrieved + SmmCommData->BootRecordSize > SmmBootRecordDataSize) {
     317              CopyMem ((UINT8 *)SmmBootRecordData + SmmBootRecordDataRetrieved, SmmCommData->BootRecordData, SmmBootRecordDataSize - SmmBootRecordDataRetrieved);
    315318            } else {
    316               CopyMem ((UINT8 *)SmmBootRecordData + SmmCommData->BootRecordOffset, SmmCommData->BootRecordData, SmmCommData->BootRecordSize);
     319              CopyMem ((UINT8 *)SmmBootRecordData + SmmBootRecordDataRetrieved, SmmCommData->BootRecordData, SmmCommData->BootRecordSize);
    317320            }
    318321
    319             SmmCommData->BootRecordOffset = SmmCommData->BootRecordOffset + SmmCommData->BootRecordSize;
     322            SmmBootRecordDataRetrieved    += SmmCommData->BootRecordSize;
     323            SmmCommData->BootRecordOffset += SmmCommData->BootRecordSize;
    320324          }
     325
     326          mSmmBootRecordOffset = SmmCommData->BootRecordOffset;
    321327
    322328          *SmmPerfData     = SmmBootRecordData;
     
    14041410        sizeof (UINT64)
    14051411        );
     1412      Status = gBS->InstallConfigurationTable (&gEdkiiFpdtExtendedFirmwarePerformanceGuid, (VOID *)(UINTN)BPDTAddr);
     1413      ASSERT_EFI_ERROR (Status);
    14061414    }
    14071415
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/TraceHubDebugSysTLib/BaseTraceHubDebugSysTLib.c

    r101291 r105670  
    4242  RETURN_STATUS     Status;
    4343  UINT32            DbgInstCount;
    44   UINT16            Index;
     44  UINT32            Index;
    4545
    4646  if (NumberOfBytes == 0) {
     
    110110  RETURN_STATUS     Status;
    111111  UINT32            DbgInstCount;
    112   UINT16            Index;
     112  UINT32            Index;
    113113
    114114  if (Guid == NULL) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/TraceHubDebugSysTLib/DxeSmmTraceHubDebugSysTLib.c

    r101291 r105670  
    4646  MIPI_SYST_HEADER  MipiSystHeader;
    4747  RETURN_STATUS     Status;
    48   UINT16            Index;
     48  UINT32            Index;
    4949
    5050  if ((mDbgInstCount == 0) || (mThDebugInstArray == NULL)) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/TraceHubDebugSysTLib/InternalTraceHubApi.c

    r101291 r105670  
    5757{
    5858  UINT8   *DbgContext;
    59   UINT16  Index;
     59  UINT32  Index;
    6060
    6161  DbgContext = GetFirstGuidHob (&gTraceHubDebugInfoHobGuid);
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/UefiBootManagerLib/BmBoot.c

    r101291 r105670  
    881881  EFI_DEVICE_PATH_PROTOCOL  *Instance;
    882882  UINTN                     Size;
     883  BOOLEAN                   MatchFound;
     884  BOOLEAN                   ConnectAllAttempted;
    883885
    884886  //
     
    975977  // to search all devices in the system for a matched partition
    976978  //
    977   EfiBootManagerConnectAll ();
    978   Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
    979   if (EFI_ERROR (Status)) {
    980     BlockIoHandleCount = 0;
    981     BlockIoBuffer      = NULL;
    982   }
    983 
    984   //
    985   // Loop through all the device handles that support the BLOCK_IO Protocol
    986   //
    987   for (Index = 0; Index < BlockIoHandleCount; Index++) {
    988     BlockIoDevicePath = DevicePathFromHandle (BlockIoBuffer[Index]);
    989     if (BlockIoDevicePath == NULL) {
    990       continue;
    991     }
    992 
    993     if (BmMatchPartitionDevicePathNode (BlockIoDevicePath, (HARDDRIVE_DEVICE_PATH *)FilePath)) {
    994       //
    995       // Find the matched partition device path
    996       //
    997       TempDevicePath = AppendDevicePath (BlockIoDevicePath, NextDevicePathNode (FilePath));
    998       FullPath       = BmGetNextLoadOptionDevicePath (TempDevicePath, NULL);
    999       FreePool (TempDevicePath);
    1000 
    1001       if (FullPath != NULL) {
    1002         BmCachePartitionDevicePath (&CachedDevicePath, BlockIoDevicePath);
    1003 
     979  BlockIoBuffer       = NULL;
     980  MatchFound          = FALSE;
     981  ConnectAllAttempted = FALSE;
     982  do {
     983    if (BlockIoBuffer != NULL) {
     984      FreePool (BlockIoBuffer);
     985    }
     986
     987    Status = gBS->LocateHandleBuffer (ByProtocol, &gEfiBlockIoProtocolGuid, NULL, &BlockIoHandleCount, &BlockIoBuffer);
     988    if (EFI_ERROR (Status)) {
     989      BlockIoHandleCount = 0;
     990      BlockIoBuffer      = NULL;
     991    }
     992
     993    //
     994    // Loop through all the device handles that support the BLOCK_IO Protocol
     995    //
     996    for (Index = 0; Index < BlockIoHandleCount; Index++) {
     997      BlockIoDevicePath = DevicePathFromHandle (BlockIoBuffer[Index]);
     998      if (BlockIoDevicePath == NULL) {
     999        continue;
     1000      }
     1001
     1002      if (BmMatchPartitionDevicePathNode (BlockIoDevicePath, (HARDDRIVE_DEVICE_PATH *)FilePath)) {
    10041003        //
    1005         // Save the matching Device Path so we don't need to do a connect all next time
    1006         // Failing to save only impacts performance next time expanding the short-form device path
     1004        // Find the matched partition device path
    10071005        //
    1008         Status = gRT->SetVariable (
    1009                         L"HDDP",
    1010                         &mBmHardDriveBootVariableGuid,
    1011                         EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_NON_VOLATILE,
    1012                         GetDevicePathSize (CachedDevicePath),
    1013                         CachedDevicePath
    1014                         );
    1015 
    1016         break;
     1006        TempDevicePath = AppendDevicePath (BlockIoDevicePath, NextDevicePathNode (FilePath));
     1007        FullPath       = BmGetNextLoadOptionDevicePath (TempDevicePath, NULL);
     1008        FreePool (TempDevicePath);
     1009
     1010        if (FullPath != NULL) {
     1011          BmCachePartitionDevicePath (&CachedDevicePath, BlockIoDevicePath);
     1012
     1013          //
     1014          // Save the matching Device Path so we don't need to do a connect all next time
     1015          // Failing to save only impacts performance next time expanding the short-form device path
     1016          //
     1017          Status = gRT->SetVariable (
     1018                          L"HDDP",
     1019                          &mBmHardDriveBootVariableGuid,
     1020                          EFI_VARIABLE_BOOTSERVICE_ACCESS |
     1021                          EFI_VARIABLE_NON_VOLATILE,
     1022                          GetDevicePathSize (CachedDevicePath),
     1023                          CachedDevicePath
     1024                          );
     1025          MatchFound = TRUE;
     1026          break;
     1027        }
    10171028      }
    10181029    }
    1019   }
     1030
     1031    //
     1032    // If we found a matching BLOCK_IO handle or we've already
     1033    // tried a ConnectAll, we are done searching.
     1034    //
     1035    if (MatchFound || ConnectAllAttempted) {
     1036      break;
     1037    }
     1038
     1039    EfiBootManagerConnectAll ();
     1040    ConnectAllAttempted = TRUE;
     1041  } while (1);
    10201042
    10211043  if (CachedDevicePath != NULL) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/UefiBootManagerLib/BmLoadOption.c

    r99404 r105670  
    14291429  }
    14301430
     1431  if (LoadOption->OptionType == LoadOptionTypePlatformRecovery) {
     1432    //
     1433    // Signal the EVT_SIGNAL_READY_TO_BOOT event when we are about to load and execute the boot option.
     1434    //
     1435    EfiSignalEventReadyToBoot ();
     1436    //
     1437    // Report Status Code to indicate ReadyToBoot was signaled
     1438    //
     1439    REPORT_STATUS_CODE (EFI_PROGRESS_CODE, (EFI_SOFTWARE_DXE_BS_DRIVER | EFI_SW_DXE_BS_PC_READY_TO_BOOT_EVENT));
     1440  }
     1441
    14311442  //
    14321443  // Load and start the load option.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/UefiSortLib/GoogleTest/UefiSortLibGoogleTest.cpp

    r101291 r105670  
    2121  )
    2222{
    23   if (*(UINT32*)Right > *(UINT32*)Left) {
     23  if (*(UINT32 *)Right > *(UINT32 *)Left) {
    2424    return 1;
    25   } else if (*(UINT32*)Right < *(UINT32*)Left) {
     25  } else if (*(UINT32 *)Right < *(UINT32 *)Left) {
    2626    return -1;
    2727  }
     
    3232// Test PerformQuickSort() API from UefiSortLib to verify a UINT32 array
    3333// with 9 elements in ascending order is sorted into descending order.
    34 TEST(PerformQuickSortTest, SortUint32AscendingArray_Size9) {
    35   CONST UINT32 ArraySize = 9;
    36   UINT32       BuffActual[ArraySize];
    37   UINT32       BuffExpected[ArraySize];
     34TEST (PerformQuickSortTest, SortUint32AscendingArray_Size9) {
     35  CONST UINT32  ArraySize = 9;
     36  UINT32        BuffActual[ArraySize];
     37  UINT32        BuffExpected[ArraySize];
    3838
    3939  for (UINT32 Index = 0; Index < ArraySize; Index++) {
    40     BuffActual[Index] = Index + 1;
     40    BuffActual[Index]   = Index + 1;
    4141    BuffExpected[Index] = ArraySize - Index;
    4242  }
    4343
    44   PerformQuickSort (BuffActual, (UINTN)ArraySize, sizeof(UINT32), (SORT_COMPARE)CompareUint32);
    45   EXPECT_THAT(BuffActual, ElementsAreArray(BuffExpected, ArraySize));
     44  PerformQuickSort (BuffActual, (UINTN)ArraySize, sizeof (UINT32), (SORT_COMPARE)CompareUint32);
     45  EXPECT_THAT (BuffActual, ElementsAreArray (BuffExpected, ArraySize));
    4646}
    4747
    4848// Test StringCompare() API from UefiSortLib to verify the comparison
    4949// succeeds when the same buffer is compared with itself.
    50 TEST(StringCompareTest, CompareSameBuffer) {
    51   INTN           RetVal;
    52   CONST CHAR16  *Buffer = (CHAR16*)L"abcdefg";
     50TEST (StringCompareTest, CompareSameBuffer) {
     51  INTN          RetVal;
     52  CONST CHAR16  *Buffer = (CHAR16 *)L"abcdefg";
    5353
    5454  RetVal = StringCompare (&Buffer, &Buffer);
    55   EXPECT_EQ(RetVal, 0);
     55  EXPECT_EQ (RetVal, 0);
    5656}
    5757
    58 int main(int argc, char* argv[]) {
    59   testing::InitGoogleTest(&argc, argv);
    60   return RUN_ALL_TESTS();
     58int
     59main (
     60  int   argc,
     61  char  *argv[]
     62  )
     63{
     64  testing::InitGoogleTest (&argc, argv);
     65  return RUN_ALL_TESTS ();
    6166}
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/VarCheckPolicyLib/VarCheckPolicyLib.c

    r101291 r105670  
    7777  EFI_STATUS                               Status;
    7878  EFI_STATUS                               SubCommandStatus;
    79   VAR_CHECK_POLICY_COMM_HEADER             *PolicyCommmHeader;
    80   VAR_CHECK_POLICY_COMM_HEADER             *InternalPolicyCommmHeader;
     79  VAR_CHECK_POLICY_COMM_HEADER             *PolicyCommHeader;
     80  VAR_CHECK_POLICY_COMM_HEADER             *InternalPolicyCommHeader;
    8181  VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS  *IsEnabledParams;
    8282  VAR_CHECK_POLICY_COMM_DUMP_PARAMS        *DumpParamsIn;
    8383  VAR_CHECK_POLICY_COMM_DUMP_PARAMS        *DumpParamsOut;
     84  VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS    *GetInfoParamsInternal;
     85  VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS    *GetInfoParamsExternal;
     86  CHAR16                                   *InternalCopyOfOutputVariableName;
     87  CHAR16                                   *ExternalCopyOfOutputVariableName;
    8488  UINT8                                    *DumpInputBuffer;
    8589  UINT8                                    *DumpOutputBuffer;
     90  UINTN                                    AllowedOutputVariableNameSize;
    8691  UINTN                                    DumpTotalPages;
     92  UINTN                                    LocalSize;
    8793  VARIABLE_POLICY_ENTRY                    *PolicyEntry;
    8894  UINTN                                    ExpectedSize;
     
    123129  InternalCommBuffer = &mSecurityEvalBuffer[0];
    124130  CopyMem (InternalCommBuffer, CommBuffer, InternalCommBufferSize);
    125   PolicyCommmHeader         = CommBuffer;
    126   InternalPolicyCommmHeader = InternalCommBuffer;
     131  PolicyCommHeader         = CommBuffer;
     132  InternalPolicyCommHeader = InternalCommBuffer;
    127133  // Check the revision and the signature of the comm header.
    128   if ((InternalPolicyCommmHeader->Signature != VAR_CHECK_POLICY_COMM_SIG) ||
    129       (InternalPolicyCommmHeader->Revision != VAR_CHECK_POLICY_COMM_REVISION))
     134  if ((InternalPolicyCommHeader->Signature != VAR_CHECK_POLICY_COMM_SIG) ||
     135      (InternalPolicyCommHeader->Revision != VAR_CHECK_POLICY_COMM_REVISION))
    130136  {
    131137    DEBUG ((DEBUG_INFO, "%a - Signature or revision are incorrect!\n", __func__));
    132138    // We have verified the buffer is not null and have enough size to hold Result field.
    133     PolicyCommmHeader->Result = EFI_INVALID_PARAMETER;
     139    PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
    134140    return EFI_SUCCESS;
    135141  }
     
    137143  // If we're in the middle of a paginated dump and any other command is sent,
    138144  // pagination cache must be cleared.
    139   if ((mPaginationCache != NULL) && (InternalPolicyCommmHeader->Command != mCurrentPaginationCommand)) {
     145  if ((mPaginationCache != NULL) && (InternalPolicyCommHeader->Command != mCurrentPaginationCommand)) {
    140146    FreePool (mPaginationCache);
    141147    mPaginationCache          = NULL;
     
    147153  // Now we can process the command as it was sent.
    148154  //
    149   PolicyCommmHeader->Result = EFI_ABORTED;    // Set a default return for incomplete commands.
    150   switch (InternalPolicyCommmHeader->Command) {
     155  PolicyCommHeader->Result = EFI_ABORTED;    // Set a default return for incomplete commands.
     156  switch (InternalPolicyCommHeader->Command) {
    151157    case VAR_CHECK_POLICY_COMMAND_DISABLE:
    152       PolicyCommmHeader->Result = DisableVariablePolicy ();
     158      PolicyCommHeader->Result = DisableVariablePolicy ();
    153159      break;
    154160
     
    159165      if (InternalCommBufferSize < ExpectedSize) {
    160166        DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize));
    161         PolicyCommmHeader->Result = EFI_INVALID_PARAMETER;
     167        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
    162168        break;
    163169      }
    164170
    165171      // Now that we know we've got a valid size, we can fill in the rest of the data.
    166       IsEnabledParams           = (VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS *)((UINT8 *)CommBuffer + sizeof (VAR_CHECK_POLICY_COMM_HEADER));
    167       IsEnabledParams->State    = IsVariablePolicyEnabled ();
    168       PolicyCommmHeader->Result = EFI_SUCCESS;
     172      IsEnabledParams          = (VAR_CHECK_POLICY_COMM_IS_ENABLED_PARAMS *)((UINT8 *)CommBuffer + sizeof (VAR_CHECK_POLICY_COMM_HEADER));
     173      IsEnabledParams->State   = IsVariablePolicyEnabled ();
     174      PolicyCommHeader->Result = EFI_SUCCESS;
    169175      break;
    170176
     
    175181      if (InternalCommBufferSize < ExpectedSize) {
    176182        DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize));
    177         PolicyCommmHeader->Result = EFI_INVALID_PARAMETER;
     183        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
    178184        break;
    179185      }
     
    188194      {
    189195        DEBUG ((DEBUG_INFO, "%a - Bad policy entry contents!\n", __func__));
    190         PolicyCommmHeader->Result = EFI_INVALID_PARAMETER;
    191         break;
    192       }
    193 
    194       PolicyCommmHeader->Result = RegisterVariablePolicy (PolicyEntry);
     196        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
     197        break;
     198      }
     199
     200      PolicyCommHeader->Result = RegisterVariablePolicy (PolicyEntry);
    195201      break;
    196202
     
    201207      if (InternalCommBufferSize < ExpectedSize) {
    202208        DEBUG ((DEBUG_INFO, "%a - Bad comm buffer size! %d < %d\n", __func__, InternalCommBufferSize, ExpectedSize));
    203         PolicyCommmHeader->Result = EFI_INVALID_PARAMETER;
     209        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
    204210        break;
    205211      }
    206212
    207213      // Now that we know we've got a valid size, we can fill in the rest of the data.
    208       DumpParamsIn  = (VAR_CHECK_POLICY_COMM_DUMP_PARAMS *)(InternalPolicyCommmHeader + 1);
    209       DumpParamsOut = (VAR_CHECK_POLICY_COMM_DUMP_PARAMS *)(PolicyCommmHeader + 1);
     214      DumpParamsIn  = (VAR_CHECK_POLICY_COMM_DUMP_PARAMS *)(InternalPolicyCommHeader + 1);
     215      DumpParamsOut = (VAR_CHECK_POLICY_COMM_DUMP_PARAMS *)(PolicyCommHeader + 1);
    210216
    211217      // If we're requesting the first page, initialize the cache and get the sizes.
     
    290296
    291297      // There's currently no use for this, but it shouldn't be hard to implement.
    292       PolicyCommmHeader->Result = SubCommandStatus;
     298      PolicyCommHeader->Result = SubCommandStatus;
    293299      break;
    294300
    295301    case VAR_CHECK_POLICY_COMMAND_LOCK:
    296       PolicyCommmHeader->Result = LockVariablePolicy ();
     302      PolicyCommHeader->Result = LockVariablePolicy ();
     303      break;
     304
     305    case VAR_CHECK_POLICY_COMMAND_GET_INFO:
     306    case VAR_CHECK_POLICY_COMMAND_GET_LOCK_VAR_STATE_INFO:
     307      ExpectedSize += VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END + VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE;
     308
     309      if (InternalCommBufferSize < ExpectedSize) {
     310        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
     311        break;
     312      }
     313
     314      GetInfoParamsInternal = (VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS *)(InternalPolicyCommHeader + 1);
     315      GetInfoParamsExternal = (VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS *)(PolicyCommHeader + 1);
     316
     317      SubCommandStatus =  SafeUintnSub (
     318                            VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE,
     319                            GetInfoParamsInternal->InputVariableNameSize,
     320                            &AllowedOutputVariableNameSize
     321                            );
     322      if (EFI_ERROR (SubCommandStatus)) {
     323        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
     324        break;
     325      }
     326
     327      if (GetInfoParamsInternal->OutputVariableNameSize > 0) {
     328        SubCommandStatus =  SafeUintnAdd (
     329                              ((UINTN)GetInfoParamsInternal + VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END),
     330                              (UINTN)GetInfoParamsInternal->InputVariableNameSize,
     331                              (UINTN *)&InternalCopyOfOutputVariableName
     332                              );
     333        if (EFI_ERROR (SubCommandStatus)) {
     334          PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
     335          break;
     336        }
     337      } else {
     338        InternalCopyOfOutputVariableName = NULL;
     339      }
     340
     341      ZeroMem (&GetInfoParamsInternal->OutputPolicyEntry, sizeof (GetInfoParamsInternal->OutputPolicyEntry));
     342      ZeroMem (&GetInfoParamsExternal->OutputPolicyEntry, sizeof (GetInfoParamsExternal->OutputPolicyEntry));
     343
     344      LocalSize = (UINTN)GetInfoParamsInternal->OutputVariableNameSize;
     345
     346      if (InternalPolicyCommHeader->Command == VAR_CHECK_POLICY_COMMAND_GET_INFO) {
     347        SubCommandStatus =  GetVariablePolicyInfo (
     348                              GetInfoParamsInternal->InputVariableName,
     349                              &GetInfoParamsInternal->InputVendorGuid,
     350                              &LocalSize,
     351                              &GetInfoParamsInternal->OutputPolicyEntry.VariablePolicy,
     352                              InternalCopyOfOutputVariableName
     353                              );
     354      } else if (InternalPolicyCommHeader->Command == VAR_CHECK_POLICY_COMMAND_GET_LOCK_VAR_STATE_INFO) {
     355        SubCommandStatus =  GetLockOnVariableStateVariablePolicyInfo (
     356                              GetInfoParamsInternal->InputVariableName,
     357                              &GetInfoParamsInternal->InputVendorGuid,
     358                              &LocalSize,
     359                              &GetInfoParamsInternal->OutputPolicyEntry.LockOnVarStatePolicy,
     360                              InternalCopyOfOutputVariableName
     361                              );
     362      } else {
     363        PolicyCommHeader->Result = EFI_INVALID_PARAMETER;
     364        break;
     365      }
     366
     367      if (EFI_ERROR (SubCommandStatus) && (SubCommandStatus != EFI_BUFFER_TOO_SMALL)) {
     368        PolicyCommHeader->Result = SubCommandStatus;
     369        break;
     370      }
     371
     372      if (EFI_ERROR (SafeUintnToUint32 (LocalSize, &GetInfoParamsInternal->OutputVariableNameSize))) {
     373        PolicyCommHeader->Result = EFI_BAD_BUFFER_SIZE;
     374        break;
     375      }
     376
     377      ASSERT (sizeof (GetInfoParamsInternal->OutputPolicyEntry) == sizeof (GetInfoParamsExternal->OutputPolicyEntry));
     378      CopyMem (
     379        &GetInfoParamsExternal->OutputPolicyEntry,
     380        &GetInfoParamsInternal->OutputPolicyEntry,
     381        sizeof (GetInfoParamsExternal->OutputPolicyEntry)
     382        );
     383
     384      GetInfoParamsExternal->OutputVariableNameSize = GetInfoParamsInternal->OutputVariableNameSize;
     385      if (SubCommandStatus == EFI_BUFFER_TOO_SMALL) {
     386        PolicyCommHeader->Result = EFI_BUFFER_TOO_SMALL;
     387        break;
     388      }
     389
     390      SubCommandStatus =  SafeUintnAdd (
     391                            ((UINTN)GetInfoParamsExternal + VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END),
     392                            (UINTN)GetInfoParamsInternal->InputVariableNameSize,
     393                            (UINTN *)&ExternalCopyOfOutputVariableName
     394                            );
     395      if (EFI_ERROR (SubCommandStatus)) {
     396        PolicyCommHeader->Result = EFI_BAD_BUFFER_SIZE;
     397        break;
     398      }
     399
     400      if (GetInfoParamsInternal->OutputVariableNameSize > 0) {
     401        SubCommandStatus =  StrnCpyS (
     402                              ExternalCopyOfOutputVariableName,
     403                              AllowedOutputVariableNameSize,
     404                              InternalCopyOfOutputVariableName,
     405                              (UINTN)GetInfoParamsInternal->OutputVariableNameSize
     406                              );
     407        ASSERT_EFI_ERROR (SubCommandStatus);
     408      } else {
     409        // The comm buffer should always have the space for the variable policy output
     410        // variable name. Fill it with NULL chars if a variable name is not present so
     411        // it has a consistent value in the case of variable name absence.
     412        SetMem (ExternalCopyOfOutputVariableName, AllowedOutputVariableNameSize, CHAR_NULL);
     413      }
     414
     415      PolicyCommHeader->Result = SubCommandStatus;
     416
    297417      break;
    298418
    299419    default:
    300420      // Mark unknown requested command as EFI_UNSUPPORTED.
    301       DEBUG ((DEBUG_INFO, "%a - Invalid command requested! %d\n", __func__, PolicyCommmHeader->Command));
    302       PolicyCommmHeader->Result = EFI_UNSUPPORTED;
     421      DEBUG ((DEBUG_INFO, "%a - Invalid command requested! %d\n", __func__, PolicyCommHeader->Command));
     422      PolicyCommHeader->Result = EFI_UNSUPPORTED;
    303423      break;
    304424  }
     
    308428    "%a - Command %d returning %r.\n",
    309429    __func__,
    310     PolicyCommmHeader->Command,
    311     PolicyCommmHeader->Result
     430    PolicyCommHeader->Command,
     431    PolicyCommHeader->Result
    312432    ));
    313433
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.c

    r101291 r105670  
    99#include <Uefi.h>
    1010
     11#include <Library/BaseLib.h>
    1112#include <Library/SafeIntLib.h>
    1213#include <Library/MemoryAllocationLib.h>
     
    686687
    687688/**
     689  This function will return variable policy information for a UEFI variable with a
     690  registered variable policy.
     691
     692  @param[in]      VariableName                          The name of the variable to use for the policy search.
     693  @param[in]      VendorGuid                            The vendor GUID of the variable to use for the policy search.
     694  @param[in,out]  VariablePolicyVariableNameBufferSize  On input, the size, in bytes, of the VariablePolicyVariableName
     695                                                        buffer.
     696
     697                                                        On output, the size, in bytes, needed to store the variable
     698                                                        policy variable name.
     699
     700                                                        If testing for the VariablePolicyVariableName buffer size
     701                                                        needed, set this value to zero so EFI_BUFFER_TOO_SMALL is
     702                                                        guaranteed to be returned if the variable policy variable name
     703                                                        is found.
     704  @param[out]     VariablePolicy                        Pointer to a buffer where the policy entry will be written
     705                                                        if found.
     706  @param[out]     VariablePolicyVariableName            Pointer to a buffer where the variable name used for the
     707                                                        variable policy will be written if a variable name is
     708                                                        registered.
     709
     710                                                        If the variable policy is not associated with a variable name
     711                                                        (e.g. applied to variable vendor namespace) and this parameter
     712                                                        is given, this parameter will not be modified and
     713                                                        VariablePolicyVariableNameBufferSize will be set to zero to
     714                                                        indicate a name was not present.
     715
     716                                                        If the pointer given is not NULL,
     717                                                        VariablePolicyVariableNameBufferSize must be non-NULL.
     718
     719  @retval     EFI_SUCCESS             A variable policy entry was found and returned successfully.
     720  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     721  @retval     EFI_BUFFER_TOO_SMALL    The VariablePolicyVariableName buffer value is too small for the size needed.
     722                                      The buffer should now point to the size needed.
     723  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     724  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     725                                      VariablePolicyVariableName is non-NULL and VariablePolicyVariableNameBufferSize
     726                                      is NULL.
     727  @retval     EFI_NOT_FOUND           A variable policy was not found for the given UEFI variable name and vendor GUID.
     728
     729**/
     730EFI_STATUS
     731EFIAPI
     732GetVariablePolicyInfo (
     733  IN      CONST CHAR16           *VariableName,
     734  IN      CONST EFI_GUID         *VendorGuid,
     735  IN OUT  UINTN                  *VariablePolicyVariableNameBufferSize OPTIONAL,
     736  OUT     VARIABLE_POLICY_ENTRY  *VariablePolicy,
     737  OUT     CHAR16                 *VariablePolicyVariableName OPTIONAL
     738  )
     739{
     740  EFI_STATUS             Status;
     741  UINT8                  MatchPriority;
     742  UINTN                  LocalVariablePolicyVariableNameBufferSize;
     743  UINTN                  RequiredVariablePolicyVariableNameBufferSize;
     744  VARIABLE_POLICY_ENTRY  *MatchPolicy;
     745
     746  Status = EFI_SUCCESS;
     747
     748  if (!IsVariablePolicyLibInitialized ()) {
     749    return EFI_NOT_READY;
     750  }
     751
     752  if ((VariableName == NULL) || (VendorGuid == NULL) || (VariablePolicy == NULL)) {
     753    return EFI_INVALID_PARAMETER;
     754  }
     755
     756  MatchPolicy = GetBestPolicyMatch (
     757                  VariableName,
     758                  VendorGuid,
     759                  &MatchPriority
     760                  );
     761  if (MatchPolicy != NULL) {
     762    CopyMem (VariablePolicy, MatchPolicy, sizeof (*VariablePolicy));
     763
     764    if (VariablePolicyVariableNameBufferSize == NULL) {
     765      if (VariablePolicyVariableName != NULL) {
     766        return EFI_INVALID_PARAMETER;
     767      }
     768
     769      return Status;
     770    }
     771
     772    if (MatchPolicy->Size != MatchPolicy->OffsetToName) {
     773      if (MatchPolicy->Size < MatchPolicy->OffsetToName) {
     774        ASSERT (MatchPolicy->Size > MatchPolicy->OffsetToName);
     775        return EFI_BAD_BUFFER_SIZE;
     776      }
     777
     778      RequiredVariablePolicyVariableNameBufferSize = (UINTN)(MatchPolicy->Size - MatchPolicy->OffsetToName);
     779      ASSERT (RequiredVariablePolicyVariableNameBufferSize > 0);
     780
     781      if (*VariablePolicyVariableNameBufferSize < RequiredVariablePolicyVariableNameBufferSize) {
     782        // Let the caller get the size needed to hold the policy variable name
     783        *VariablePolicyVariableNameBufferSize = RequiredVariablePolicyVariableNameBufferSize;
     784        return EFI_BUFFER_TOO_SMALL;
     785      }
     786
     787      if (VariablePolicyVariableName == NULL) {
     788        // If the policy variable name size given is valid, then a valid policy variable name buffer should be provided
     789        *VariablePolicyVariableNameBufferSize = RequiredVariablePolicyVariableNameBufferSize;
     790        return EFI_INVALID_PARAMETER;
     791      }
     792
     793      LocalVariablePolicyVariableNameBufferSize = *VariablePolicyVariableNameBufferSize;
     794
     795      // Actual string size should match expected string size
     796      if (
     797          ((StrnLenS (GET_POLICY_NAME (MatchPolicy), RequiredVariablePolicyVariableNameBufferSize) + 1) * sizeof (CHAR16))
     798          != RequiredVariablePolicyVariableNameBufferSize)
     799      {
     800        ASSERT_EFI_ERROR (EFI_BAD_BUFFER_SIZE);
     801        return EFI_BAD_BUFFER_SIZE;
     802      }
     803
     804      *VariablePolicyVariableNameBufferSize = RequiredVariablePolicyVariableNameBufferSize;
     805
     806      Status = StrnCpyS (
     807                 VariablePolicyVariableName,
     808                 LocalVariablePolicyVariableNameBufferSize / sizeof (CHAR16),
     809                 GET_POLICY_NAME (MatchPolicy),
     810                 RequiredVariablePolicyVariableNameBufferSize / sizeof (CHAR16)
     811                 );
     812      ASSERT_EFI_ERROR (Status);
     813    } else {
     814      // A variable policy variable name is not present. Return values according to interface.
     815      *VariablePolicyVariableNameBufferSize = 0;
     816    }
     817
     818    return Status;
     819  }
     820
     821  return EFI_NOT_FOUND;
     822}
     823
     824/**
     825  This function will return the Lock on Variable State policy information for the policy
     826  associated with the given UEFI variable.
     827
     828  @param[in]      VariableName                              The name of the variable to use for the policy search.
     829  @param[in]      VendorGuid                                The vendor GUID of the variable to use for the policy
     830                                                            search.
     831  @param[in,out]  VariableLockPolicyVariableNameBufferSize  On input, the size, in bytes, of the
     832                                                            VariableLockPolicyVariableName buffer.
     833
     834                                                            On output, the size, in bytes, needed to store the variable
     835                                                            policy variable name.
     836
     837                                                            If testing for the VariableLockPolicyVariableName buffer
     838                                                            size needed, set this value to zero so EFI_BUFFER_TOO_SMALL
     839                                                            is guaranteed to be returned if the variable policy variable
     840                                                            name is found.
     841  @param[out]     VariablePolicy                            Pointer to a buffer where the policy entry will be written
     842                                                            if found.
     843  @param[out]     VariableLockPolicyVariableName            Pointer to a buffer where the variable name used for the
     844                                                            variable lock on variable state policy will be written if
     845                                                            a variable name is registered.
     846
     847                                                            If the lock on variable policy is not associated with a
     848                                                            variable name (e.g. applied to variable vendor namespace)
     849                                                            and this parameter is given, this parameter will not be
     850                                                            modified and VariableLockPolicyVariableNameBufferSize will
     851                                                            be set to zero to indicate a name was not present.
     852
     853                                                            If the pointer given is not NULL,
     854                                                            VariableLockPolicyVariableNameBufferSize must be non-NULL.
     855
     856  @retval     EFI_SUCCESS             A Lock on Variable State variable policy entry was found and returned
     857                                      successfully.
     858  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     859  @retval     EFI_BUFFER_TOO_SMALL    The VariableLockPolicyVariableName buffer is too small for the size needed.
     860                                      The buffer should now point to the size needed.
     861  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     862  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     863                                      VariableLockPolicyVariableName is non-NULL and
     864                                      VariableLockPolicyVariableNameBufferSize is NULL.
     865  @retval     EFI_NOT_FOUND           A Lock on Variable State variable policy was not found for the given UEFI
     866                                      variable name and vendor GUID.
     867
     868**/
     869EFI_STATUS
     870EFIAPI
     871GetLockOnVariableStateVariablePolicyInfo (
     872  IN      CONST CHAR16                       *VariableName,
     873  IN      CONST EFI_GUID                     *VendorGuid,
     874  IN OUT  UINTN                              *VariableLockPolicyVariableNameBufferSize OPTIONAL,
     875  OUT     VARIABLE_LOCK_ON_VAR_STATE_POLICY  *VariablePolicy,
     876  OUT     CHAR16                             *VariableLockPolicyVariableName OPTIONAL
     877  )
     878{
     879  EFI_STATUS                         Status;
     880  UINT8                              MatchPriority;
     881  UINTN                              RequiredVariablePolicyVariableNameBufferSize;
     882  UINTN                              RequiredVariableLockPolicyVariableNameBufferSize;
     883  UINTN                              LocalVariablePolicyLockVariableNameBufferSize;
     884  UINTN                              LockOnVarStatePolicyEndOffset;
     885  CHAR16                             *LocalVariableLockPolicyVariableName;
     886  VARIABLE_LOCK_ON_VAR_STATE_POLICY  *LocalLockOnVarStatePolicy;
     887  VARIABLE_POLICY_ENTRY              *MatchPolicy;
     888
     889  Status = EFI_SUCCESS;
     890
     891  if (!IsVariablePolicyLibInitialized ()) {
     892    return EFI_NOT_READY;
     893  }
     894
     895  if ((VariableName == NULL) || (VendorGuid == NULL) || (VariablePolicy == NULL)) {
     896    return EFI_INVALID_PARAMETER;
     897  }
     898
     899  MatchPolicy = GetBestPolicyMatch (
     900                  VariableName,
     901                  VendorGuid,
     902                  &MatchPriority
     903                  );
     904  if (MatchPolicy != NULL) {
     905    if (MatchPolicy->LockPolicyType != VARIABLE_POLICY_TYPE_LOCK_ON_VAR_STATE) {
     906      return EFI_NOT_FOUND;
     907    }
     908
     909    Status = SafeUintnAdd (
     910               sizeof (VARIABLE_POLICY_ENTRY),
     911               sizeof (VARIABLE_LOCK_ON_VAR_STATE_POLICY),
     912               &LockOnVarStatePolicyEndOffset
     913               );
     914    if (EFI_ERROR (Status) || (LockOnVarStatePolicyEndOffset > (UINTN)MatchPolicy->Size)) {
     915      return EFI_BAD_BUFFER_SIZE;
     916    }
     917
     918    LocalLockOnVarStatePolicy = (VARIABLE_LOCK_ON_VAR_STATE_POLICY *)(MatchPolicy + 1);
     919    CopyMem (VariablePolicy, LocalLockOnVarStatePolicy, sizeof (*LocalLockOnVarStatePolicy));
     920
     921    if ((VariableLockPolicyVariableNameBufferSize == NULL)) {
     922      if (VariableLockPolicyVariableName != NULL) {
     923        return EFI_INVALID_PARAMETER;
     924      }
     925
     926      return Status;
     927    }
     928
     929    // The name offset should be less than or equal to the total policy size.
     930    if (MatchPolicy->Size < MatchPolicy->OffsetToName) {
     931      return EFI_BAD_BUFFER_SIZE;
     932    }
     933
     934    RequiredVariablePolicyVariableNameBufferSize     = (UINTN)(MatchPolicy->Size - MatchPolicy->OffsetToName);
     935    RequiredVariableLockPolicyVariableNameBufferSize =  MatchPolicy->Size -
     936                                                       (LockOnVarStatePolicyEndOffset + RequiredVariablePolicyVariableNameBufferSize);
     937
     938    LocalVariablePolicyLockVariableNameBufferSize = *VariableLockPolicyVariableNameBufferSize;
     939    *VariableLockPolicyVariableNameBufferSize     = RequiredVariableLockPolicyVariableNameBufferSize;
     940
     941    if (LocalVariablePolicyLockVariableNameBufferSize < RequiredVariableLockPolicyVariableNameBufferSize) {
     942      // Let the caller get the size needed to hold the policy variable name
     943      return EFI_BUFFER_TOO_SMALL;
     944    }
     945
     946    if (VariableLockPolicyVariableName == NULL) {
     947      // If the policy variable name size given is valid, then a valid policy variable name buffer should be provided
     948      return EFI_INVALID_PARAMETER;
     949    }
     950
     951    if (RequiredVariableLockPolicyVariableNameBufferSize == 0) {
     952      return Status;
     953    }
     954
     955    LocalVariableLockPolicyVariableName       = (CHAR16 *)((UINT8 *)LocalLockOnVarStatePolicy + sizeof (*LocalLockOnVarStatePolicy));
     956    *VariableLockPolicyVariableNameBufferSize = RequiredVariableLockPolicyVariableNameBufferSize;
     957
     958    // Actual string size should match expected string size (if a variable name is present)
     959    if (
     960        (RequiredVariablePolicyVariableNameBufferSize > 0) &&
     961        (((StrnLenS (GET_POLICY_NAME (MatchPolicy), RequiredVariablePolicyVariableNameBufferSize) + 1) * sizeof (CHAR16)) !=
     962         RequiredVariablePolicyVariableNameBufferSize))
     963    {
     964      ASSERT_EFI_ERROR (EFI_BAD_BUFFER_SIZE);
     965      return EFI_BAD_BUFFER_SIZE;
     966    }
     967
     968    // Actual string size should match expected string size (if here, variable lock variable name is present)
     969    if (
     970        ((StrnLenS (LocalVariableLockPolicyVariableName, RequiredVariableLockPolicyVariableNameBufferSize) + 1) * sizeof (CHAR16)) !=
     971        RequiredVariableLockPolicyVariableNameBufferSize)
     972    {
     973      ASSERT_EFI_ERROR (EFI_BAD_BUFFER_SIZE);
     974      return EFI_BAD_BUFFER_SIZE;
     975    }
     976
     977    Status =  StrnCpyS (
     978                VariableLockPolicyVariableName,
     979                LocalVariablePolicyLockVariableNameBufferSize / sizeof (CHAR16),
     980                LocalVariableLockPolicyVariableName,
     981                RequiredVariableLockPolicyVariableNameBufferSize / sizeof (CHAR16)
     982                );
     983    ASSERT_EFI_ERROR (Status);
     984
     985    return Status;
     986  }
     987
     988  return EFI_NOT_FOUND;
     989}
     990
     991/**
    688992  This API function returns whether or not the policy engine is
    689993  currently being enforced.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Library/VariablePolicyLib/VariablePolicyLib.inf

    r89983 r105670  
    3333
    3434[LibraryClasses]
     35  BaseLib
    3536  DebugLib
    3637  BaseMemoryLib
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/MdeModulePkg.ci.yaml

    r99404 r105670  
    88##
    99{
     10    "PrEval": {
     11        "DscPath": "MdeModulePkg.dsc",
     12    },
    1013    ## options defined .pytool/Plugin/LicenseCheck
    1114    "LicenseCheck": {
     
    5154            "MdePkg/MdePkg.dec",
    5255            "MdeModulePkg/MdeModulePkg.dec",
    53             "StandaloneMmPkg/StandaloneMmPkg.dec",
    54             "ArmPkg/ArmPkg.dec"  # this should be fixed by promoting an abstraction
     56            "StandaloneMmPkg/StandaloneMmPkg.dec"
    5557        ],
    5658        # For host based unit tests
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/MdeModulePkg.dec

    r101291 r105670  
    1010# Copyright (c) 2017, AMD Incorporated. All rights reserved.<BR>
    1111# Copyright (c) Microsoft Corporation.<BR>
    12 # Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
     12# Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved.<BR>
    1313# SPDX-License-Identifier: BSD-2-Clause-Patent
    1414#
     
    164164  #
    165165  VariableFlashInfoLib|Include/Library/VariableFlashInfoLib.h
     166
     167  ##  @libraryclass   Memory Attribute Table support logic for tracking and reporting
     168  #                   runtime images
     169  #
     170  ImagePropertiesRecordLib|Include/Library/ImagePropertiesRecordLib.h
     171
     172  ##  @libraryclass   Platform SPI Host Controller library which provides low-level
     173  #                   control over the SPI hardware
     174  #
     175  SpiHcPlatformLib|Include/Library/SpiHcPlatformLib.h
    166176
    167177[Guids]
     
    417427
    418428  ## Include/Guid/MigratedFvInfo.h
    419   gEdkiiMigratedFvInfoGuid = { 0xc1ab12f7, 0x74aa, 0x408d, { 0xa2, 0xf4, 0xc6, 0xce, 0xfd, 0x17, 0x98, 0x71 } }
     429  gEdkiiMigrationInfoGuid   = { 0xb4b140a5, 0x72f6, 0x4c21, { 0x93, 0xe4, 0xac, 0xc4, 0xec, 0xcb, 0x23, 0x23 } }
     430  gEdkiiMigratedFvInfoGuid  = { 0xc1ab12f7, 0x74aa, 0x408d, { 0xa2, 0xf4, 0xc6, 0xce, 0xfd, 0x17, 0x98, 0x71 } }
     431
     432  ## Include/Guid/RngAlgorithm.h
     433  gEdkiiRngAlgorithmUnSafe = { 0x869f728c, 0x409d, 0x4ab4, {0xac, 0x03, 0x71, 0xd3, 0x09, 0xc1, 0xb3, 0xf4 }}
    420434
    421435  #
     
    445459  ## GUID used for Boot Discovery Policy FormSet guid and related variables.
    446460  gBootDiscoveryPolicyMgrFormsetGuid = { 0x5b6f7107, 0xbb3c, 0x4660, { 0x92, 0xcd, 0x54, 0x26, 0x90, 0x28, 0x0b, 0xbd } }
     461
     462  #
     463  # SPI NOR flash JEDEC Serial Flash Discoverable Parameters (SFDP) driver GUID
     464  #
     465  gEdk2JedecSfdpSpiDxeDriverGuid  = { 0xBE71701E, 0xB63C, 0x4574, { 0x9C, 0x5C, 0x36, 0x29, 0xE8, 0xEA, 0xC4, 0x14 }}
     466  gEdk2JedecSfdpSpiSmmDriverGuid  = { 0x95A1E915, 0x195C, 0x477C, { 0x92, 0x6F, 0x7E, 0x24, 0x67, 0xC1, 0xB3, 0x1F }}
    447467
    448468[Ppis]
     
    10181038  # free pages for all of them. The page allocation for the type related to
    10191039  # cleared bits keeps the same as ususal.
     1040  #
     1041  # The heap guard system only supports guarding EfiRuntimeServicesCode, EfiRuntimeServicesData,
     1042  # EfiReservedMemoryType, and EfiACPIMemoryNVS memory types for systems that have
     1043  # RUNTIME_PAGE_ALLOCATION_GRANULARITY == EFI_PAGE_SIZE. This is to preserve alignment requirements
     1044  # without extending the page guard size to very large granularities.
    10201045  #
    10211046  # This PCD is only valid if BIT0 and/or BIT2 are set in PcdHeapGuardPropertyMask.
     
    10501075  # type related to cleared bits keeps the same as ususal.
    10511076  #
     1077  # The heap guard system only supports guarding EfiRuntimeServicesCode, EfiRuntimeServicesData,
     1078  # EfiReservedMemoryType, and EfiACPIMemoryNVS memory types for systems that have
     1079  # RUNTIME_PAGE_ALLOCATION_GRANULARITY == EFI_PAGE_SIZE. This is to preserve alignment requirements
     1080  # without extending the page guard size to very large granularities.
     1081  #
    10521082  # This PCD is only valid if BIT1 and/or BIT3 are set in PcdHeapGuardPropertyMask.
    10531083  #
     
    11221152  # @Prompt Output MMIO address of Trace Hub message.
    11231153  gEfiMdeModulePkgTokenSpaceGuid.PcdTraceHubDebugMmioAddress|0|UINT64|0x30001058
     1154
     1155  ## Indicates if images with large load address (>0x100000) should attempted to load at specified location.
     1156  #  If enabled, attempt to allocate at specfied location will be attempted with a fall back to any address.
     1157  #   TRUE  - UEFI will attempt to load at specified location.<BR>
     1158  #   FALSE - UEFI will load at any address<BR>
     1159  # @Prompt Enable large address image loading.
     1160  gEfiMdeModulePkgTokenSpaceGuid.PcdImageLargeAddressLoad|TRUE|BOOLEAN|0x30001059
     1161
     1162  ## Indicates time delay for XHCI registers access after it issues HCRST.
     1163  # Default is 2000, it represent delay is 2 ms.
     1164  # @Prompt Delay access XHCI register after it issues HCRST (us)
     1165  gEfiMdeModulePkgTokenSpaceGuid.PcdDelayXhciHCReset|2000|UINT16|0x30001060
    11241166
    11251167[PcdsFixedAtBuild, PcdsPatchableInModule]
     
    15081550  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiExposedTableVersions|0x3E|UINT32|0x0001004c
    15091551
     1552  ## Indicates whether ACPI Reclaim memory is not available
     1553  # Default is FALSE that means ACPI Reclaim memory is available
     1554  # If it is set to TRUE that means ACPI Reclaim memory is not available
     1555  # For example ACPI Table protocol will use ACPI NVS memory instead of ACPI Reclaim memory
     1556  # @Prompt ACPI Reclaim memory is not available.
     1557  gEfiMdeModulePkgTokenSpaceGuid.PcdNoACPIReclaimMemory|FALSE|BOOLEAN|0x0001008b
     1558
    15101559  ## This PCD defines the MAX repair count.
    15111560  #  The default value is 0 that means infinite.
     
    16121661  # @Prompt The value of Retry Count,  Default value is 5.
    16131662  gEfiMdeModulePkgTokenSpaceGuid.PcdAhciCommandRetryCount|5|UINT32|0x00000032
     1663
     1664  ## SPI NOR Flash operation retry counts
     1665  #  0x00000000:  No retry
     1666  #  0xFFFFFFFF:  Maximum retry value
     1667  #
     1668  # @Prompt SPI NOR Flash Operation Retry Value
     1669  gEfiMdeModulePkgTokenSpaceGuid.PcdSpiNorFlashOperationRetryCount|0x00000003|UINT32|0x00000033
     1670
     1671  ## SPI NOR Flash operation retry counts for the fixed timeout value
     1672  #  0x00000000:  No retry
     1673  #  0xFFFFFFFF:  Maximum retry value
     1674  #
     1675  # @Prompt SPI NOR Flash Operation Retry Value for the Fixed Timeout Value
     1676  gEfiMdeModulePkgTokenSpaceGuid.PcdSpiNorFlashFixedTimeoutRetryCount|0x0000FFFF|UINT32|0x00000034
     1677
     1678  ## SPI NOR Flash operation delay in microseconds
     1679  #  Deafult is set to 0x00000010 microseconds
     1680  #
     1681  # @Prompt SPI NOR Flash Operation Delay in Microseconds (16 us)
     1682  gEfiMdeModulePkgTokenSpaceGuid.PcdSpiNorFlashOperationDelayMicroseconds|0x00000010|UINT32|0x00000035
    16141683
    16151684[PcdsPatchableInModule, PcdsDynamic, PcdsDynamicEx]
     
    21142183  gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision|0|UINT32|0x00010077
    21152184
     2185  ## Specify whether to enable the state of SPDM device authentication and measurement.<BR><BR>
     2186  #  0: Platform Firmware not supports SPDM device authentication and measurement.
     2187  #  1: Platform Firmware supports SPDM device authentication and measurement.
     2188  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableSpdmDeviceAuthentication|0|UINT8|0x00010033
     2189
    21162190  ## Indicates if StatusCode is reported via Serial port.<BR><BR>
    21172191  #   TRUE  - Reports StatusCode via Serial port.<BR>
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/MdeModulePkg.dsc

    r101291 r105670  
    55# Copyright (c) 2007 - 2021, Intel Corporation. All rights reserved.<BR>
    66# Copyright (c) Microsoft Corporation.
    7 # Copyright (C) 2023 Advanced Micro Devices, Inc. All rights reserved.<BR>
     7# Copyright (C) 2024 Advanced Micro Devices, Inc. All rights reserved.<BR>
    88#
    99#    SPDX-License-Identifier: BSD-2-Clause-Patent
     
    9797  FileExplorerLib|MdeModulePkg/Library/FileExplorerLib/FileExplorerLib.inf
    9898  NonDiscoverableDeviceRegistrationLib|MdeModulePkg/Library/NonDiscoverableDeviceRegistrationLib/NonDiscoverableDeviceRegistrationLib.inf
     99  ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
    99100
    100101  FmpAuthenticationLib|MdeModulePkg/Library/FmpAuthenticationLibNull/FmpAuthenticationLibNull.inf
     
    107108  VariableFlashInfoLib|MdeModulePkg/Library/BaseVariableFlashInfoLib/BaseVariableFlashInfoLib.inf
    108109  IpmiCommandLib|MdeModulePkg/Library/BaseIpmiCommandLibNull/BaseIpmiCommandLibNull.inf
     110  SpiHcPlatformLib|MdeModulePkg/Library/BaseSpiHcPlatformLibNull/BaseSpiHcPlatformLibNull.inf
    109111
    110112[LibraryClasses.EBC.PEIM]
     
    179181
    180182[LibraryClasses.ARM, LibraryClasses.AARCH64]
    181   ArmLib|ArmPkg/Library/ArmLib/ArmBaseLib.inf
    182   ArmMmuLib|ArmPkg/Library/ArmMmuLib/ArmMmuBaseLib.inf
    183183  LockBoxLib|MdeModulePkg/Library/LockBoxNullLib/LockBoxNullLib.inf
    184184
     
    238238  MdeModulePkg/Library/BaseMemoryAllocationLibNull/BaseMemoryAllocationLibNull.inf
    239239  MdeModulePkg/Library/VariablePolicyHelperLib/VariablePolicyHelperLib.inf
     240  MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
    240241
    241242  MdeModulePkg/Bus/Pci/PciHostBridgeDxe/PciHostBridgeDxe.inf
     
    286287  MdeModulePkg/Bus/Isa/Ps2MouseDxe/Ps2MouseDxe.inf
    287288  MdeModulePkg/Bus/Pci/NonDiscoverablePciDeviceDxe/NonDiscoverablePciDeviceDxe.inf
     289  MdeModulePkg/Bus/Spi/SpiNorFlashJedecSfdp/SpiNorFlashJedecSfdpDxe.inf
     290  MdeModulePkg/Bus/Spi/SpiNorFlashJedecSfdp/SpiNorFlashJedecSfdpSmm.inf
     291  MdeModulePkg/Bus/Spi/SpiBus/SpiBusDxe.inf
     292  MdeModulePkg/Bus/Spi/SpiBus/SpiBusSmm.inf
     293  MdeModulePkg/Bus/Spi/SpiHc/SpiHcDxe.inf
     294  MdeModulePkg/Bus/Spi/SpiHc/SpiHcSmm.inf
    288295
    289296  MdeModulePkg/Core/DxeIplPeim/DxeIpl.inf
     
    346353  MdeModulePkg/Library/DisplayUpdateProgressLibGraphics/DisplayUpdateProgressLibGraphics.inf
    347354  MdeModulePkg/Library/DisplayUpdateProgressLibText/DisplayUpdateProgressLibText.inf
     355  MdeModulePkg/Library/BaseRngLibTimerLib/BaseRngLibTimerLib.inf
    348356
    349357  MdeModulePkg/Universal/BdsDxe/BdsDxe.inf
     
    524532  MdeModulePkg/Library/TraceHubDebugSysTLib/PeiTraceHubDebugSysTLib.inf
    525533  MdeModulePkg/Library/TraceHubDebugSysTLib/DxeSmmTraceHubDebugSysTLib.inf
     534  MdeModulePkg/Library/BaseSpiHcPlatformLibNull/BaseSpiHcPlatformLibNull.inf
    526535
    527536[Components.X64]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/MdeModulePkg.uni

    r101291 r105670  
    956956                                                                                             "BIT 5 - EFI_ACPI_TABLE_VERSION_5_0.<BR>"
    957957
     958#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdNoACPIReclaimMemory_PROMPT  #language en-US "ACPI Reclaim memory is not available."
     959
     960#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdNoACPIReclaimMemory_HELP  #language en-US "Indicates whether ACPI Reclaim memory is not available\n"
     961                                                                                     "Default is FALSE that means ACPI Reclaim memory is available\n"
     962                                                                                     "If it is set to TRUE that means ACPI Reclaim memory is not available\n"
     963                                                                                     "For example ACPI Table protocol will use ACPI NVS memory instead of ACPI Reclaim memory"
     964
     965
    958966#string STR_gEfiMdeModulePkgTokenSpaceGuid_PcdHiiOsRuntimeSupport_PROMPT  #language en-US "Enable export HII data and configuration to be used in OS runtime."
    959967
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Test/MdeModulePkgHostTest.dsc

    r101291 r105670  
    5555  }
    5656
     57  MdeModulePkg/Library/ImagePropertiesRecordLib/UnitTest/ImagePropertiesRecordLibUnitTestHost.inf {
     58    <LibraryClasses>
     59      ImagePropertiesRecordLib|MdeModulePkg/Library/ImagePropertiesRecordLib/ImagePropertiesRecordLib.inf
     60      PeCoffGetEntryPointLib|MdePkg/Library/BasePeCoffGetEntryPointLib/BasePeCoffGetEntryPointLib.inf
     61  }
     62
    5763  #
    5864  # Build HOST_APPLICATION Libraries
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Test/Mock/Include/GoogleTest/Library/MockPciHostBridgeLib.h

    r101291 r105670  
    1212#include <Library/FunctionMockLib.h>
    1313extern "C" {
    14 #include <Uefi.h>
    15 #include <Library/PciHostBridgeLib.h>
     14  #include <Uefi.h>
     15  #include <Library/PciHostBridgeLib.h>
    1616}
    1717
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Test/Mock/Library/GoogleTest/MockPciHostBridgeLib/MockPciHostBridgeLib.cpp

    r101291 r105670  
    88#include <GoogleTest/Library/MockPciHostBridgeLib.h>
    99
    10 MOCK_INTERFACE_DEFINITION(MockPciHostBridgeLib);
     10MOCK_INTERFACE_DEFINITION (MockPciHostBridgeLib);
    1111
    12 MOCK_FUNCTION_DEFINITION(MockPciHostBridgeLib, PciHostBridgeGetRootBridges, 1, EFIAPI);
    13 MOCK_FUNCTION_DEFINITION(MockPciHostBridgeLib, PciHostBridgeFreeRootBridges, 2, EFIAPI);
    14 MOCK_FUNCTION_DEFINITION(MockPciHostBridgeLib, PciHostBridgeResourceConflict, 2, EFIAPI);
     12MOCK_FUNCTION_DEFINITION (MockPciHostBridgeLib, PciHostBridgeGetRootBridges, 1, EFIAPI);
     13MOCK_FUNCTION_DEFINITION (MockPciHostBridgeLib, PciHostBridgeFreeRootBridges, 2, EFIAPI);
     14MOCK_FUNCTION_DEFINITION (MockPciHostBridgeLib, PciHostBridgeResourceConflict, 2, EFIAPI);
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableDxe.inf

    r99404 r105670  
    6969  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiDefaultCreatorRevision  ## CONSUMES
    7070  gEfiMdeModulePkgTokenSpaceGuid.PcdAcpiExposedTableVersions    ## CONSUMES
     71  gEfiMdeModulePkgTokenSpaceGuid.PcdNoACPIReclaimMemory         ## CONSUMES
    7172
    7273[Protocols]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Acpi/AcpiTableDxe/AcpiTableProtocol.c

    r99404 r105670  
    341341  EFI_STATUS               Status;
    342342  UINT64                   CurrentData;
     343  EFI_MEMORY_TYPE          AcpiAllocateMemoryType;
    343344
    344345  CopyMem (&TempPrivateData, AcpiTableInstance, sizeof (EFI_ACPI_TABLE_INSTANCE));
     
    360361  }
    361362
     363  if (PcdGetBool (PcdNoACPIReclaimMemory)) {
     364    AcpiAllocateMemoryType = EfiACPIMemoryNVS;
     365  } else {
     366    AcpiAllocateMemoryType = EfiACPIReclaimMemory;
     367  }
     368
    362369  if (mAcpiTableAllocType != AllocateAnyPages) {
    363370    //
     
    373380    Status      = gBS->AllocatePages (
    374381                         mAcpiTableAllocType,
    375                          EfiACPIReclaimMemory,
     382                         AcpiAllocateMemoryType,
    376383                         EFI_SIZE_TO_PAGES (TotalSize),
    377384                         &PageAddress
     
    379386  } else {
    380387    Status = gBS->AllocatePool (
    381                     EfiACPIReclaimMemory,
     388                    AcpiAllocateMemoryType,
    382389                    TotalSize,
    383390                    (VOID **)&Pointer
     
    513520  UINT64                Buffer64;
    514521  BOOLEAN               AddToRsdt;
     522  EFI_MEMORY_TYPE       AcpiAllocateMemoryType;
    515523
    516524  //
     
    550558  CurrentTableList->TableSize      = CurrentTableSize;
    551559  CurrentTableList->PoolAllocation = FALSE;
     560
     561  if (PcdGetBool (PcdNoACPIReclaimMemory)) {
     562    AcpiAllocateMemoryType = EfiACPIMemoryNVS;
     563  } else {
     564    AcpiAllocateMemoryType = EfiACPIReclaimMemory;
     565  }
    552566
    553567  //
     
    586600    //
    587601    Status = gBS->AllocatePool (
    588                     EfiACPIReclaimMemory,
     602                    AcpiAllocateMemoryType,
    589603                    CurrentTableList->TableSize,
    590604                    (VOID **)&CurrentTableList->Table
     
    597611    Status = gBS->AllocatePages (
    598612                    mAcpiTableAllocType,
    599                     EfiACPIReclaimMemory,
     613                    AcpiAllocateMemoryType,
    600614                    EFI_SIZE_TO_PAGES (CurrentTableList->TableSize),
    601615                    &AllocPhysAddress
     
    18931907        }
    18941908
    1895         if (((EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)ChildTable)->Dsdt != 0) {
     1909        //
     1910        // First check if xDSDT is available, as that is preferred as per
     1911        // ACPI Spec 6.5+ Table 5-9 X_DSDT definition
     1912        //
     1913        if (((EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)ChildTable)->XDsdt != 0) {
     1914          TableToInstall = (VOID *)(UINTN)((EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)ChildTable)->XDsdt;
     1915        } else if (((EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)ChildTable)->Dsdt != 0) {
    18961916          TableToInstall = (VOID *)(UINTN)((EFI_ACPI_3_0_FIXED_ACPI_DESCRIPTION_TABLE *)ChildTable)->Dsdt;
    1897           Status         = AddTableToList (AcpiTableInstance, TableToInstall, TRUE, Version, TRUE, &TableKey);
    1898           if (EFI_ERROR (Status)) {
    1899             DEBUG ((DEBUG_ERROR, "InstallAcpiTableFromHob: Fail to add ACPI table DSDT\n"));
    1900             ASSERT_EFI_ERROR (Status);
    1901             break;
    1902           }
     1917        } else {
     1918          DEBUG ((DEBUG_ERROR, "DSDT table not found\n"));
     1919          continue;
     1920        }
     1921
     1922        Status = AddTableToList (AcpiTableInstance, TableToInstall, TRUE, Version, TRUE, &TableKey);
     1923        if (EFI_ERROR (Status)) {
     1924          DEBUG ((DEBUG_ERROR, "InstallAcpiTableFromHob: Fail to add ACPI table DSDT\n"));
     1925          ASSERT_EFI_ERROR (Status);
     1926          break;
    19031927        }
    19041928      }
     
    19451969  UINT8                 *Pointer;
    19461970  EFI_PHYSICAL_ADDRESS  PageAddress;
     1971  EFI_MEMORY_TYPE       AcpiAllocateMemoryType;
    19471972
    19481973  //
     
    19792004  }
    19802005
     2006  if (PcdGetBool (PcdNoACPIReclaimMemory)) {
     2007    AcpiAllocateMemoryType = EfiACPIMemoryNVS;
     2008  } else {
     2009    AcpiAllocateMemoryType = EfiACPIReclaimMemory;
     2010  }
     2011
    19812012  if (mAcpiTableAllocType != AllocateAnyPages) {
    19822013    PageAddress = 0xFFFFFFFF;
    19832014    Status      = gBS->AllocatePages (
    19842015                         mAcpiTableAllocType,
    1985                          EfiACPIReclaimMemory,
     2016                         AcpiAllocateMemoryType,
    19862017                         EFI_SIZE_TO_PAGES (RsdpTableSize),
    19872018                         &PageAddress
     
    19892020  } else {
    19902021    Status = gBS->AllocatePool (
    1991                     EfiACPIReclaimMemory,
     2022                    AcpiAllocateMemoryType,
    19922023                    RsdpTableSize,
    19932024                    (VOID **)&Pointer
     
    20382069    Status      = gBS->AllocatePages (
    20392070                         mAcpiTableAllocType,
    2040                          EfiACPIReclaimMemory,
     2071                         AcpiAllocateMemoryType,
    20412072                         EFI_SIZE_TO_PAGES (TotalSize),
    20422073                         &PageAddress
     
    20442075  } else {
    20452076    Status = gBS->AllocatePool (
    2046                     EfiACPIReclaimMemory,
     2077                    AcpiAllocateMemoryType,
    20472078                    TotalSize,
    20482079                    (VOID **)&Pointer
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Acpi/FirmwarePerformanceDataTablePei/FirmwarePerformancePei.c

    r99404 r105670  
    113113  S3ResumeTotal = MultU64x32 (AcpiS3ResumeRecord->AverageResume, AcpiS3ResumeRecord->ResumeCount);
    114114  AcpiS3ResumeRecord->ResumeCount++;
    115   AcpiS3ResumeRecord->AverageResume = DivU64x32 (S3ResumeTotal + AcpiS3ResumeRecord->FullResume, AcpiS3ResumeRecord->ResumeCount);
    116 
    117   DEBUG ((DEBUG_INFO, "FPDT: S3 Resume Performance - ResumeCount   = %d\n", AcpiS3ResumeRecord->ResumeCount));
    118   DEBUG ((DEBUG_INFO, "FPDT: S3 Resume Performance - FullResume    = %ld\n", AcpiS3ResumeRecord->FullResume));
    119   DEBUG ((DEBUG_INFO, "FPDT: S3 Resume Performance - AverageResume = %ld\n", AcpiS3ResumeRecord->AverageResume));
     115  if (AcpiS3ResumeRecord->ResumeCount > 0) {
     116    AcpiS3ResumeRecord->AverageResume = DivU64x32 (S3ResumeTotal + AcpiS3ResumeRecord->FullResume, AcpiS3ResumeRecord->ResumeCount);
     117    DEBUG ((DEBUG_INFO, "\nFPDT: S3 Resume Performance - AverageResume = 0x%x\n", AcpiS3ResumeRecord->AverageResume));
     118  } else {
     119    DEBUG ((DEBUG_ERROR, "\nFPDT: S3 ResumeCount reaches the MAX_UINT32 value. S3 ResumeCount record reset to Zero."));
     120  }
     121
     122  DEBUG ((DEBUG_INFO, "FPDT: S3 Resume Performance - ResumeCount   = 0x%x\n", AcpiS3ResumeRecord->ResumeCount));
     123  DEBUG ((DEBUG_INFO, "FPDT: S3 Resume Performance - FullResume    = 0x%x\n", AcpiS3ResumeRecord->FullResume));
    120124
    121125  //
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/CapsuleRuntimeDxe/CapsuleService.c

    r99404 r105670  
    5454  @retval EFI_OUT_OF_RESOURCES  When ExitBootServices() has not been previously called then this error indicates
    5555                                the capsule is compatible with this platform but there are insufficient resources to process.
     56  @retval EFI_UNSUPPORTED       This call is not supported by this platform at the time the call is made.
     57                                The platform should describe this runtime service as unsupported at runtime
     58                                via an EFI_RT_PROPERTIES_TABLE configuration table.
    5659
    5760**/
     
    248251  @retval EFI_INVALID_PARAMETER MaximumCapsuleSize is NULL, or ResetTyep is NULL,
    249252                                Or CapsuleCount is Zero, or CapsuleImage is not valid.
     253  @retval EFI_OUT_OF_RESOURCES  When ExitBootServices() has been previously called this error indicates
     254                                the capsule is compatible with this platform but is not capable of
     255                                being submitted or processed in runtime.
     256                                The caller may resubmit the capsule prior to ExitBootServices().
     257  @retval EFI_OUT_OF_RESOURCES  When ExitBootServices() has not been previously called then this error
     258                                indicates the capsule is compatible with this platform but there are
     259                                insufficient resources to process.
     260  @retval EFI_UNSUPPORTED       This call is not supported by this platform at the time the call is made.
     261                                The platform should describe this runtime service as unsupported at runtime
     262                                via an EFI_RT_PROPERTIES_TABLE configuration table.
    250263
    251264**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitter.c

    r99404 r105670  
    35523552  @retval EFI_DEVICE_ERROR         The keydtroke information was not returned due
    35533553                                   to hardware errors.
     3554  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     3555                                   keystroke data.
    35543556
    35553557**/
     
    36243626  @retval EFI_DEVICE_ERROR         The keydtroke information was not returned due
    36253627                                   to hardware errors.
     3628  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     3629                                   keystroke data.
    36263630
    36273631**/
     
    38063810                                   to hardware errors.
    38073811  @retval EFI_INVALID_PARAMETER    KeyData is NULL.
     3812  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     3813                                   keystroke data.
    38083814
    38093815**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Console/ConSplitterDxe/ConSplitter.h

    r99404 r105670  
    12661266  @retval EFI_DEVICE_ERROR         The keydtroke information was not returned due
    12671267                                   to hardware errors.
     1268  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     1269                                   keystroke data.
    12681270
    12691271**/
     
    13431345                                   to hardware errors.
    13441346  @retval EFI_INVALID_PARAMETER    KeyData is NULL.
     1347  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     1348                                   keystroke data.
    13451349
    13461350**/
     
    14541458  @retval EFI_DEVICE_ERROR         The keydtroke information was not returned due
    14551459                                   to hardware errors.
     1460  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     1461                                   keystroke data.
    14561462
    14571463**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Console/TerminalDxe/Terminal.h

    r99404 r105670  
    224224  @retval EFI_NOT_READY       There is no keystroke data available.
    225225  @retval EFI_DEVICE_ERROR    The dependent serial device encounters error.
     226  @retval EFI_UNSUPPORTED     The device does not support the ability to read
     227                              keystroke data.
    226228
    227229**/
     
    304306                                   to hardware errors.
    305307  @retval EFI_INVALID_PARAMETER    KeyData is NULL.
     308  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     309                                   keystroke data.
    306310
    307311**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Console/TerminalDxe/TerminalConIn.c

    r99404 r105670  
    110110  @retval EFI_NOT_READY       There is no keystroke data available.
    111111  @retval EFI_DEVICE_ERROR    The dependent serial device encounters error.
     112  @retval EFI_UNSUPPORTED     The device does not support the ability to read
     113                              keystroke data.
    112114
    113115**/
     
    238240                                   to hardware errors.
    239241  @retval EFI_INVALID_PARAMETER    KeyData is NULL.
     242  @retval EFI_UNSUPPORTED          The device does not support the ability to read
     243                                   keystroke data.
    240244
    241245**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/DriverSampleDxe/DriverSample.c

    r99404 r105670  
    859859  @retval EFI_NOT_FOUND          Routing data doesn't match any storage in this
    860860                                 driver.
     861  @retval EFI_DEVICE_ERROR       If value is 44, return error for testing.
    861862
    862863**/
     
    10641065  if (EFI_ERROR (Status)) {
    10651066    return Status;
     1067  }
     1068
     1069  if (PrivateData->Configuration.QuestionApply == 44) {
     1070    // Return error for verify the error handling of caller.
     1071    return EFI_DEVICE_ERROR;
    10661072  }
    10671073
     
    16001606          break;
    16011607
     1608        case 0x1253:
     1609          //
     1610          // User change the value of "Question apply test".
     1611          //
     1612          *ActionRequest = EFI_BROWSER_ACTION_REQUEST_QUESTION_APPLY;
     1613          break;
     1614
    16021615        case 0x1231:
    16031616          //
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/DriverSampleDxe/NVDataStruc.h

    r99404 r105670  
    9696  UINT8                QuestionXUefiKeywordRestStyle;
    9797  UINT8                QuestionNonXUefiKeywordRestStyle;
     98  UINT8                QuestionApply;
    9899} DRIVER_SAMPLE_CONFIGURATION;
    99100
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/DriverSampleDxe/Vfr.vfr

    r89983 r105670  
    514514    endnumeric;
    515515
     516    numeric varid   = MyIfrNVData.QuestionApply,
     517            questionid = 0x1253,
     518            prompt  = STRING_TOKEN(STR_QUESTION_APPLY_TEST_PROMPT),
     519            help    = STRING_TOKEN(STR_QUESTION_APPLY_TEST_HELP),
     520            flags   = INTERACTIVE,
     521            minimum = 0,
     522            maximum = 255,
     523            default = 19,
     524    endnumeric;
     525
    516526    text
    517527      help  = STRING_TOKEN(STR_POPUP_TEST_HELP),
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/DriverSampleDxe/VfrStrings.uni

    r89983 r105670  
    270270#string STR_SUBMITTED_CALLBACK_TEST_HELP             #language en-US "Change the value and press F10 to submit will pop up a dialogue to show SUBMITTED Callback has been triggered"
    271271                                                     #language fr-FR "Change the value and press F10 to submit will pop up a dialogue to show SUBMITTED Callback has been triggered"
     272#string STR_QUESTION_APPLY_TEST_PROMPT               #language en-US "Question apply test"
     273                                                     #language fr-FR "Question apply test"
     274#string STR_QUESTION_APPLY_TEST_HELP                 #language en-US "Change the value and it will be applied automaticlly. If set to 44, then return failed."
     275                                                     #language fr-FR "Change the value and it will be applied automaticlly. If set to 44, then return failed."
    272276#string STR_POPUP_TEST_PROMPT                        #language en-US "Select it to invoke Hii Popup Protocol"
    273277                                                     #language fr-FR "Select it to invoke Hii Popup Protocol"
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/HiiDatabaseDxe/ConfigKeywordHandler.c

    r99404 r105670  
    19881988                   );
    19891989  if (BestLanguage == NULL) {
    1990     BestLanguage = AllocateCopyPool (AsciiStrLen ("en-US"), "en-US");
     1990    BestLanguage = AllocateCopyPool (sizeof ("en-US"), "en-US");
    19911991    ASSERT (BestLanguage != NULL);
    19921992  }
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/MonotonicCounterRuntimeDxe/MonotonicCounter.c

    r99404 r105670  
    126126  @retval EFI_OUT_OF_RESOURCES  If variable service reports that not enough storage
    127127                                is available to hold the variable and its data.
     128  @retval EFI_UNSUPPORTED       This call is not supported by this platform at the time the call is made.
     129                                The platform should describe this runtime service as unsupported at runtime
     130                                via an EFI_RT_PROPERTIES_TABLE configuration table.
    128131
    129132**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/RegularExpressionDxe/RegularExpressionDxe.inf

    r85718 r105670  
    103103  # Oniguruma: old style declaration in st.c
    104104  MSFT:*_*_*_CC_FLAGS = /wd4131
     105  GCC:*_*_*_CC_FLAGS = -Wno-deprecated-non-prototype
    105106
    106107  # Oniguruma: 'type cast' : truncation from 'OnigUChar *' to 'unsigned int'
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/ResetSystemRuntimeDxe/ResetSystem.c

    r99404 r105670  
    253253    ));
    254254
     255  if ((ResetData != NULL) && (DataSize != 0)) {
     256    DEBUG ((
     257      DEBUG_INFO,
     258      "DXE ResetSystem2: ResetData: %s\n",
     259      ResetData
     260      ));
     261  }
     262
    255263  if (mResetNotifyDepth <= MAX_RESET_NOTIFY_DEPTH) {
    256264    if (!EfiAtRuntime ()) {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/SetupBrowserDxe/Presentation.c

    r99404 r105670  
    21442144            case EFI_BROWSER_ACTION_REQUEST_RECONNECT:
    21452145              gCallbackReconnect = TRUE;
     2146              break;
     2147
     2148            case EFI_BROWSER_ACTION_REQUEST_QUESTION_APPLY:
     2149              Status = SetQuestionValue (
     2150                         gCurrentSelection->FormSet,
     2151                         gCurrentSelection->Form,
     2152                         Statement,
     2153                         GetSetValueWithHiiDriver
     2154                         );
    21462155              break;
    21472156
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/SmbiosDxe/SmbiosDxe.c

    r101291 r105670  
    10731073    EntryPointStructureData.MajorVersion      = mPrivateData.Smbios.MajorVersion;
    10741074    EntryPointStructureData.MinorVersion      = mPrivateData.Smbios.MinorVersion;
    1075     EntryPointStructureData.SmbiosBcdRevision = (UINT8)((PcdGet16 (PcdSmbiosVersion) >> 4) & 0xf0) | (UINT8)(PcdGet16 (PcdSmbiosVersion) & 0x0f);
    1076     PhysicalAddress                           = 0xffffffff;
    1077     Status                                    = gBS->AllocatePages (
    1078                                                        AllocateMaxAddress,
    1079                                                        EfiRuntimeServicesData,
    1080                                                        EFI_SIZE_TO_PAGES (sizeof (SMBIOS_TABLE_ENTRY_POINT)),
    1081                                                        &PhysicalAddress
    1082                                                        );
     1075    EntryPointStructureData.SmbiosBcdRevision = 0;
     1076    if ((mPrivateData.Smbios.MajorVersion <= 9) && (mPrivateData.Smbios.MinorVersion <= 9)) {
     1077      EntryPointStructureData.SmbiosBcdRevision = ((mPrivateData.Smbios.MajorVersion & 0x0f) << 4) | (mPrivateData.Smbios.MinorVersion & 0x0f);
     1078    }
     1079
     1080    PhysicalAddress = 0xffffffff;
     1081    Status          = gBS->AllocatePages (
     1082                             AllocateMaxAddress,
     1083                             EfiRuntimeServicesData,
     1084                             EFI_SIZE_TO_PAGES (sizeof (SMBIOS_TABLE_ENTRY_POINT)),
     1085                             &PhysicalAddress
     1086                             );
    10831087    if (EFI_ERROR (Status)) {
    10841088      DEBUG ((DEBUG_ERROR, "SmbiosCreateTable () could not allocate EntryPointStructure < 4GB\n"));
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/Measurement.c

    r99404 r105670  
    99#include <PiDxe.h>
    1010#include <Guid/ImageAuthentication.h>
     11#include <Guid/DeviceAuthentication.h>
    1112#include <IndustryStandard/UefiTcgPlatform.h>
    1213
     
    2728
    2829VARIABLE_TYPE  mVariableType[] = {
    29   { EFI_SECURE_BOOT_MODE_NAME,    &gEfiGlobalVariableGuid        },
    30   { EFI_PLATFORM_KEY_NAME,        &gEfiGlobalVariableGuid        },
    31   { EFI_KEY_EXCHANGE_KEY_NAME,    &gEfiGlobalVariableGuid        },
    32   { EFI_IMAGE_SECURITY_DATABASE,  &gEfiImageSecurityDatabaseGuid },
    33   { EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid },
    34   { EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid },
     30  { EFI_SECURE_BOOT_MODE_NAME,    &gEfiGlobalVariableGuid          },
     31  { EFI_PLATFORM_KEY_NAME,        &gEfiGlobalVariableGuid          },
     32  { EFI_KEY_EXCHANGE_KEY_NAME,    &gEfiGlobalVariableGuid          },
     33  { EFI_IMAGE_SECURITY_DATABASE,  &gEfiImageSecurityDatabaseGuid   },
     34  { EFI_IMAGE_SECURITY_DATABASE1, &gEfiImageSecurityDatabaseGuid   },
     35  { EFI_IMAGE_SECURITY_DATABASE2, &gEfiImageSecurityDatabaseGuid   },
     36  { EFI_DEVICE_SECURITY_DATABASE, &gEfiDeviceSignatureDatabaseGuid },
    3537};
    3638
     
    124126  }
    125127
     128  if (CompareGuid (VendorGuid, &gEfiDeviceSignatureDatabaseGuid)) {
     129    DEBUG ((DEBUG_INFO, "VariableDxe: MeasureVariable (Pcr - %x, EventType - %x, ", PCR_INDEX_FOR_SIGNATURE_DB, (UINTN)EV_EFI_SPDM_DEVICE_POLICY));
     130    DEBUG ((DEBUG_INFO, "VariableName - %s, VendorGuid - %g)\n", VarName, VendorGuid));
     131
     132    Status = TpmMeasureAndLogData (
     133               PCR_INDEX_FOR_SIGNATURE_DB,
     134               EV_EFI_SPDM_DEVICE_POLICY,
     135               VarLog,
     136               VarLogSize,
     137               VarLog,
     138               VarLogSize
     139               );
     140    FreePool (VarLog);
     141    return Status;
     142  }
     143
    126144  DEBUG ((DEBUG_INFO, "VariableDxe: MeasureVariable (Pcr - %x, EventType - %x, ", (UINTN)7, (UINTN)EV_EFI_VARIABLE_DRIVER_CONFIG));
    127145  DEBUG ((DEBUG_INFO, "VariableName - %s, VendorGuid - %g)\n", VarName, VendorGuid));
     
    227245  if (!IsSecureBootPolicyVariable (VariableName, VendorGuid)) {
    228246    return;
     247  }
     248
     249  if (CompareGuid (VendorGuid, &gEfiDeviceSignatureDatabaseGuid)) {
     250    if ((PcdGet32 (PcdTcgPfpMeasurementRevision) < TCG_EfiSpecIDEventStruct_SPEC_ERRATA_TPM2_REV_106) ||
     251        (PcdGet8 (PcdEnableSpdmDeviceAuthentication) == 0))
     252    {
     253      return;
     254    }
    229255  }
    230256
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.c

    r101291 r105670  
    22352235    if (!mVariableModuleGlobal->VariableGlobal.EmuNvMode) {
    22362236      //
    2237       // Four steps
    2238       // 1. Write variable header
    2239       // 2. Set variable state to header valid
    2240       // 3. Write variable data
    2241       // 4. Set variable state to valid
     2237      // Two steps
     2238      // 1. Write variable header and data
     2239      // 2. Set variable state to valid
    22422240      //
    22432241      //
     
    22502248                 Fvb,
    22512249                 mVariableModuleGlobal->NonVolatileLastVariableOffset,
    2252                  (UINT32)GetVariableHeaderSize (AuthFormat),
     2250                 (UINT32)VarSize,
    22532251                 (UINT8 *)NextVariable
    22542252                 );
     
    22602258      //
    22612259      // Step 2:
    2262       //
    2263       NextVariable->State = VAR_HEADER_VALID_ONLY;
    2264       Status              = UpdateVariableStore (
    2265                               &mVariableModuleGlobal->VariableGlobal,
    2266                               FALSE,
    2267                               TRUE,
    2268                               Fvb,
    2269                               mVariableModuleGlobal->NonVolatileLastVariableOffset + OFFSET_OF (VARIABLE_HEADER, State),
    2270                               sizeof (UINT8),
    2271                               &NextVariable->State
    2272                               );
    2273 
    2274       if (EFI_ERROR (Status)) {
    2275         goto Done;
    2276       }
    2277 
    2278       //
    2279       // Step 3:
    2280       //
    2281       Status = UpdateVariableStore (
    2282                  &mVariableModuleGlobal->VariableGlobal,
    2283                  FALSE,
    2284                  TRUE,
    2285                  Fvb,
    2286                  mVariableModuleGlobal->NonVolatileLastVariableOffset + GetVariableHeaderSize (AuthFormat),
    2287                  (UINT32)(VarSize - GetVariableHeaderSize (AuthFormat)),
    2288                  (UINT8 *)NextVariable + GetVariableHeaderSize (AuthFormat)
    2289                  );
    2290 
    2291       if (EFI_ERROR (Status)) {
    2292         goto Done;
    2293       }
    2294 
    2295       //
    2296       // Step 4:
    22972260      //
    22982261      NextVariable->State = VAR_ADDED;
     
    24892452                                    with a zero DataSize in order to determine the size buffer needed.
    24902453
    2491   @return EFI_INVALID_PARAMETER     Invalid parameter.
    2492   @return EFI_SUCCESS               Find the specified variable.
    2493   @return EFI_NOT_FOUND             Not found.
    2494   @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result.
     2454  @retval EFI_SUCCESS               The function completed successfully.
     2455  @retval EFI_NOT_FOUND             The variable was not found.
     2456  @retval EFI_BUFFER_TOO_SMALL      The DataSize is too small for the result.
     2457  @retval EFI_INVALID_PARAMETER     VariableName is NULL.
     2458  @retval EFI_INVALID_PARAMETER     VendorGuid is NULL.
     2459  @retval EFI_INVALID_PARAMETER     DataSize is NULL.
     2460  @retval EFI_INVALID_PARAMETER     The DataSize is not too small and Data is NULL.
     2461  @retval EFI_DEVICE_ERROR          The variable could not be retrieved due to a hardware error.
     2462  @retval EFI_SECURITY_VIOLATION    The variable could not be retrieved due to an authentication failure.
     2463  @retval EFI_UNSUPPORTED           After ExitBootServices() has been called, this return code may be returned
     2464                                    if no variable storage is supported. The platform should describe this
     2465                                    runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     2466                                    configuration table.
    24952467
    24962468**/
     
    26392611  @retval EFI_INVALID_PARAMETER     Null-terminator is not found in the first VariableNameSize bytes of
    26402612                                    the input VariableName buffer.
     2613  @retval EFI_DEVICE_ERROR          The variable could not be retrieved due to a hardware error.
     2614  @retval EFI_UNSUPPORTED           After ExitBootServices() has been called, this return code may be returned
     2615                                    if no variable storage is supported. The platform should describe this
     2616                                    runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     2617                                    configuration table.
    26412618
    26422619**/
     
    28032780  @param Data                             Data pointer.
    28042781
    2805   @return EFI_INVALID_PARAMETER           Invalid parameter.
    2806   @return EFI_SUCCESS                     Set successfully.
    2807   @return EFI_OUT_OF_RESOURCES            Resource not enough to set variable.
    2808   @return EFI_NOT_FOUND                   Not found.
    2809   @return EFI_WRITE_PROTECTED             Variable is read-only.
     2782  @retval EFI_SUCCESS                     The function completed successfully.
     2783  @retval EFI_NOT_FOUND                   The variable was not found.
     2784  @retval EFI_BUFFER_TOO_SMALL            The DataSize is too small for the result.
     2785  @retval EFI_INVALID_PARAMETER           VariableName is NULL.
     2786  @retval EFI_INVALID_PARAMETER           VendorGuid is NULL.
     2787  @retval EFI_INVALID_PARAMETER           DataSize is NULL.
     2788  @retval EFI_INVALID_PARAMETER           The DataSize is not too small and Data is NULL.
     2789  @retval EFI_DEVICE_ERROR                The variable could not be retrieved due to a hardware error.
     2790  @retval EFI_SECURITY_VIOLATION          The variable could not be retrieved due to an authentication failure.
     2791  @retval EFI_UNSUPPORTED                 After ExitBootServices() has been called, this return code may be returned
     2792                                          if no variable storage is supported. The platform should describe this
     2793                                          runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     2794                                          configuration table.
    28102795
    28112796**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/Variable.h

    r99404 r105670  
    447447                                    with a zero DataSize in order to determine the size buffer needed.
    448448
    449   @return EFI_INVALID_PARAMETER     Invalid parameter.
    450   @return EFI_SUCCESS               Find the specified variable.
    451   @return EFI_NOT_FOUND             Not found.
    452   @return EFI_BUFFER_TO_SMALL       DataSize is too small for the result.
     449  @retval EFI_SUCCESS            The function completed successfully.
     450  @retval EFI_NOT_FOUND          The variable was not found.
     451  @retval EFI_BUFFER_TOO_SMALL   The DataSize is too small for the result.
     452  @retval EFI_INVALID_PARAMETER  VariableName is NULL.
     453  @retval EFI_INVALID_PARAMETER  VendorGuid is NULL.
     454  @retval EFI_INVALID_PARAMETER  DataSize is NULL.
     455  @retval EFI_INVALID_PARAMETER  The DataSize is not too small and Data is NULL.
     456  @retval EFI_DEVICE_ERROR       The variable could not be retrieved due to a hardware error.
     457  @retval EFI_SECURITY_VIOLATION The variable could not be retrieved due to an authentication failure.
     458  @retval EFI_UNSUPPORTED        After ExitBootServices() has been called, this return code may be returned
     459                                 if no variable storage is supported. The platform should describe this
     460                                 runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     461                                 configuration table.
    453462
    454463**/
     
    486495  @retval EFI_INVALID_PARAMETER     Null-terminator is not found in the first VariableNameSize bytes of
    487496                                    the input VariableName buffer.
     497  @retval EFI_DEVICE_ERROR          The variable could not be retrieved due to a hardware error.
     498  @retval EFI_UNSUPPORTED           After ExitBootServices() has been called, this return code may be returned
     499                                    if no variable storage is supported. The platform should describe this
     500                                    runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     501                                    configuration table.
    488502
    489503**/
     
    514528  @param Data                             Data pointer.
    515529
    516   @return EFI_INVALID_PARAMETER           Invalid parameter.
    517   @return EFI_SUCCESS                     Set successfully.
    518   @return EFI_OUT_OF_RESOURCES            Resource not enough to set variable.
    519   @return EFI_NOT_FOUND                   Not found.
    520   @return EFI_WRITE_PROTECTED             Variable is read-only.
     530  @retval EFI_SUCCESS                     The function completed successfully.
     531  @retval EFI_NOT_FOUND                   The variable was not found.
     532  @retval EFI_BUFFER_TOO_SMALL            The DataSize is too small for the result.
     533  @retval EFI_INVALID_PARAMETER           VariableName is NULL.
     534  @retval EFI_INVALID_PARAMETER           VendorGuid is NULL.
     535  @retval EFI_INVALID_PARAMETER           DataSize is NULL.
     536  @retval EFI_INVALID_PARAMETER           The DataSize is not too small and Data is NULL.
     537  @retval EFI_DEVICE_ERROR                The variable could not be retrieved due to a hardware error.
     538  @retval EFI_SECURITY_VIOLATION          The variable could not be retrieved due to an authentication failure.
     539  @retval EFI_UNSUPPORTED                 After ExitBootServices() has been called, this return code may be returned
     540                                          if no variable storage is supported. The platform should describe this
     541                                          runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     542                                          configuration table.
    521543
    522544**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableDxe.c

    r99404 r105670  
    3434  RegisterVariablePolicy,
    3535  DumpVariablePolicy,
    36   LockVariablePolicy
     36  LockVariablePolicy,
     37  GetVariablePolicyInfo,
     38  GetLockOnVariableStateVariablePolicyInfo
    3739};
    3840EDKII_VAR_CHECK_PROTOCOL        mVarCheck = {
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/VariablePolicySmmDxe.c

    r101291 r105670  
    412412
    413413/**
     414  Internal implementation to retrieve variable information for a given UEFI variable that is shared
     415  between different policy types.
     416
     417  Currently, the two policy structure types supported (and all that is defined) are VARIABLE_POLICY_ENTRY
     418  and VARIABLE_LOCK_ON_VAR_STATE_POLICY.
     419
     420  @param[in]      Command                               The command value to use in the communicate call.
     421  @param[in]      VariableName                          The name of the variable to use for the policy search.
     422  @param[in]      VendorGuid                            The vendor GUID of the variable to use for the policy search.
     423  @param[in,out]  VariablePolicyVariableNameBufferSize  On input, the size, in bytes, of the VariablePolicyVariableName
     424                                                        buffer.
     425
     426                                                        On output, the size, in bytes, needed to store the variable
     427                                                        policy variable name.
     428
     429                                                        If testing for the VariablePolicyVariableName buffer size
     430                                                        needed, set this value to zero so EFI_BUFFER_TOO_SMALL is
     431                                                        guaranteed to be returned if the variable policy variable name
     432                                                        is found.
     433  @param[out]     VariablePolicy                        Pointer to a buffer where the policy entry will be written
     434                                                        if found.
     435  @param[out]     VariablePolicyVariableName            Pointer to a buffer where the variable name used for the
     436                                                        variable policy will be written if a variable name is
     437                                                        registered.
     438
     439                                                        If the variable policy is not associated with a variable name
     440                                                        (e.g. applied to variable vendor namespace) and this parameter
     441                                                        is given, this parameter will not be modified and
     442                                                        VariablePolicyVariableNameBufferSize will be set to zero to
     443                                                        indicate a name was not present.
     444
     445                                                        If the pointer given is not NULL,
     446                                                        VariablePolicyVariableNameBufferSize must be non-NULL.
     447
     448  @retval     EFI_SUCCESS             A variable policy entry was found and returned successfully.
     449  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     450  @retval     EFI_BUFFER_TOO_SMALL    The VariablePolicyVariableName buffer value is too small for the size needed.
     451                                      The buffer should now point to the size needed.
     452  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     453  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     454                                      VariablePolicyVariableName is non-NULL and VariablePolicyVariableNameBufferSize
     455                                      is NULL. It can also be returned if the Command value provided is invalid.
     456  @retval     EFI_NOT_FOUND           A variable policy was not found for the given UEFI variable name and vendor GUID.
     457
     458
     459**/
     460STATIC
     461EFI_STATUS
     462InternalProtocolGetVariablePolicyInfo (
     463  IN      UINT32 Command,
     464  IN      CONST CHAR16 *VariableName,
     465  IN      CONST EFI_GUID *VendorGuid,
     466  IN OUT  UINTN *VariablePolicyVariableNameBufferSize, OPTIONAL
     467  OUT     VOID                        *VariablePolicy,
     468  OUT     CHAR16                      *VariablePolicyVariableName             OPTIONAL
     469  )
     470{
     471  EFI_STATUS                             Status;
     472  CHAR16                                 *OutputVariableName;
     473  EFI_MM_COMMUNICATE_HEADER              *CommHeader;
     474  VAR_CHECK_POLICY_COMM_HEADER           *PolicyHeader;
     475  VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS  *CommandParams;
     476  UINTN                                  AllowedOutputVariableNameSize;
     477  UINTN                                  BufferSize;
     478  UINTN                                  VariableNameSize;
     479
     480  if ((VariableName == NULL) || (VendorGuid == NULL) || (VariablePolicy == NULL)) {
     481    return EFI_INVALID_PARAMETER;
     482  }
     483
     484  switch (Command) {
     485    case VAR_CHECK_POLICY_COMMAND_GET_INFO:
     486    case VAR_CHECK_POLICY_COMMAND_GET_LOCK_VAR_STATE_INFO:
     487      break;
     488    default:
     489      return EFI_INVALID_PARAMETER;
     490  }
     491
     492  AcquireLockOnlyAtBootTime (&mMmCommunicationLock);
     493
     494  VariableNameSize = StrnSizeS (
     495                       VariableName,
     496                       (VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE - VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END)
     497                       );
     498  if (VariableNameSize >= (VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE - VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END)) {
     499    Status = EFI_INVALID_PARAMETER;
     500    goto Done;
     501  }
     502
     503  if ((VariablePolicyVariableName != NULL) && (VariablePolicyVariableNameBufferSize == NULL)) {
     504    return EFI_INVALID_PARAMETER;
     505    goto Done;
     506  }
     507
     508  BufferSize = mMmCommunicationBufferSize;
     509  CommHeader = mMmCommunicationBuffer;
     510
     511  Status =  SafeUintnSub (
     512              VAR_CHECK_POLICY_MM_GET_INFO_BUFFER_SIZE,
     513              VariableNameSize,
     514              &AllowedOutputVariableNameSize
     515              );
     516  if (EFI_ERROR (Status)) {
     517    Status = EFI_INVALID_PARAMETER;
     518    goto Done;
     519  }
     520
     521  if (VariablePolicyVariableNameBufferSize != NULL) {
     522    AllowedOutputVariableNameSize = MIN (AllowedOutputVariableNameSize, *VariablePolicyVariableNameBufferSize);
     523  } else {
     524    AllowedOutputVariableNameSize = 0;
     525  }
     526
     527  PolicyHeader  = (VAR_CHECK_POLICY_COMM_HEADER *)&CommHeader->Data;
     528  CommandParams = (VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS *)(PolicyHeader + 1);
     529
     530  CopyGuid (&CommHeader->HeaderGuid, &gVarCheckPolicyLibMmiHandlerGuid);
     531  CommHeader->MessageLength = BufferSize - OFFSET_OF (EFI_MM_COMMUNICATE_HEADER, Data);
     532  PolicyHeader->Signature   = VAR_CHECK_POLICY_COMM_SIG;
     533  PolicyHeader->Revision    = VAR_CHECK_POLICY_COMM_REVISION;
     534  PolicyHeader->Command     = Command;
     535
     536  ZeroMem ((VOID *)&CommandParams->OutputPolicyEntry, sizeof (CommandParams->OutputPolicyEntry));
     537  CopyGuid (&CommandParams->InputVendorGuid, VendorGuid);
     538  Status = SafeUintnToUint32 (VariableNameSize, &CommandParams->InputVariableNameSize);
     539  if (EFI_ERROR (Status)) {
     540    Status = EFI_INVALID_PARAMETER;
     541    goto Done;
     542  }
     543
     544  Status = SafeUintnToUint32 (AllowedOutputVariableNameSize, &CommandParams->OutputVariableNameSize);
     545  if (EFI_ERROR (Status)) {
     546    Status = EFI_INVALID_PARAMETER;
     547    goto Done;
     548  }
     549
     550  if (AllowedOutputVariableNameSize > 0) {
     551    Status =  StrnCpyS (
     552                CommandParams->InputVariableName,
     553                AllowedOutputVariableNameSize / sizeof (CHAR16),
     554                VariableName,
     555                (UINTN)CommandParams->InputVariableNameSize / sizeof (CHAR16)
     556                );
     557    ASSERT_EFI_ERROR (Status);
     558  }
     559
     560  Status = InternalMmCommunicate (CommHeader, &BufferSize);
     561  if (Status == EFI_SUCCESS) {
     562    CopyMem (
     563      VariablePolicy,
     564      (VOID *)&CommandParams->OutputPolicyEntry,
     565      (Command == VAR_CHECK_POLICY_COMMAND_GET_INFO) ?
     566      sizeof (CommandParams->OutputPolicyEntry.VariablePolicy) :
     567      sizeof (CommandParams->OutputPolicyEntry.LockOnVarStatePolicy)
     568      );
     569
     570    if (VariablePolicyVariableNameBufferSize == NULL) {
     571      if (VariablePolicyVariableName != NULL) {
     572        Status = EFI_INVALID_PARAMETER;
     573      }
     574
     575      goto Done;
     576    }
     577
     578    if (PolicyHeader->Result == EFI_BUFFER_TOO_SMALL) {
     579      *VariablePolicyVariableNameBufferSize = (UINTN)CommandParams->OutputVariableNameSize;
     580      goto Done;
     581    }
     582
     583    if (PolicyHeader->Result == EFI_SUCCESS) {
     584      if (CommandParams->OutputVariableNameSize > 0) {
     585        Status =  SafeUintnAdd (
     586                    ((UINTN)CommandParams + VAR_CHECK_POLICY_COMM_GET_INFO_PARAMS_END),
     587                    (UINTN)CommandParams->InputVariableNameSize,
     588                    (UINTN *)&OutputVariableName
     589                    );
     590        if (EFI_ERROR (Status)) {
     591          Status = EFI_BAD_BUFFER_SIZE;
     592          goto Done;
     593        }
     594
     595        Status =  StrnCpyS (
     596                    VariablePolicyVariableName,
     597                    *VariablePolicyVariableNameBufferSize / sizeof (CHAR16),
     598                    OutputVariableName,
     599                    (UINTN)CommandParams->OutputVariableNameSize
     600                    );
     601        ASSERT_EFI_ERROR (Status);
     602        *VariablePolicyVariableNameBufferSize = (UINTN)CommandParams->OutputVariableNameSize;
     603      } else {
     604        // A variable policy variable name is not present. Return values according to interface.
     605        *VariablePolicyVariableNameBufferSize = 0;
     606      }
     607    }
     608  }
     609
     610Done:
     611  ReleaseLockOnlyAtBootTime (&mMmCommunicationLock);
     612
     613  return (EFI_ERROR (Status)) ? Status : PolicyHeader->Result;
     614}
     615
     616/**
     617  This function will return variable policy information for a UEFI variable with a
     618  registered variable policy.
     619
     620  @param[in]      VariableName                          The name of the variable to use for the policy search.
     621  @param[in]      VendorGuid                            The vendor GUID of the variable to use for the policy search.
     622  @param[in,out]  VariablePolicyVariableNameBufferSize  On input, the size, in bytes, of the VariablePolicyVariableName
     623                                                        buffer.
     624
     625                                                        On output, the size, in bytes, needed to store the variable
     626                                                        policy variable name.
     627
     628                                                        If testing for the VariablePolicyVariableName buffer size
     629                                                        needed, set this value to zero so EFI_BUFFER_TOO_SMALL is
     630                                                        guaranteed to be returned if the variable policy variable name
     631                                                        is found.
     632  @param[out]     VariablePolicy                        Pointer to a buffer where the policy entry will be written
     633                                                        if found.
     634  @param[out]     VariablePolicyVariableName            Pointer to a buffer where the variable name used for the
     635                                                        variable policy will be written if a variable name is
     636                                                        registered.
     637
     638                                                        If the variable policy is not associated with a variable name
     639                                                        (e.g. applied to variable vendor namespace) and this parameter
     640                                                        is given, this parameter will not be modified and
     641                                                        VariablePolicyVariableNameBufferSize will be set to zero to
     642                                                        indicate a name was not present.
     643
     644                                                        If the pointer given is not NULL,
     645                                                        VariablePolicyVariableNameBufferSize must be non-NULL.
     646
     647  @retval     EFI_SUCCESS             A variable policy entry was found and returned successfully.
     648  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     649  @retval     EFI_BUFFER_TOO_SMALL    The VariablePolicyVariableName buffer value is too small for the size needed.
     650                                      The buffer should now point to the size needed.
     651  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     652  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     653                                      VariablePolicyVariableName is non-NULL and VariablePolicyVariableNameBufferSize
     654                                      is NULL.
     655  @retval     EFI_NOT_FOUND           A variable policy was not found for the given UEFI variable name and vendor GUID.
     656
     657**/
     658STATIC
     659EFI_STATUS
     660EFIAPI
     661ProtocolGetVariablePolicyInfo (
     662  IN      CONST CHAR16 *VariableName,
     663  IN      CONST EFI_GUID *VendorGuid,
     664  IN OUT  UINTN *VariablePolicyVariableNameBufferSize, OPTIONAL
     665  OUT     VARIABLE_POLICY_ENTRY       *VariablePolicy,
     666  OUT     CHAR16                      *VariablePolicyVariableName             OPTIONAL
     667  )
     668{
     669  return InternalProtocolGetVariablePolicyInfo (
     670           VAR_CHECK_POLICY_COMMAND_GET_INFO,
     671           VariableName,
     672           VendorGuid,
     673           VariablePolicyVariableNameBufferSize,
     674           VariablePolicy,
     675           VariablePolicyVariableName
     676           );
     677}
     678
     679/**
     680  This function will return the Lock on Variable State policy information for the policy
     681  associated with the given UEFI variable.
     682
     683  @param[in]      VariableName                              The name of the variable to use for the policy search.
     684  @param[in]      VendorGuid                                The vendor GUID of the variable to use for the policy
     685                                                            search.
     686  @param[in,out]  VariableLockPolicyVariableNameBufferSize  On input, the size, in bytes, of the
     687                                                            VariableLockPolicyVariableName buffer.
     688
     689                                                            On output, the size, in bytes, needed to store the variable
     690                                                            policy variable name.
     691
     692                                                            If testing for the VariableLockPolicyVariableName buffer
     693                           P                                 size needed, set this value to zero so EFI_BUFFER_TOO_SMALL
     694                                                            is guaranteed to be returned if the variable policy variable
     695                                                            name is found.
     696  @param[out]     VariablePolicy                            Pointer to a buffer where the policy entry will be written
     697                                                            if found.
     698  @param[out]     VariableLockPolicyVariableName            Pointer to a buffer where the variable name used for the
     699                                                            variable lock on variable state policy will be written if
     700                                                            a variable name is registered.
     701
     702                                                            If the lock on variable policy is not associated with a
     703                                                            variable name (e.g. applied to variable vendor namespace)
     704                                                            and this parameter is given, this parameter will not be
     705                                                            modified and VariableLockPolicyVariableNameBufferSize will
     706                                                            be set to zero to indicate a name was not present.
     707
     708                                                            If the pointer given is not NULL,
     709                                                            VariableLockPolicyVariableNameBufferSize must be non-NULL.
     710
     711  @retval     EFI_SUCCESS             A Lock on Variable State variable policy entry was found and returned
     712                                      successfully.
     713  @retval     EFI_BAD_BUFFER_SIZE     An internal buffer size caused a calculation error.
     714  @retval     EFI_BUFFER_TOO_SMALL    The VariableLockPolicyVariableName buffer is too small for the size needed.
     715                                      The buffer should now point to the size needed.
     716  @retval     EFI_NOT_READY           Variable policy has not yet been initialized.
     717  @retval     EFI_INVALID_PARAMETER   A required pointer argument passed is NULL. This will be returned if
     718                                      VariableLockPolicyVariableName is non-NULL and
     719                                      VariableLockPolicyVariableNameBufferSize is NULL.
     720  @retval     EFI_NOT_FOUND           A Lock on Variable State variable policy was not found for the given UEFI
     721                                      variable name and vendor GUID.
     722
     723**/
     724STATIC
     725EFI_STATUS
     726EFIAPI
     727ProtocolGetLockOnVariableStateVariablePolicyInfo (
     728  IN      CONST CHAR16 *VariableName,
     729  IN      CONST EFI_GUID *VendorGuid,
     730  IN OUT  UINTN *VariableLockPolicyVariableNameBufferSize, OPTIONAL
     731  OUT     VARIABLE_LOCK_ON_VAR_STATE_POLICY   *VariablePolicy,
     732  OUT     CHAR16                              *VariableLockPolicyVariableName             OPTIONAL
     733  )
     734{
     735  return InternalProtocolGetVariablePolicyInfo (
     736           VAR_CHECK_POLICY_COMMAND_GET_LOCK_VAR_STATE_INFO,
     737           VariableName,
     738           VendorGuid,
     739           VariableLockPolicyVariableNameBufferSize,
     740           VariablePolicy,
     741           VariableLockPolicyVariableName
     742           );
     743}
     744
     745/**
    414746  This helper function locates the shared comm buffer and assigns it to input pointers.
    415747
     
    515847
    516848  // Configure the VariablePolicy protocol structure.
    517   mVariablePolicyProtocol.Revision                = EDKII_VARIABLE_POLICY_PROTOCOL_REVISION;
    518   mVariablePolicyProtocol.DisableVariablePolicy   = ProtocolDisableVariablePolicy;
    519   mVariablePolicyProtocol.IsVariablePolicyEnabled = ProtocolIsVariablePolicyEnabled;
    520   mVariablePolicyProtocol.RegisterVariablePolicy  = ProtocolRegisterVariablePolicy;
    521   mVariablePolicyProtocol.DumpVariablePolicy      = ProtocolDumpVariablePolicy;
    522   mVariablePolicyProtocol.LockVariablePolicy      = ProtocolLockVariablePolicy;
     849  mVariablePolicyProtocol.Revision                                 = EDKII_VARIABLE_POLICY_PROTOCOL_REVISION;
     850  mVariablePolicyProtocol.DisableVariablePolicy                    = ProtocolDisableVariablePolicy;
     851  mVariablePolicyProtocol.IsVariablePolicyEnabled                  = ProtocolIsVariablePolicyEnabled;
     852  mVariablePolicyProtocol.RegisterVariablePolicy                   = ProtocolRegisterVariablePolicy;
     853  mVariablePolicyProtocol.DumpVariablePolicy                       = ProtocolDumpVariablePolicy;
     854  mVariablePolicyProtocol.LockVariablePolicy                       = ProtocolLockVariablePolicy;
     855  mVariablePolicyProtocol.GetVariablePolicyInfo                    = ProtocolGetVariablePolicyInfo;
     856  mVariablePolicyProtocol.GetLockOnVariableStateVariablePolicyInfo = ProtocolGetLockOnVariableStateVariablePolicyInfo;
    523857
    524858  // Register all the protocols and return the status.
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableRuntimeDxe.inf

    r99404 r105670  
    127127  ## SOMETIMES_CONSUMES   ## Variable:L"dbt"
    128128  gEfiImageSecurityDatabaseGuid
     129  gEfiDeviceSignatureDatabaseGuid
    129130
    130131[Pcd]
     
    140141  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvModeEnable         ## SOMETIMES_CONSUMES
    141142  gEfiMdeModulePkgTokenSpaceGuid.PcdEmuVariableNvStoreReserved      ## SOMETIMES_CONSUMES
     143  gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision       ## CONSUMES
     144  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableSpdmDeviceAuthentication   ## PRODUCES AND CONSUMES
    142145
    143146[FeaturePcd]
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.c

    r99404 r105670  
    832832  @param[out]     Data               Data pointer.
    833833
    834   @retval EFI_INVALID_PARAMETER      Invalid parameter.
    835   @retval EFI_SUCCESS                Find the specified variable.
    836   @retval EFI_NOT_FOUND              Not found.
    837   @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
     834  @retval EFI_SUCCESS                The function completed successfully.
     835  @retval EFI_NOT_FOUND              The variable was not found.
     836  @retval EFI_BUFFER_TOO_SMALL       The DataSize is too small for the result.
     837  @retval EFI_INVALID_PARAMETER      VariableName is NULL.
     838  @retval EFI_INVALID_PARAMETER      VendorGuid is NULL.
     839  @retval EFI_INVALID_PARAMETER      DataSize is NULL.
     840  @retval EFI_INVALID_PARAMETER      The DataSize is not too small and Data is NULL.
     841  @retval EFI_DEVICE_ERROR           The variable could not be retrieved due to a hardware error.
     842  @retval EFI_SECURITY_VIOLATION     The variable could not be retrieved due to an authentication failure.
     843  @retval EFI_UNSUPPORTED            After ExitBootServices() has been called, this return code may be returned
     844                                     if no variable storage is supported. The platform should describe this
     845                                     runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     846                                     configuration table.
    838847
    839848**/
     
    877886  @param[in, out] VendorGuid         Variable Vendor Guid.
    878887
    879   @retval EFI_INVALID_PARAMETER      Invalid parameter.
    880   @retval EFI_SUCCESS                Find the specified variable.
    881   @retval EFI_NOT_FOUND              Not found.
    882   @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
     888  @retval EFI_SUCCESS                The function completed successfully.
     889  @retval EFI_NOT_FOUND              The next variable was not found.
     890  @retval EFI_BUFFER_TOO_SMALL       The VariableNameSize is too small for the result.
     891                                     VariableNameSize has been updated with the size needed to complete the request.
     892  @retval EFI_INVALID_PARAMETER      VariableNameSize is NULL.
     893  @retval EFI_INVALID_PARAMETER      VariableName is NULL.
     894  @retval EFI_INVALID_PARAMETER      VendorGuid is NULL.
     895  @retval EFI_INVALID_PARAMETER      The input values of VariableName and VendorGuid are not a name and
     896                                     GUID of an existing variable.
     897  @retval EFI_INVALID_PARAMETER      Null-terminator is not found in the first VariableNameSize bytes of
     898                                     the input VariableName buffer.
     899  @retval EFI_DEVICE_ERROR           The variable could not be retrieved due to a hardware error.
     900  @retval EFI_UNSUPPORTED            After ExitBootServices() has been called, this return code may be returned
     901                                     if no variable storage is supported. The platform should describe this
     902                                     runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     903                                     configuration table.
    883904
    884905**/
     
    952973  @param[in, out] VendorGuid         Variable Vendor Guid.
    953974
    954   @retval EFI_INVALID_PARAMETER      Invalid parameter.
    955   @retval EFI_SUCCESS                Find the specified variable.
    956   @retval EFI_NOT_FOUND              Not found.
    957   @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
     975  @retval EFI_SUCCESS                The function completed successfully.
     976  @retval EFI_NOT_FOUND              The next variable was not found.
     977  @retval EFI_BUFFER_TOO_SMALL       The VariableNameSize is too small for the result.
     978                                     VariableNameSize has been updated with the size needed to complete the request.
     979  @retval EFI_INVALID_PARAMETER      VariableNameSize is NULL.
     980  @retval EFI_INVALID_PARAMETER      VariableName is NULL.
     981  @retval EFI_INVALID_PARAMETER      VendorGuid is NULL.
     982  @retval EFI_INVALID_PARAMETER      The input values of VariableName and VendorGuid are not a name and
     983                                     GUID of an existing variable.
     984  @retval EFI_INVALID_PARAMETER      Null-terminator is not found in the first VariableNameSize bytes of
     985                                     the input VariableName buffer.
     986  @retval EFI_DEVICE_ERROR           The variable could not be retrieved due to a hardware error.
     987  @retval EFI_UNSUPPORTED            After ExitBootServices() has been called, this return code may be returned
     988                                     if no variable storage is supported. The platform should describe this
     989                                     runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     990                                     configuration table.
    958991
    959992**/
     
    10531086  @param[in, out] VendorGuid         Variable Vendor Guid.
    10541087
    1055   @retval EFI_INVALID_PARAMETER      Invalid parameter.
    1056   @retval EFI_SUCCESS                Find the specified variable.
    1057   @retval EFI_NOT_FOUND              Not found.
    1058   @retval EFI_BUFFER_TO_SMALL        DataSize is too small for the result.
     1088  @retval EFI_SUCCESS                The function completed successfully.
     1089  @retval EFI_NOT_FOUND              The next variable was not found.
     1090  @retval EFI_BUFFER_TOO_SMALL       The VariableNameSize is too small for the result.
     1091                                     VariableNameSize has been updated with the size needed to complete the request.
     1092  @retval EFI_INVALID_PARAMETER      VariableNameSize is NULL.
     1093  @retval EFI_INVALID_PARAMETER      VariableName is NULL.
     1094  @retval EFI_INVALID_PARAMETER      VendorGuid is NULL.
     1095  @retval EFI_INVALID_PARAMETER      The input values of VariableName and VendorGuid are not a name and
     1096                                     GUID of an existing variable.
     1097  @retval EFI_INVALID_PARAMETER      Null-terminator is not found in the first VariableNameSize bytes of
     1098                                     the input VariableName buffer.
     1099  @retval EFI_DEVICE_ERROR           The variable could not be retrieved due to a hardware error.
     1100  @retval EFI_UNSUPPORTED            After ExitBootServices() has been called, this return code may be returned
     1101                                     if no variable storage is supported. The platform should describe this
     1102                                     runtime service as unsupported at runtime via an EFI_RT_PROPERTIES_TABLE
     1103                                     configuration table.
    10591104
    10601105**/
     
    11131158  @param[in] Data                         Data pointer.
    11141159
    1115   @retval EFI_INVALID_PARAMETER           Invalid parameter.
    1116   @retval EFI_SUCCESS                     Set successfully.
    1117   @retval EFI_OUT_OF_RESOURCES            Resource not enough to set variable.
    1118   @retval EFI_NOT_FOUND                   Not found.
    1119   @retval EFI_WRITE_PROTECTED             Variable is read-only.
     1160  @retval EFI_SUCCESS                     The firmware has successfully stored the variable and its data as
     1161                                          defined by the Attributes.
     1162  @retval EFI_INVALID_PARAMETER           An invalid combination of attribute bits, name, and GUID was supplied, or the
     1163                                          DataSize exceeds the maximum allowed.
     1164  @retval EFI_INVALID_PARAMETER           VariableName is an empty string.
     1165  @retval EFI_OUT_OF_RESOURCES            Not enough storage is available to hold the variable and its data.
     1166  @retval EFI_DEVICE_ERROR                The variable could not be retrieved due to a hardware error.
     1167  @retval EFI_WRITE_PROTECTED             The variable in question is read-only.
     1168  @retval EFI_WRITE_PROTECTED             The variable in question cannot be deleted.
     1169  @retval EFI_SECURITY_VIOLATION          The variable could not be written due to
     1170                                          EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACESS being set,
     1171                                          but the AuthInfo does NOT pass the validation check carried out by the firmware.
     1172
     1173  @retval EFI_NOT_FOUND                   The variable trying to be updated or deleted was not found.
     1174  @retval EFI_UNSUPPORTED                 This call is not supported by this platform at the time the call is made.
     1175                                          The platform should describe this runtime service as unsupported at runtime
     1176                                          via an EFI_RT_PROPERTIES_TABLE configuration table.
    11201177
    11211178**/
  • trunk/src/VBox/Devices/EFI/FirmwareNew/MdeModulePkg/Universal/Variable/RuntimeDxe/VariableSmmRuntimeDxe.inf

    r89983 r105670  
    8282[Pcd]
    8383  gEfiMdeModulePkgTokenSpaceGuid.PcdAllowVariablePolicyEnforcementDisable     ## CONSUMES
     84  gEfiMdeModulePkgTokenSpaceGuid.PcdTcgPfpMeasurementRevision                 ## CONSUMES
     85  gEfiMdeModulePkgTokenSpaceGuid.PcdEnableSpdmDeviceAuthentication             ## PRODUCES AND CONSUMES
    8486
    8587[Guids]
     
    112114  gVarCheckPolicyLibMmiHandlerGuid
    113115  gEfiEndOfDxeEventGroupGuid
     116  gEfiDeviceSignatureDatabaseGuid
    114117
    115118[Depex]
Note: See TracChangeset for help on using the changeset viewer.

© 2025 Oracle Support Privacy / Do Not Sell My Info Terms of Use Trademark Policy Automated Access Etiquette