1 /** @file
2   MDE DXE Services Library provides functions that simplify the development of DXE Drivers.
3   These functions help access data from sections of FFS files or from file path.
4 
5   Copyright (c) 2007 - 2015, Intel Corporation. All rights reserved.<BR>
6   (C) Copyright 2015 Hewlett Packard Enterprise Development LP<BR>
7   This program and the accompanying materials
8   are licensed and made available under the terms and conditions of the BSD License
9   which accompanies this distribution.  The full text of the license may be found at
10   http://opensource.org/licenses/bsd-license.php.
11 
12   THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
13   WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
14 
15 **/
16 
17 #include <PiDxe.h>
18 #include <Library/DebugLib.h>
19 #include <Library/MemoryAllocationLib.h>
20 #include <Library/UefiBootServicesTableLib.h>
21 #include <Library/DevicePathLib.h>
22 #include <Library/UefiLib.h>
23 #include <Library/DxeServicesLib.h>
24 #include <Protocol/FirmwareVolume2.h>
25 #include <Protocol/LoadedImage.h>
26 #include <Protocol/LoadFile2.h>
27 #include <Protocol/LoadFile.h>
28 #include <Protocol/SimpleFileSystem.h>
29 #include <Guid/FileInfo.h>
30 
31 /**
32   Identify the device handle from which the Image is loaded from. As this device handle is passed to
33   GetSectionFromFv as the identifier for a Firmware Volume, an EFI_FIRMWARE_VOLUME2_PROTOCOL
34   protocol instance should be located succesfully by calling gBS->HandleProtocol ().
35 
36   This function locates the EFI_LOADED_IMAGE_PROTOCOL instance installed
37   on ImageHandle. It then returns EFI_LOADED_IMAGE_PROTOCOL.DeviceHandle.
38 
39   If ImageHandle is NULL, then ASSERT ();
40   If failed to locate a EFI_LOADED_IMAGE_PROTOCOL on ImageHandle, then ASSERT ();
41 
42   @param  ImageHandle         The firmware allocated handle for UEFI image.
43 
44   @retval  EFI_HANDLE         The device handle from which the Image is loaded from.
45 
46 **/
47 EFI_HANDLE
InternalImageHandleToFvHandle(EFI_HANDLE ImageHandle)48 InternalImageHandleToFvHandle (
49   EFI_HANDLE ImageHandle
50   )
51 {
52   EFI_STATUS                    Status;
53   EFI_LOADED_IMAGE_PROTOCOL     *LoadedImage;
54 
55   ASSERT (ImageHandle != NULL);
56 
57   Status = gBS->HandleProtocol (
58              (EFI_HANDLE *) ImageHandle,
59              &gEfiLoadedImageProtocolGuid,
60              (VOID **) &LoadedImage
61              );
62 
63   ASSERT_EFI_ERROR (Status);
64 
65   return LoadedImage->DeviceHandle;
66 
67 }
68 
69 /**
70   Allocate and fill a buffer from a Firmware Section identified by a Firmware File GUID name, a Firmware
71   Section type and instance number from the specified Firmware Volume.
72 
73   This functions first locate the EFI_FIRMWARE_VOLUME2_PROTOCOL protocol instance on FvHandle in order to
74   carry out the Firmware Volume read operation. The function then reads the Firmware Section found sepcifed
75   by NameGuid, SectionType and SectionInstance.
76 
77   The details of this search order is defined in description of EFI_FIRMWARE_VOLUME2_PROTOCOL.ReadSection ()
78   found in PI Specification.
79 
80   If SectionType is EFI_SECTION_TE, EFI_SECTION_TE is used as section type to start the search. If EFI_SECTION_TE section
81   is not found, EFI_SECTION_PE32 will be used to try the search again. If no EFI_SECTION_PE32 section is found, EFI_NOT_FOUND
82   is returned.
83 
84   The data and size is returned by Buffer and Size. The caller is responsible to free the Buffer allocated
85   by this function. This function can be only called at TPL_NOTIFY and below.
86 
87   If FvHandle is NULL, then ASSERT ();
88   If NameGuid is NULL, then ASSERT();
89   If Buffer is NULL, then ASSERT();
90   If Size is NULL, then ASSERT().
91 
92   @param  FvHandle                The device handle that contains a instance of
93                                   EFI_FIRMWARE_VOLUME2_PROTOCOL instance.
94   @param  NameGuid                The GUID name of a Firmware File.
95   @param  SectionType             The Firmware Section type.
96   @param  SectionInstance         The instance number of Firmware Section to
97                                   read from starting from 0.
98   @param  Buffer                  On output, Buffer contains the the data read
99                                   from the section in the Firmware File found.
100   @param  Size                    On output, the size of Buffer.
101 
102   @retval  EFI_SUCCESS            The image is found and data and size is returned.
103   @retval  EFI_NOT_FOUND          The image specified by NameGuid and SectionType
104                                   can't be found.
105   @retval  EFI_OUT_OF_RESOURCES   There were not enough resources to allocate the
106                                   output data buffer or complete the operations.
107   @retval  EFI_DEVICE_ERROR       A hardware error occurs during reading from the
108                                   Firmware Volume.
109   @retval  EFI_ACCESS_DENIED      The firmware volume containing the searched
110                                   Firmware File is configured to disallow reads.
111 
112 **/
113 EFI_STATUS
InternalGetSectionFromFv(IN EFI_HANDLE FvHandle,IN CONST EFI_GUID * NameGuid,IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT VOID ** Buffer,OUT UINTN * Size)114 InternalGetSectionFromFv (
115   IN  EFI_HANDLE                    FvHandle,
116   IN  CONST EFI_GUID                *NameGuid,
117   IN  EFI_SECTION_TYPE              SectionType,
118   IN  UINTN                         SectionInstance,
119   OUT VOID                          **Buffer,
120   OUT UINTN                         *Size
121   )
122 {
123   EFI_STATUS                    Status;
124   EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
125   UINT32                        AuthenticationStatus;
126 
127   ASSERT (NameGuid != NULL);
128   ASSERT (Buffer != NULL);
129   ASSERT (Size != NULL);
130 
131   ASSERT (FvHandle != NULL);
132 
133   Status = gBS->HandleProtocol (
134                   FvHandle,
135                   &gEfiFirmwareVolume2ProtocolGuid,
136                   (VOID **) &Fv
137                   );
138   if (EFI_ERROR (Status)) {
139     return EFI_NOT_FOUND;
140   }
141 
142   //
143   // Read desired section content in NameGuid file
144   //
145   *Buffer     = NULL;
146   *Size       = 0;
147   Status      = Fv->ReadSection (
148                       Fv,
149                       NameGuid,
150                       SectionType,
151                       SectionInstance,
152                       Buffer,
153                       Size,
154                       &AuthenticationStatus
155                       );
156 
157   if (EFI_ERROR (Status) && (SectionType == EFI_SECTION_TE)) {
158     //
159     // Try reading PE32 section, if the required section is TE type
160     //
161     *Buffer = NULL;
162     *Size   = 0;
163     Status  = Fv->ReadSection (
164                     Fv,
165                     NameGuid,
166                     EFI_SECTION_PE32,
167                     SectionInstance,
168                     Buffer,
169                     Size,
170                     &AuthenticationStatus
171                     );
172   }
173 
174   return Status;
175 }
176 
177 /**
178   Searches all the available firmware volumes and returns the first matching FFS section.
179 
180   This function searches all the firmware volumes for FFS files with FV file type specified by FileType
181   The order that the firmware volumes is searched is not deterministic. For each available FV a search
182   is made for FFS file of type FileType. If the FV contains more than one FFS file with the same FileType,
183   the FileInstance instance will be the matched FFS file. For each FFS file found a search
184   is made for FFS sections of type SectionType. If the FFS file contains at least SectionInstance instances
185   of the FFS section specified by SectionType, then the SectionInstance instance is returned in Buffer.
186   Buffer is allocated using AllocatePool(), and the size of the allocated buffer is returned in Size.
187   It is the caller's responsibility to use FreePool() to free the allocated buffer.
188   See EFI_FIRMWARE_VOLUME2_PROTOCOL.ReadSection() for details on how sections
189   are retrieved from an FFS file based on SectionType and SectionInstance.
190 
191   If SectionType is EFI_SECTION_TE, and the search with an FFS file fails,
192   the search will be retried with a section type of EFI_SECTION_PE32.
193   This function must be called with a TPL <= TPL_NOTIFY.
194 
195   If Buffer is NULL, then ASSERT().
196   If Size is NULL, then ASSERT().
197 
198   @param  FileType             Indicates the FV file type to search for within all
199                                available FVs.
200   @param  FileInstance         Indicates which file instance within all available
201                                FVs specified by FileType.
202                                FileInstance starts from zero.
203   @param  SectionType          Indicates the FFS section type to search for
204                                within the FFS file
205                                specified by FileType with FileInstance.
206   @param  SectionInstance      Indicates which section instance within the FFS file
207                                specified by FileType with FileInstance to retrieve.
208                                SectionInstance starts from zero.
209   @param  Buffer               On output, a pointer to a callee allocated buffer
210                                containing the FFS file section that was found.
211                                Is it the caller's responsibility to free this
212                                buffer using FreePool().
213   @param  Size                 On output, a pointer to the size, in bytes, of Buffer.
214 
215   @retval  EFI_SUCCESS          The specified FFS section was returned.
216   @retval  EFI_NOT_FOUND        The specified FFS section could not be found.
217   @retval  EFI_OUT_OF_RESOURCES There are not enough resources available to retrieve
218                                 the matching FFS section.
219   @retval  EFI_DEVICE_ERROR     The FFS section could not be retrieves due to a
220                                 device error.
221   @retval  EFI_ACCESS_DENIED    The FFS section could not be retrieves because
222                                 the firmware volume that
223                                 contains the matching FFS section does not allow reads.
224 **/
225 EFI_STATUS
226 EFIAPI
GetSectionFromAnyFvByFileType(IN EFI_FV_FILETYPE FileType,IN UINTN FileInstance,IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT VOID ** Buffer,OUT UINTN * Size)227 GetSectionFromAnyFvByFileType  (
228   IN  EFI_FV_FILETYPE               FileType,
229   IN  UINTN                         FileInstance,
230   IN  EFI_SECTION_TYPE              SectionType,
231   IN  UINTN                         SectionInstance,
232   OUT VOID                          **Buffer,
233   OUT UINTN                         *Size
234   )
235 {
236   EFI_STATUS                    Status;
237   EFI_HANDLE                    *HandleBuffer;
238   UINTN                         HandleCount;
239   UINTN                         IndexFv;
240   UINTN                         IndexFile;
241   UINTN                         Key;
242   EFI_GUID                      NameGuid;
243   EFI_FV_FILE_ATTRIBUTES        Attributes;
244   EFI_FIRMWARE_VOLUME2_PROTOCOL *Fv;
245 
246   //
247   // Locate all available FVs.
248   //
249   HandleBuffer = NULL;
250   Status = gBS->LocateHandleBuffer (
251                   ByProtocol,
252                   &gEfiFirmwareVolume2ProtocolGuid,
253                   NULL,
254                   &HandleCount,
255                   &HandleBuffer
256                   );
257   if (EFI_ERROR (Status)) {
258     return Status;
259   }
260 
261   //
262   // Go through FVs one by one to find the required section data.
263   //
264   for (IndexFv = 0; IndexFv < HandleCount; IndexFv++) {
265     Status = gBS->HandleProtocol (
266                     HandleBuffer[IndexFv],
267                     &gEfiFirmwareVolume2ProtocolGuid,
268                     (VOID **)&Fv
269                     );
270     if (EFI_ERROR (Status)) {
271       continue;
272     }
273 
274     //
275     // Use Firmware Volume 2 Protocol to search for a file of type FileType in all FVs.
276     //
277     IndexFile = FileInstance + 1;
278     Key = 0;
279     do {
280       Status = Fv->GetNextFile (Fv, &Key, &FileType, &NameGuid, &Attributes, Size);
281       if (EFI_ERROR (Status)) {
282         break;
283       }
284       IndexFile --;
285     } while (IndexFile > 0);
286 
287     //
288     // Fv File with the required FV file type is found.
289     // Search the section file in the found FV file.
290     //
291     if (IndexFile == 0) {
292       Status = InternalGetSectionFromFv (
293                  HandleBuffer[IndexFv],
294                  &NameGuid,
295                  SectionType,
296                  SectionInstance,
297                  Buffer,
298                  Size
299                  );
300 
301       if (!EFI_ERROR (Status)) {
302         goto Done;
303       }
304     }
305   }
306 
307   //
308   // The required FFS section file is not found.
309   //
310   if (IndexFv == HandleCount) {
311     Status = EFI_NOT_FOUND;
312   }
313 
314 Done:
315   if (HandleBuffer != NULL) {
316     FreePool(HandleBuffer);
317   }
318 
319   return Status;
320 }
321 
322 /**
323   Searches all the availables firmware volumes and returns the first matching FFS section.
324 
325   This function searches all the firmware volumes for FFS files with an FFS filename specified by NameGuid.
326   The order that the firmware volumes is searched is not deterministic. For each FFS file found a search
327   is made for FFS sections of type SectionType. If the FFS file contains at least SectionInstance instances
328   of the FFS section specified by SectionType, then the SectionInstance instance is returned in Buffer.
329   Buffer is allocated using AllocatePool(), and the size of the allocated buffer is returned in Size.
330   It is the caller's responsibility to use FreePool() to free the allocated buffer.
331   See EFI_FIRMWARE_VOLUME2_PROTOCOL.ReadSection() for details on how sections
332   are retrieved from an FFS file based on SectionType and SectionInstance.
333 
334   If SectionType is EFI_SECTION_TE, and the search with an FFS file fails,
335   the search will be retried with a section type of EFI_SECTION_PE32.
336   This function must be called with a TPL <= TPL_NOTIFY.
337 
338   If NameGuid is NULL, then ASSERT().
339   If Buffer is NULL, then ASSERT().
340   If Size is NULL, then ASSERT().
341 
342 
343   @param  NameGuid             A pointer to to the FFS filename GUID to search for
344                                within any of the firmware volumes in the platform.
345   @param  SectionType          Indicates the FFS section type to search for within
346                                the FFS file specified by NameGuid.
347   @param  SectionInstance      Indicates which section instance within the FFS file
348                                specified by NameGuid to retrieve.
349   @param  Buffer               On output, a pointer to a callee allocated buffer
350                                containing the FFS file section that was found.
351                                Is it the caller's responsibility to free this buffer
352                                using FreePool().
353   @param  Size                 On output, a pointer to the size, in bytes, of Buffer.
354 
355   @retval  EFI_SUCCESS          The specified FFS section was returned.
356   @retval  EFI_NOT_FOUND        The specified FFS section could not be found.
357   @retval  EFI_OUT_OF_RESOURCES There are not enough resources available to
358                                 retrieve the matching FFS section.
359   @retval  EFI_DEVICE_ERROR     The FFS section could not be retrieves due to a
360                                 device error.
361   @retval  EFI_ACCESS_DENIED    The FFS section could not be retrieves because the
362                                 firmware volume that
363                                 contains the matching FFS section does not allow reads.
364 **/
365 EFI_STATUS
366 EFIAPI
GetSectionFromAnyFv(IN CONST EFI_GUID * NameGuid,IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT VOID ** Buffer,OUT UINTN * Size)367 GetSectionFromAnyFv  (
368   IN CONST  EFI_GUID           *NameGuid,
369   IN        EFI_SECTION_TYPE   SectionType,
370   IN        UINTN              SectionInstance,
371   OUT       VOID               **Buffer,
372   OUT       UINTN              *Size
373   )
374 {
375   EFI_STATUS                    Status;
376   EFI_HANDLE                    *HandleBuffer;
377   UINTN                         HandleCount;
378   UINTN                         Index;
379   EFI_HANDLE                    FvHandle;
380 
381   //
382   // Search the FV that contain the caller's FFS first.
383   // FV builder can choose to build FFS into the this FV
384   // so that this implementation of GetSectionFromAnyFv
385   // will locate the FFS faster.
386   //
387   FvHandle = InternalImageHandleToFvHandle (gImageHandle);
388   Status = InternalGetSectionFromFv (
389              FvHandle,
390              NameGuid,
391              SectionType,
392              SectionInstance,
393              Buffer,
394              Size
395              );
396   if (!EFI_ERROR (Status)) {
397     return EFI_SUCCESS;
398   }
399 
400   HandleBuffer = NULL;
401   Status = gBS->LocateHandleBuffer (
402                   ByProtocol,
403                   &gEfiFirmwareVolume2ProtocolGuid,
404                   NULL,
405                   &HandleCount,
406                   &HandleBuffer
407                   );
408   if (EFI_ERROR (Status)) {
409     goto Done;
410   }
411 
412   for (Index = 0; Index < HandleCount; Index++) {
413     //
414     // Skip the FV that contain the caller's FFS
415     //
416     if (HandleBuffer[Index] != FvHandle) {
417       Status = InternalGetSectionFromFv (
418                  HandleBuffer[Index],
419                  NameGuid,
420                  SectionType,
421                  SectionInstance,
422                  Buffer,
423                  Size
424                  );
425 
426       if (!EFI_ERROR (Status)) {
427         goto Done;
428       }
429     }
430 
431   }
432 
433   if (Index == HandleCount) {
434     Status = EFI_NOT_FOUND;
435   }
436 
437 Done:
438 
439   if (HandleBuffer != NULL) {
440     FreePool(HandleBuffer);
441   }
442   return Status;
443 
444 }
445 
446 /**
447   Searches the firmware volume that the currently executing module was loaded from and returns the first matching FFS section.
448 
449   This function searches the firmware volume that the currently executing module was loaded
450   from for an FFS file with an FFS filename specified by NameGuid. If the FFS file is found a search
451   is made for FFS sections of type SectionType. If the FFS file contains at least SectionInstance
452   instances of the FFS section specified by SectionType, then the SectionInstance instance is returned in Buffer.
453   Buffer is allocated using AllocatePool(), and the size of the allocated buffer is returned in Size.
454   It is the caller's responsibility to use FreePool() to free the allocated buffer.
455   See EFI_FIRMWARE_VOLUME2_PROTOCOL.ReadSection() for details on how sections are retrieved from
456   an FFS file based on SectionType and SectionInstance.
457 
458   If the currently executing module was not loaded from a firmware volume, then EFI_NOT_FOUND is returned.
459   If SectionType is EFI_SECTION_TE, and the search with an FFS file fails,
460   the search will be retried with a section type of EFI_SECTION_PE32.
461 
462   This function must be called with a TPL <= TPL_NOTIFY.
463   If NameGuid is NULL, then ASSERT().
464   If Buffer is NULL, then ASSERT().
465   If Size is NULL, then ASSERT().
466 
467   @param  NameGuid             A pointer to to the FFS filename GUID to search for
468                                within the firmware volumes that the currently
469                                executing module was loaded from.
470   @param  SectionType          Indicates the FFS section type to search for within
471                                the FFS file specified by NameGuid.
472   @param  SectionInstance      Indicates which section instance within the FFS file
473                                specified by NameGuid to retrieve.
474   @param  Buffer               On output, a pointer to a callee allocated buffer
475                                containing the FFS file section that was found.
476                                Is it the caller's responsibility to free this buffer
477                                using FreePool().
478   @param  Size                 On output, a pointer to the size, in bytes, of Buffer.
479 
480 
481   @retval  EFI_SUCCESS          The specified FFS section was returned.
482   @retval  EFI_NOT_FOUND        The specified FFS section could not be found.
483   @retval  EFI_OUT_OF_RESOURCES There are not enough resources available to retrieve
484                                 the matching FFS section.
485   @retval  EFI_DEVICE_ERROR     The FFS section could not be retrieves due to a
486                                 device error.
487   @retval  EFI_ACCESS_DENIED    The FFS section could not be retrieves because the
488                                 firmware volume that contains the matching FFS
489                                 section does not allow reads.
490 **/
491 EFI_STATUS
492 EFIAPI
GetSectionFromFv(IN CONST EFI_GUID * NameGuid,IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT VOID ** Buffer,OUT UINTN * Size)493 GetSectionFromFv (
494   IN  CONST EFI_GUID                *NameGuid,
495   IN  EFI_SECTION_TYPE              SectionType,
496   IN  UINTN                         SectionInstance,
497   OUT VOID                          **Buffer,
498   OUT UINTN                         *Size
499     )
500 {
501   return InternalGetSectionFromFv (
502            InternalImageHandleToFvHandle(gImageHandle),
503            NameGuid,
504            SectionType,
505            SectionInstance,
506            Buffer,
507            Size
508            );
509 }
510 
511 
512 /**
513   Searches the FFS file the the currently executing module was loaded from and returns the first matching FFS section.
514 
515   This function searches the FFS file that the currently executing module was loaded from for a FFS sections of type SectionType.
516   If the FFS file contains at least SectionInstance instances of the FFS section specified by SectionType,
517   then the SectionInstance instance is returned in Buffer. Buffer is allocated using AllocatePool(),
518   and the size of the allocated buffer is returned in Size. It is the caller's responsibility
519   to use FreePool() to free the allocated buffer. See EFI_FIRMWARE_VOLUME2_PROTOCOL.ReadSection() for
520   details on how sections are retrieved from an FFS file based on SectionType and SectionInstance.
521 
522   If the currently executing module was not loaded from an FFS file, then EFI_NOT_FOUND is returned.
523   If SectionType is EFI_SECTION_TE, and the search with an FFS file fails,
524   the search will be retried with a section type of EFI_SECTION_PE32.
525   This function must be called with a TPL <= TPL_NOTIFY.
526 
527   If Buffer is NULL, then ASSERT().
528   If Size is NULL, then ASSERT().
529 
530 
531   @param  SectionType          Indicates the FFS section type to search for within
532                                the FFS file that the currently executing module
533                                was loaded from.
534   @param  SectionInstance      Indicates which section instance to retrieve within
535                                the FFS file that the currently executing module
536                                was loaded from.
537   @param  Buffer               On output, a pointer to a callee allocated buffer
538                                containing the FFS file section that was found.
539                                Is it the caller's responsibility to free this buffer
540                                using FreePool().
541   @param  Size                 On output, a pointer to the size, in bytes, of Buffer.
542 
543   @retval  EFI_SUCCESS          The specified FFS section was returned.
544   @retval  EFI_NOT_FOUND        The specified FFS section could not be found.
545   @retval  EFI_OUT_OF_RESOURCES There are not enough resources available to retrieve
546                                 the matching FFS section.
547   @retval  EFI_DEVICE_ERROR     The FFS section could not be retrieves due to a
548                                 device error.
549   @retval  EFI_ACCESS_DENIED    The FFS section could not be retrieves because the
550                                 firmware volume that contains the matching FFS
551                                 section does not allow reads.
552 
553 **/
554 EFI_STATUS
555 EFIAPI
GetSectionFromFfs(IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT VOID ** Buffer,OUT UINTN * Size)556 GetSectionFromFfs (
557   IN  EFI_SECTION_TYPE              SectionType,
558   IN  UINTN                         SectionInstance,
559   OUT VOID                          **Buffer,
560   OUT UINTN                         *Size
561     )
562 {
563   return InternalGetSectionFromFv(
564            InternalImageHandleToFvHandle(gImageHandle),
565            &gEfiCallerIdGuid,
566            SectionType,
567            SectionInstance,
568            Buffer,
569            Size
570            );
571 }
572 
573 
574 /**
575   Get the image file buffer data and buffer size by its device path.
576 
577   Access the file either from a firmware volume, from a file system interface,
578   or from the load file interface.
579 
580   Allocate memory to store the found image. The caller is responsible to free memory.
581 
582   If FilePath is NULL, then NULL is returned.
583   If FileSize is NULL, then NULL is returned.
584   If AuthenticationStatus is NULL, then NULL is returned.
585 
586   @param[in]       BootPolicy           Policy for Open Image File.If TRUE, indicates
587                                         that the request originates from the boot
588                                         manager, and that the boot manager is
589                                         attempting to load FilePath as a boot
590                                         selection. If FALSE, then FilePath must
591                                         match an exact file to be loaded.
592   @param[in]       FilePath             The pointer to the device path of the file
593                                         that is absracted to the file buffer.
594   @param[out]      FileSize             The pointer to the size of the abstracted
595                                         file buffer.
596   @param[out]      AuthenticationStatus Pointer to the authentication status.
597 
598   @retval NULL   FilePath is NULL, or FileSize is NULL, or AuthenticationStatus is NULL, or the file can't be found.
599   @retval other  The abstracted file buffer. The caller is responsible to free memory.
600 **/
601 VOID *
602 EFIAPI
GetFileBufferByFilePath(IN BOOLEAN BootPolicy,IN CONST EFI_DEVICE_PATH_PROTOCOL * FilePath,OUT UINTN * FileSize,OUT UINT32 * AuthenticationStatus)603 GetFileBufferByFilePath (
604   IN BOOLEAN                           BootPolicy,
605   IN CONST EFI_DEVICE_PATH_PROTOCOL    *FilePath,
606   OUT      UINTN                       *FileSize,
607   OUT UINT32                           *AuthenticationStatus
608   )
609 {
610   EFI_DEVICE_PATH_PROTOCOL          *DevicePathNode;
611   EFI_DEVICE_PATH_PROTOCOL          *OrigDevicePathNode;
612   EFI_DEVICE_PATH_PROTOCOL          *TempDevicePathNode;
613   EFI_HANDLE                        Handle;
614   EFI_GUID                          *FvNameGuid;
615   EFI_FIRMWARE_VOLUME2_PROTOCOL     *FwVol;
616   EFI_SECTION_TYPE                  SectionType;
617   UINT8                             *ImageBuffer;
618   UINTN                             ImageBufferSize;
619   EFI_FV_FILETYPE                   Type;
620   EFI_FV_FILE_ATTRIBUTES            Attrib;
621   EFI_SIMPLE_FILE_SYSTEM_PROTOCOL   *Volume;
622   EFI_FILE_HANDLE                   FileHandle;
623   EFI_FILE_HANDLE                   LastHandle;
624   EFI_FILE_INFO                     *FileInfo;
625   UINTN                             FileInfoSize;
626   EFI_LOAD_FILE_PROTOCOL            *LoadFile;
627   EFI_LOAD_FILE2_PROTOCOL           *LoadFile2;
628   EFI_STATUS                        Status;
629 
630   //
631   // Check input File device path.
632   //
633   if (FilePath == NULL || FileSize == NULL || AuthenticationStatus == NULL) {
634     return NULL;
635   }
636 
637   //
638   // Init local variable
639   //
640   TempDevicePathNode  = NULL;
641   FvNameGuid          = NULL;
642   FileInfo            = NULL;
643   FileHandle          = NULL;
644   ImageBuffer         = NULL;
645   ImageBufferSize     = 0;
646   *AuthenticationStatus = 0;
647 
648   //
649   // Copy File Device Path
650   //
651   OrigDevicePathNode = DuplicateDevicePath (FilePath);
652   if (OrigDevicePathNode == NULL) {
653     return NULL;
654   }
655 
656   //
657   // Check whether this device path support FV2 protocol.
658   // Is so, this device path may contain a Image.
659   //
660   DevicePathNode = OrigDevicePathNode;
661   Status = gBS->LocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &DevicePathNode, &Handle);
662   if (!EFI_ERROR (Status)) {
663     //
664     // For FwVol File system there is only a single file name that is a GUID.
665     //
666     FvNameGuid = EfiGetNameGuidFromFwVolDevicePathNode ((CONST MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *) DevicePathNode);
667     if (FvNameGuid == NULL) {
668       Status = EFI_INVALID_PARAMETER;
669     } else {
670       //
671       // Read image from the firmware file
672       //
673       Status = gBS->HandleProtocol (Handle, &gEfiFirmwareVolume2ProtocolGuid, (VOID**)&FwVol);
674       if (!EFI_ERROR (Status)) {
675         SectionType = EFI_SECTION_PE32;
676         ImageBuffer = NULL;
677         Status = FwVol->ReadSection (
678                           FwVol,
679                           FvNameGuid,
680                           SectionType,
681                           0,
682                           (VOID **)&ImageBuffer,
683                           &ImageBufferSize,
684                           AuthenticationStatus
685                           );
686         if (EFI_ERROR (Status)) {
687           //
688           // Try a raw file, since a PE32 SECTION does not exist
689           //
690           if (ImageBuffer != NULL) {
691             FreePool (ImageBuffer);
692             *AuthenticationStatus = 0;
693           }
694           ImageBuffer = NULL;
695           Status = FwVol->ReadFile (
696                             FwVol,
697                             FvNameGuid,
698                             (VOID **)&ImageBuffer,
699                             &ImageBufferSize,
700                             &Type,
701                             &Attrib,
702                             AuthenticationStatus
703                             );
704         }
705       }
706     }
707     if (!EFI_ERROR (Status)) {
708       goto Finish;
709     }
710   }
711 
712   //
713   // Attempt to access the file via a file system interface
714   //
715   DevicePathNode = OrigDevicePathNode;
716   Status = gBS->LocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &DevicePathNode, &Handle);
717   if (!EFI_ERROR (Status)) {
718     Status = gBS->HandleProtocol (Handle, &gEfiSimpleFileSystemProtocolGuid, (VOID**)&Volume);
719     if (!EFI_ERROR (Status)) {
720       //
721       // Open the Volume to get the File System handle
722       //
723       Status = Volume->OpenVolume (Volume, &FileHandle);
724       if (!EFI_ERROR (Status)) {
725         //
726         // Duplicate the device path to avoid the access to unaligned device path node.
727         // Because the device path consists of one or more FILE PATH MEDIA DEVICE PATH
728         // nodes, It assures the fields in device path nodes are 2 byte aligned.
729         //
730         TempDevicePathNode = DuplicateDevicePath (DevicePathNode);
731         if (TempDevicePathNode == NULL) {
732           FileHandle->Close (FileHandle);
733           //
734           // Setting Status to an EFI_ERROR value will cause the rest of
735           // the file system support below to be skipped.
736           //
737           Status = EFI_OUT_OF_RESOURCES;
738         }
739         //
740         // Parse each MEDIA_FILEPATH_DP node. There may be more than one, since the
741         // directory information and filename can be seperate. The goal is to inch
742         // our way down each device path node and close the previous node
743         //
744         DevicePathNode = TempDevicePathNode;
745         while (!EFI_ERROR (Status) && !IsDevicePathEnd (DevicePathNode)) {
746           if (DevicePathType (DevicePathNode) != MEDIA_DEVICE_PATH ||
747               DevicePathSubType (DevicePathNode) != MEDIA_FILEPATH_DP) {
748             Status = EFI_UNSUPPORTED;
749             break;
750           }
751 
752           LastHandle = FileHandle;
753           FileHandle = NULL;
754 
755           Status = LastHandle->Open (
756                                 LastHandle,
757                                 &FileHandle,
758                                 ((FILEPATH_DEVICE_PATH *) DevicePathNode)->PathName,
759                                 EFI_FILE_MODE_READ,
760                                 0
761                                 );
762 
763           //
764           // Close the previous node
765           //
766           LastHandle->Close (LastHandle);
767 
768           DevicePathNode = NextDevicePathNode (DevicePathNode);
769         }
770 
771         if (!EFI_ERROR (Status)) {
772           //
773           // We have found the file. Now we need to read it. Before we can read the file we need to
774           // figure out how big the file is.
775           //
776           FileInfo = NULL;
777           FileInfoSize = 0;
778           Status = FileHandle->GetInfo (
779                                 FileHandle,
780                                 &gEfiFileInfoGuid,
781                                 &FileInfoSize,
782                                 FileInfo
783                                 );
784 
785           if (Status == EFI_BUFFER_TOO_SMALL) {
786             FileInfo = AllocatePool (FileInfoSize);
787             if (FileInfo == NULL) {
788               Status = EFI_OUT_OF_RESOURCES;
789             } else {
790               Status = FileHandle->GetInfo (
791                                     FileHandle,
792                                     &gEfiFileInfoGuid,
793                                     &FileInfoSize,
794                                     FileInfo
795                                     );
796             }
797           }
798 
799           if (!EFI_ERROR (Status) && (FileInfo != NULL)) {
800             if ((FileInfo->Attribute & EFI_FILE_DIRECTORY) == 0) {
801               //
802               // Allocate space for the file
803               //
804               ImageBuffer = AllocatePool ((UINTN)FileInfo->FileSize);
805               if (ImageBuffer == NULL) {
806                 Status = EFI_OUT_OF_RESOURCES;
807               } else {
808                 //
809                 // Read the file into the buffer we allocated
810                 //
811                 ImageBufferSize = (UINTN)FileInfo->FileSize;
812                 Status          = FileHandle->Read (FileHandle, &ImageBufferSize, ImageBuffer);
813               }
814             }
815           }
816         }
817         //
818         // Close the file and Free FileInfo and TempDevicePathNode since we are done
819         //
820         if (FileInfo != NULL) {
821           FreePool (FileInfo);
822         }
823         if (FileHandle != NULL) {
824           FileHandle->Close (FileHandle);
825         }
826         if (TempDevicePathNode != NULL) {
827           FreePool (TempDevicePathNode);
828         }
829       }
830     }
831     if (!EFI_ERROR (Status)) {
832       goto Finish;
833     }
834   }
835 
836   //
837   // Attempt to access the file via LoadFile2 interface
838   //
839   if (!BootPolicy) {
840     DevicePathNode = OrigDevicePathNode;
841     Status = gBS->LocateDevicePath (&gEfiLoadFile2ProtocolGuid, &DevicePathNode, &Handle);
842     if (!EFI_ERROR (Status)) {
843       Status = gBS->HandleProtocol (Handle, &gEfiLoadFile2ProtocolGuid, (VOID**)&LoadFile2);
844       if (!EFI_ERROR (Status)) {
845         //
846         // Call LoadFile2 with the correct buffer size
847         //
848         ImageBufferSize = 0;
849         ImageBuffer     = NULL;
850         Status = LoadFile2->LoadFile (
851                              LoadFile2,
852                              DevicePathNode,
853                              FALSE,
854                              &ImageBufferSize,
855                              ImageBuffer
856                              );
857         if (Status == EFI_BUFFER_TOO_SMALL) {
858           ImageBuffer = AllocatePool (ImageBufferSize);
859           if (ImageBuffer == NULL) {
860             Status = EFI_OUT_OF_RESOURCES;
861           } else {
862             Status = LoadFile2->LoadFile (
863                                  LoadFile2,
864                                  DevicePathNode,
865                                  FALSE,
866                                  &ImageBufferSize,
867                                  ImageBuffer
868                                  );
869           }
870         }
871       }
872       if (!EFI_ERROR (Status)) {
873         goto Finish;
874       }
875     }
876   }
877 
878   //
879   // Attempt to access the file via LoadFile interface
880   //
881   DevicePathNode = OrigDevicePathNode;
882   Status = gBS->LocateDevicePath (&gEfiLoadFileProtocolGuid, &DevicePathNode, &Handle);
883   if (!EFI_ERROR (Status)) {
884     Status = gBS->HandleProtocol (Handle, &gEfiLoadFileProtocolGuid, (VOID**)&LoadFile);
885     if (!EFI_ERROR (Status)) {
886       //
887       // Call LoadFile with the correct buffer size
888       //
889       ImageBufferSize = 0;
890       ImageBuffer     = NULL;
891       Status = LoadFile->LoadFile (
892                            LoadFile,
893                            DevicePathNode,
894                            BootPolicy,
895                            &ImageBufferSize,
896                            ImageBuffer
897                            );
898       if (Status == EFI_BUFFER_TOO_SMALL) {
899         ImageBuffer = AllocatePool (ImageBufferSize);
900         if (ImageBuffer == NULL) {
901           Status = EFI_OUT_OF_RESOURCES;
902         } else {
903           Status = LoadFile->LoadFile (
904                                LoadFile,
905                                DevicePathNode,
906                                BootPolicy,
907                                &ImageBufferSize,
908                                ImageBuffer
909                                );
910         }
911       }
912     }
913   }
914 
915 Finish:
916 
917   if (EFI_ERROR (Status)) {
918     if (ImageBuffer != NULL) {
919       FreePool (ImageBuffer);
920       ImageBuffer = NULL;
921     }
922     *FileSize = 0;
923   } else {
924     *FileSize = ImageBufferSize;
925   }
926 
927   FreePool (OrigDevicePathNode);
928 
929   return ImageBuffer;
930 }
931 
932 /**
933   Searches all the available firmware volumes and returns the file device path of first matching
934   FFS section.
935 
936   This function searches all the firmware volumes for FFS files with an FFS filename specified by NameGuid.
937   The order that the firmware volumes is searched is not deterministic. For each FFS file found a search
938   is made for FFS sections of type SectionType.
939 
940   If SectionType is EFI_SECTION_TE, and the search with an FFS file fails,
941   the search will be retried with a section type of EFI_SECTION_PE32.
942   This function must be called with a TPL <= TPL_NOTIFY.
943 
944   If NameGuid is NULL, then ASSERT().
945 
946    @param  NameGuid             A pointer to to the FFS filename GUID to search for
947                                 within any of the firmware volumes in the platform.
948    @param  SectionType          Indicates the FFS section type to search for within
949                                 the FFS file specified by NameGuid.
950    @param  SectionInstance      Indicates which section instance within the FFS file
951                                 specified by NameGuid to retrieve.
952    @param  FvFileDevicePath     Device path for the target FFS
953                                 file.
954 
955    @retval  EFI_SUCCESS           The specified file device path of FFS section was returned.
956    @retval  EFI_NOT_FOUND         The specified file device path of FFS section could not be found.
957    @retval  EFI_DEVICE_ERROR      The FFS section could not be retrieves due to a
958                                   device error.
959    @retval  EFI_ACCESS_DENIED     The FFS section could not be retrieves because the
960                                   firmware volume that contains the matching FFS section does not
961                                   allow reads.
962    @retval  EFI_INVALID_PARAMETER FvFileDevicePath is NULL.
963 
964 **/
965 EFI_STATUS
966 EFIAPI
GetFileDevicePathFromAnyFv(IN CONST EFI_GUID * NameGuid,IN EFI_SECTION_TYPE SectionType,IN UINTN SectionInstance,OUT EFI_DEVICE_PATH_PROTOCOL ** FvFileDevicePath)967 GetFileDevicePathFromAnyFv (
968   IN CONST  EFI_GUID                  *NameGuid,
969   IN        EFI_SECTION_TYPE          SectionType,
970   IN        UINTN                     SectionInstance,
971   OUT       EFI_DEVICE_PATH_PROTOCOL  **FvFileDevicePath
972   )
973 {
974   EFI_STATUS                        Status;
975   EFI_HANDLE                        *HandleBuffer;
976   UINTN                             HandleCount;
977   UINTN                             Index;
978   EFI_HANDLE                        FvHandle;
979   EFI_DEVICE_PATH_PROTOCOL          *FvDevicePath;
980   MEDIA_FW_VOL_FILEPATH_DEVICE_PATH *TempFvFileDevicePath;
981   VOID                              *Buffer;
982   UINTN                             Size;
983 
984   if (FvFileDevicePath == NULL) {
985     return EFI_INVALID_PARAMETER;
986   }
987 
988   HandleBuffer         = NULL;
989   FvDevicePath         = NULL;
990   TempFvFileDevicePath = NULL;
991   Buffer               = NULL;
992   Size                 = 0;
993 
994   //
995   // Search the FV that contain the caller's FFS first.
996   // FV builder can choose to build FFS into the this FV
997   // so that this implementation of GetSectionFromAnyFv
998   // will locate the FFS faster.
999   //
1000   FvHandle = InternalImageHandleToFvHandle (gImageHandle);
1001   Status = InternalGetSectionFromFv (
1002              FvHandle,
1003              NameGuid,
1004              SectionType,
1005              SectionInstance,
1006              &Buffer,
1007              &Size
1008              );
1009   if (!EFI_ERROR (Status)) {
1010     goto Done;
1011   }
1012 
1013   Status = gBS->LocateHandleBuffer (
1014                   ByProtocol,
1015                   &gEfiFirmwareVolume2ProtocolGuid,
1016                   NULL,
1017                   &HandleCount,
1018                   &HandleBuffer
1019                   );
1020   if (EFI_ERROR (Status)) {
1021     goto Done;
1022   }
1023 
1024   for (Index = 0; Index < HandleCount; Index++) {
1025     //
1026     // Skip the FV that contain the caller's FFS
1027     //
1028     if (HandleBuffer[Index] != FvHandle) {
1029       Status = InternalGetSectionFromFv (
1030                  HandleBuffer[Index],
1031                  NameGuid,
1032                  SectionType,
1033                  SectionInstance,
1034                  &Buffer,
1035                  &Size
1036                  );
1037 
1038       if (!EFI_ERROR (Status)) {
1039         //
1040         // Update FvHandle to the current handle.
1041         //
1042         FvHandle = HandleBuffer[Index];
1043         goto Done;
1044       }
1045     }
1046   }
1047 
1048   if (Index == HandleCount) {
1049     Status = EFI_NOT_FOUND;
1050   }
1051 
1052 Done:
1053   if (Status == EFI_SUCCESS) {
1054     //
1055     // Build a device path to the file in the FV to pass into gBS->LoadImage
1056     //
1057     Status = gBS->HandleProtocol (FvHandle, &gEfiDevicePathProtocolGuid, (VOID **)&FvDevicePath);
1058     if (EFI_ERROR (Status)) {
1059       *FvFileDevicePath = NULL;
1060     } else {
1061       TempFvFileDevicePath = AllocateZeroPool (sizeof (MEDIA_FW_VOL_FILEPATH_DEVICE_PATH) + END_DEVICE_PATH_LENGTH);
1062       if (TempFvFileDevicePath == NULL) {
1063         *FvFileDevicePath = NULL;
1064         return EFI_OUT_OF_RESOURCES;
1065       }
1066       EfiInitializeFwVolDevicepathNode ((MEDIA_FW_VOL_FILEPATH_DEVICE_PATH*)TempFvFileDevicePath, NameGuid);
1067       SetDevicePathEndNode (NextDevicePathNode (TempFvFileDevicePath));
1068       *FvFileDevicePath = AppendDevicePath (
1069                             FvDevicePath,
1070                             (EFI_DEVICE_PATH_PROTOCOL *)TempFvFileDevicePath
1071                             );
1072       FreePool (TempFvFileDevicePath);
1073     }
1074   }
1075 
1076   if (Buffer != NULL) {
1077     FreePool (Buffer);
1078   }
1079 
1080   if (HandleBuffer != NULL) {
1081     FreePool (HandleBuffer);
1082   }
1083 
1084   return Status;
1085 }
1086