]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/Dxe/Image/Image.c
MdeModulePkg/DxeCore: Add UEFI image protection.
[mirror_edk2.git] / MdeModulePkg / Core / Dxe / Image / Image.c
1 /** @file
2 Core image handling services to load and unload PeImage.
3
4 Copyright (c) 2006 - 2017, Intel Corporation. All rights reserved.<BR>
5 This program and the accompanying materials
6 are licensed and made available under the terms and conditions of the BSD License
7 which accompanies this distribution. The full text of the license may be found at
8 http://opensource.org/licenses/bsd-license.php
9
10 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
11 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
12
13 **/
14
15 #include "DxeMain.h"
16 #include "Image.h"
17
18 //
19 // Module Globals
20 //
21 LOADED_IMAGE_PRIVATE_DATA *mCurrentImage = NULL;
22
23 LOAD_PE32_IMAGE_PRIVATE_DATA mLoadPe32PrivateData = {
24 LOAD_PE32_IMAGE_PRIVATE_DATA_SIGNATURE,
25 NULL,
26 {
27 CoreLoadImageEx,
28 CoreUnloadImageEx
29 }
30 };
31
32
33 //
34 // This code is needed to build the Image handle for the DXE Core
35 //
36 LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage = {
37 LOADED_IMAGE_PRIVATE_DATA_SIGNATURE, // Signature
38 NULL, // Image handle
39 EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, // Image type
40 TRUE, // If entrypoint has been called
41 NULL, // EntryPoint
42 {
43 EFI_LOADED_IMAGE_INFORMATION_REVISION, // Revision
44 NULL, // Parent handle
45 NULL, // System handle
46
47 NULL, // Device handle
48 NULL, // File path
49 NULL, // Reserved
50
51 0, // LoadOptionsSize
52 NULL, // LoadOptions
53
54 NULL, // ImageBase
55 0, // ImageSize
56 EfiBootServicesCode, // ImageCodeType
57 EfiBootServicesData // ImageDataType
58 },
59 (EFI_PHYSICAL_ADDRESS)0, // ImageBasePage
60 0, // NumberOfPages
61 NULL, // FixupData
62 0, // Tpl
63 EFI_SUCCESS, // Status
64 0, // ExitDataSize
65 NULL, // ExitData
66 NULL, // JumpBuffer
67 NULL, // JumpContext
68 0, // Machine
69 NULL, // Ebc
70 NULL, // RuntimeData
71 NULL // LoadedImageDevicePath
72 };
73 //
74 // The field is define for Loading modules at fixed address feature to tracker the PEI code
75 // memory range usage. It is a bit mapped array in which every bit indicates the correspoding memory page
76 // available or not.
77 //
78 GLOBAL_REMOVE_IF_UNREFERENCED UINT64 *mDxeCodeMemoryRangeUsageBitMap=NULL;
79
80 typedef struct {
81 UINT16 MachineType;
82 CHAR16 *MachineTypeName;
83 } MACHINE_TYPE_INFO;
84
85 //
86 // EBC machine is not listed in this table, because EBC is in the default supported scopes of other machine type.
87 //
88 GLOBAL_REMOVE_IF_UNREFERENCED MACHINE_TYPE_INFO mMachineTypeInfo[] = {
89 {EFI_IMAGE_MACHINE_IA32, L"IA32"},
90 {EFI_IMAGE_MACHINE_IA64, L"IA64"},
91 {EFI_IMAGE_MACHINE_X64, L"X64"},
92 {EFI_IMAGE_MACHINE_ARMTHUMB_MIXED, L"ARM"}
93 };
94
95 UINT16 mDxeCoreImageMachineType = 0;
96
97 /**
98 Return machine type name.
99
100 @param MachineType The machine type
101
102 @return machine type name
103 **/
104 CHAR16 *
105 GetMachineTypeName (
106 UINT16 MachineType
107 )
108 {
109 UINTN Index;
110
111 for (Index = 0; Index < sizeof(mMachineTypeInfo)/sizeof(mMachineTypeInfo[0]); Index++) {
112 if (mMachineTypeInfo[Index].MachineType == MachineType) {
113 return mMachineTypeInfo[Index].MachineTypeName;
114 }
115 }
116
117 return L"<Unknown>";
118 }
119
120 /**
121 Add the Image Services to EFI Boot Services Table and install the protocol
122 interfaces for this image.
123
124 @param HobStart The HOB to initialize
125
126 @return Status code.
127
128 **/
129 EFI_STATUS
130 CoreInitializeImageServices (
131 IN VOID *HobStart
132 )
133 {
134 EFI_STATUS Status;
135 LOADED_IMAGE_PRIVATE_DATA *Image;
136 EFI_PHYSICAL_ADDRESS DxeCoreImageBaseAddress;
137 UINT64 DxeCoreImageLength;
138 VOID *DxeCoreEntryPoint;
139 EFI_PEI_HOB_POINTERS DxeCoreHob;
140
141 //
142 // Searching for image hob
143 //
144 DxeCoreHob.Raw = HobStart;
145 while ((DxeCoreHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, DxeCoreHob.Raw)) != NULL) {
146 if (CompareGuid (&DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.Name, &gEfiHobMemoryAllocModuleGuid)) {
147 //
148 // Find Dxe Core HOB
149 //
150 break;
151 }
152 DxeCoreHob.Raw = GET_NEXT_HOB (DxeCoreHob);
153 }
154 ASSERT (DxeCoreHob.Raw != NULL);
155
156 DxeCoreImageBaseAddress = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress;
157 DxeCoreImageLength = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength;
158 DxeCoreEntryPoint = (VOID *) (UINTN) DxeCoreHob.MemoryAllocationModule->EntryPoint;
159 gDxeCoreFileName = &DxeCoreHob.MemoryAllocationModule->ModuleName;
160
161 //
162 // Initialize the fields for an internal driver
163 //
164 Image = &mCorePrivateImage;
165
166 Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)DxeCoreEntryPoint;
167 Image->ImageBasePage = DxeCoreImageBaseAddress;
168 Image->NumberOfPages = (UINTN)(EFI_SIZE_TO_PAGES((UINTN)(DxeCoreImageLength)));
169 Image->Tpl = gEfiCurrentTpl;
170 Image->Info.SystemTable = gDxeCoreST;
171 Image->Info.ImageBase = (VOID *)(UINTN)DxeCoreImageBaseAddress;
172 Image->Info.ImageSize = DxeCoreImageLength;
173
174 //
175 // Install the protocol interfaces for this image
176 //
177 Status = CoreInstallProtocolInterface (
178 &Image->Handle,
179 &gEfiLoadedImageProtocolGuid,
180 EFI_NATIVE_INTERFACE,
181 &Image->Info
182 );
183 ASSERT_EFI_ERROR (Status);
184
185 mCurrentImage = Image;
186
187 //
188 // Fill in DXE globals
189 //
190 mDxeCoreImageMachineType = PeCoffLoaderGetMachineType (Image->Info.ImageBase);
191 gDxeCoreImageHandle = Image->Handle;
192 gDxeCoreLoadedImage = &Image->Info;
193
194 if (FeaturePcdGet (PcdFrameworkCompatibilitySupport)) {
195 //
196 // Export DXE Core PE Loader functionality for backward compatibility.
197 //
198 Status = CoreInstallProtocolInterface (
199 &mLoadPe32PrivateData.Handle,
200 &gEfiLoadPeImageProtocolGuid,
201 EFI_NATIVE_INTERFACE,
202 &mLoadPe32PrivateData.Pe32Image
203 );
204 }
205
206 ProtectUefiImage (&Image->Info, Image->LoadedImageDevicePath);
207
208 return Status;
209 }
210
211 /**
212 Read image file (specified by UserHandle) into user specified buffer with specified offset
213 and length.
214
215 @param UserHandle Image file handle
216 @param Offset Offset to the source file
217 @param ReadSize For input, pointer of size to read; For output,
218 pointer of size actually read.
219 @param Buffer Buffer to write into
220
221 @retval EFI_SUCCESS Successfully read the specified part of file
222 into buffer.
223
224 **/
225 EFI_STATUS
226 EFIAPI
227 CoreReadImageFile (
228 IN VOID *UserHandle,
229 IN UINTN Offset,
230 IN OUT UINTN *ReadSize,
231 OUT VOID *Buffer
232 )
233 {
234 UINTN EndPosition;
235 IMAGE_FILE_HANDLE *FHand;
236
237 if (UserHandle == NULL || ReadSize == NULL || Buffer == NULL) {
238 return EFI_INVALID_PARAMETER;
239 }
240
241 if (MAX_ADDRESS - Offset < *ReadSize) {
242 return EFI_INVALID_PARAMETER;
243 }
244
245 FHand = (IMAGE_FILE_HANDLE *)UserHandle;
246 ASSERT (FHand->Signature == IMAGE_FILE_HANDLE_SIGNATURE);
247
248 //
249 // Move data from our local copy of the file
250 //
251 EndPosition = Offset + *ReadSize;
252 if (EndPosition > FHand->SourceSize) {
253 *ReadSize = (UINT32)(FHand->SourceSize - Offset);
254 }
255 if (Offset >= FHand->SourceSize) {
256 *ReadSize = 0;
257 }
258
259 CopyMem (Buffer, (CHAR8 *)FHand->Source + Offset, *ReadSize);
260 return EFI_SUCCESS;
261 }
262 /**
263 To check memory usage bit map array to figure out if the memory range the image will be loaded in is available or not. If
264 memory range is available, the function will mark the corresponding bits to 1 which indicates the memory range is used.
265 The function is only invoked when load modules at fixed address feature is enabled.
266
267 @param ImageBase The base address the image will be loaded at.
268 @param ImageSize The size of the image
269
270 @retval EFI_SUCCESS The memory range the image will be loaded in is available
271 @retval EFI_NOT_FOUND The memory range the image will be loaded in is not available
272 **/
273 EFI_STATUS
274 CheckAndMarkFixLoadingMemoryUsageBitMap (
275 IN EFI_PHYSICAL_ADDRESS ImageBase,
276 IN UINTN ImageSize
277 )
278 {
279 UINT32 DxeCodePageNumber;
280 UINT64 DxeCodeSize;
281 EFI_PHYSICAL_ADDRESS DxeCodeBase;
282 UINTN BaseOffsetPageNumber;
283 UINTN TopOffsetPageNumber;
284 UINTN Index;
285 //
286 // The DXE code range includes RuntimeCodePage range and Boot time code range.
287 //
288 DxeCodePageNumber = PcdGet32(PcdLoadFixAddressRuntimeCodePageNumber);
289 DxeCodePageNumber += PcdGet32(PcdLoadFixAddressBootTimeCodePageNumber);
290 DxeCodeSize = EFI_PAGES_TO_SIZE(DxeCodePageNumber);
291 DxeCodeBase = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress - DxeCodeSize;
292
293 //
294 // If the memory usage bit map is not initialized, do it. Every bit in the array
295 // indicate the status of the corresponding memory page, available or not
296 //
297 if (mDxeCodeMemoryRangeUsageBitMap == NULL) {
298 mDxeCodeMemoryRangeUsageBitMap = AllocateZeroPool(((DxeCodePageNumber/64) + 1)*sizeof(UINT64));
299 }
300 //
301 // If the Dxe code memory range is not allocated or the bit map array allocation failed, return EFI_NOT_FOUND
302 //
303 if (!gLoadFixedAddressCodeMemoryReady || mDxeCodeMemoryRangeUsageBitMap == NULL) {
304 return EFI_NOT_FOUND;
305 }
306 //
307 // Test the memory range for loading the image in the DXE code range.
308 //
309 if (gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress < ImageBase + ImageSize ||
310 DxeCodeBase > ImageBase) {
311 return EFI_NOT_FOUND;
312 }
313 //
314 // Test if the memory is avalaible or not.
315 //
316 BaseOffsetPageNumber = (UINTN)EFI_SIZE_TO_PAGES((UINT32)(ImageBase - DxeCodeBase));
317 TopOffsetPageNumber = (UINTN)EFI_SIZE_TO_PAGES((UINT32)(ImageBase + ImageSize - DxeCodeBase));
318 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
319 if ((mDxeCodeMemoryRangeUsageBitMap[Index / 64] & LShiftU64(1, (Index % 64))) != 0) {
320 //
321 // This page is already used.
322 //
323 return EFI_NOT_FOUND;
324 }
325 }
326
327 //
328 // Being here means the memory range is available. So mark the bits for the memory range
329 //
330 for (Index = BaseOffsetPageNumber; Index < TopOffsetPageNumber; Index ++) {
331 mDxeCodeMemoryRangeUsageBitMap[Index / 64] |= LShiftU64(1, (Index % 64));
332 }
333 return EFI_SUCCESS;
334 }
335 /**
336
337 Get the fixed loading address from image header assigned by build tool. This function only be called
338 when Loading module at Fixed address feature enabled.
339
340 @param ImageContext Pointer to the image context structure that describes the PE/COFF
341 image that needs to be examined by this function.
342 @retval EFI_SUCCESS An fixed loading address is assigned to this image by build tools .
343 @retval EFI_NOT_FOUND The image has no assigned fixed loading address.
344
345 **/
346 EFI_STATUS
347 GetPeCoffImageFixLoadingAssignedAddress(
348 IN OUT PE_COFF_LOADER_IMAGE_CONTEXT *ImageContext
349 )
350 {
351 UINTN SectionHeaderOffset;
352 EFI_STATUS Status;
353 EFI_IMAGE_SECTION_HEADER SectionHeader;
354 EFI_IMAGE_OPTIONAL_HEADER_UNION *ImgHdr;
355 UINT16 Index;
356 UINTN Size;
357 UINT16 NumberOfSections;
358 IMAGE_FILE_HANDLE *Handle;
359 UINT64 ValueInSectionHeader;
360
361
362 Status = EFI_NOT_FOUND;
363
364 //
365 // Get PeHeader pointer
366 //
367 Handle = (IMAGE_FILE_HANDLE*)ImageContext->Handle;
368 ImgHdr = (EFI_IMAGE_OPTIONAL_HEADER_UNION *)((CHAR8* )Handle->Source + ImageContext->PeCoffHeaderOffset);
369 SectionHeaderOffset = (UINTN)(
370 ImageContext->PeCoffHeaderOffset +
371 sizeof (UINT32) +
372 sizeof (EFI_IMAGE_FILE_HEADER) +
373 ImgHdr->Pe32.FileHeader.SizeOfOptionalHeader
374 );
375 NumberOfSections = ImgHdr->Pe32.FileHeader.NumberOfSections;
376
377 //
378 // Get base address from the first section header that doesn't point to code section.
379 //
380 for (Index = 0; Index < NumberOfSections; Index++) {
381 //
382 // Read section header from file
383 //
384 Size = sizeof (EFI_IMAGE_SECTION_HEADER);
385 Status = ImageContext->ImageRead (
386 ImageContext->Handle,
387 SectionHeaderOffset,
388 &Size,
389 &SectionHeader
390 );
391 if (EFI_ERROR (Status)) {
392 return Status;
393 }
394 if (Size != sizeof (EFI_IMAGE_SECTION_HEADER)) {
395 return EFI_NOT_FOUND;
396 }
397
398 Status = EFI_NOT_FOUND;
399
400 if ((SectionHeader.Characteristics & EFI_IMAGE_SCN_CNT_CODE) == 0) {
401 //
402 // Build tool will save the address in PointerToRelocations & PointerToLineNumbers fields in the first section header
403 // that doesn't point to code section in image header, as well as ImageBase field of image header. And there is an
404 // assumption that when the feature is enabled, if a module is assigned a loading address by tools, PointerToRelocations
405 // & PointerToLineNumbers fields should NOT be Zero, or else, these 2 fields should be set to Zero
406 //
407 ValueInSectionHeader = ReadUnaligned64((UINT64*)&SectionHeader.PointerToRelocations);
408 if (ValueInSectionHeader != 0) {
409 //
410 // When the feature is configured as load module at fixed absolute address, the ImageAddress field of ImageContext
411 // hold the spcified address. If the feature is configured as load module at fixed offset, ImageAddress hold an offset
412 // relative to top address
413 //
414 if ((INT64)PcdGet64(PcdLoadModuleAtFixAddressEnable) < 0) {
415 ImageContext->ImageAddress = gLoadModuleAtFixAddressConfigurationTable.DxeCodeTopAddress + (INT64)(INTN)ImageContext->ImageAddress;
416 }
417 //
418 // Check if the memory range is available.
419 //
420 Status = CheckAndMarkFixLoadingMemoryUsageBitMap (ImageContext->ImageAddress, (UINTN)(ImageContext->ImageSize + ImageContext->SectionAlignment));
421 }
422 break;
423 }
424 SectionHeaderOffset += sizeof (EFI_IMAGE_SECTION_HEADER);
425 }
426 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED INFO: Loading module at fixed address 0x%11p. Status = %r \n", (VOID *)(UINTN)(ImageContext->ImageAddress), Status));
427 return Status;
428 }
429 /**
430 Loads, relocates, and invokes a PE/COFF image
431
432 @param BootPolicy If TRUE, indicates that the request originates
433 from the boot manager, and that the boot
434 manager is attempting to load FilePath as a
435 boot selection.
436 @param Pe32Handle The handle of PE32 image
437 @param Image PE image to be loaded
438 @param DstBuffer The buffer to store the image
439 @param EntryPoint A pointer to the entry point
440 @param Attribute The bit mask of attributes to set for the load
441 PE image
442
443 @retval EFI_SUCCESS The file was loaded, relocated, and invoked
444 @retval EFI_OUT_OF_RESOURCES There was not enough memory to load and
445 relocate the PE/COFF file
446 @retval EFI_INVALID_PARAMETER Invalid parameter
447 @retval EFI_BUFFER_TOO_SMALL Buffer for image is too small
448
449 **/
450 EFI_STATUS
451 CoreLoadPeImage (
452 IN BOOLEAN BootPolicy,
453 IN VOID *Pe32Handle,
454 IN LOADED_IMAGE_PRIVATE_DATA *Image,
455 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
456 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
457 IN UINT32 Attribute
458 )
459 {
460 EFI_STATUS Status;
461 BOOLEAN DstBufAlocated;
462 UINTN Size;
463
464 ZeroMem (&Image->ImageContext, sizeof (Image->ImageContext));
465
466 Image->ImageContext.Handle = Pe32Handle;
467 Image->ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)CoreReadImageFile;
468
469 //
470 // Get information about the image being loaded
471 //
472 Status = PeCoffLoaderGetImageInfo (&Image->ImageContext);
473 if (EFI_ERROR (Status)) {
474 return Status;
475 }
476
477 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->ImageContext.Machine)) {
478 if (!EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED (Image->ImageContext.Machine)) {
479 //
480 // The PE/COFF loader can support loading image types that can be executed.
481 // If we loaded an image type that we can not execute return EFI_UNSUPORTED.
482 //
483 DEBUG ((EFI_D_ERROR, "Image type %s can't be loaded ", GetMachineTypeName(Image->ImageContext.Machine)));
484 DEBUG ((EFI_D_ERROR, "on %s UEFI system.\n", GetMachineTypeName(mDxeCoreImageMachineType)));
485 return EFI_UNSUPPORTED;
486 }
487 }
488
489 //
490 // Set EFI memory type based on ImageType
491 //
492 switch (Image->ImageContext.ImageType) {
493 case EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION:
494 Image->ImageContext.ImageCodeMemoryType = EfiLoaderCode;
495 Image->ImageContext.ImageDataMemoryType = EfiLoaderData;
496 break;
497 case EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER:
498 Image->ImageContext.ImageCodeMemoryType = EfiBootServicesCode;
499 Image->ImageContext.ImageDataMemoryType = EfiBootServicesData;
500 break;
501 case EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER:
502 case EFI_IMAGE_SUBSYSTEM_SAL_RUNTIME_DRIVER:
503 Image->ImageContext.ImageCodeMemoryType = EfiRuntimeServicesCode;
504 Image->ImageContext.ImageDataMemoryType = EfiRuntimeServicesData;
505 break;
506 default:
507 Image->ImageContext.ImageError = IMAGE_ERROR_INVALID_SUBSYSTEM;
508 return EFI_UNSUPPORTED;
509 }
510
511 //
512 // Allocate memory of the correct memory type aligned on the required image boundary
513 //
514 DstBufAlocated = FALSE;
515 if (DstBuffer == 0) {
516 //
517 // Allocate Destination Buffer as caller did not pass it in
518 //
519
520 if (Image->ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
521 Size = (UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment;
522 } else {
523 Size = (UINTN)Image->ImageContext.ImageSize;
524 }
525
526 Image->NumberOfPages = EFI_SIZE_TO_PAGES (Size);
527
528 //
529 // If the image relocations have not been stripped, then load at any address.
530 // Otherwise load at the address at which it was linked.
531 //
532 // Memory below 1MB should be treated reserved for CSM and there should be
533 // no modules whose preferred load addresses are below 1MB.
534 //
535 Status = EFI_OUT_OF_RESOURCES;
536 //
537 // If Loading Module At Fixed Address feature is enabled, the module should be loaded to
538 // a specified address.
539 //
540 if (PcdGet64(PcdLoadModuleAtFixAddressEnable) != 0 ) {
541 Status = GetPeCoffImageFixLoadingAssignedAddress (&(Image->ImageContext));
542
543 if (EFI_ERROR (Status)) {
544 //
545 // If the code memory is not ready, invoke CoreAllocatePage with AllocateAnyPages to load the driver.
546 //
547 DEBUG ((EFI_D_INFO|EFI_D_LOAD, "LOADING MODULE FIXED ERROR: Loading module at fixed address failed since specified memory is not available.\n"));
548
549 Status = CoreAllocatePages (
550 AllocateAnyPages,
551 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),
552 Image->NumberOfPages,
553 &Image->ImageContext.ImageAddress
554 );
555 }
556 } else {
557 if (Image->ImageContext.ImageAddress >= 0x100000 || Image->ImageContext.RelocationsStripped) {
558 Status = CoreAllocatePages (
559 AllocateAddress,
560 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),
561 Image->NumberOfPages,
562 &Image->ImageContext.ImageAddress
563 );
564 }
565 if (EFI_ERROR (Status) && !Image->ImageContext.RelocationsStripped) {
566 Status = CoreAllocatePages (
567 AllocateAnyPages,
568 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),
569 Image->NumberOfPages,
570 &Image->ImageContext.ImageAddress
571 );
572 }
573 }
574 if (EFI_ERROR (Status)) {
575 return Status;
576 }
577 DstBufAlocated = TRUE;
578 } else {
579 //
580 // Caller provided the destination buffer
581 //
582
583 if (Image->ImageContext.RelocationsStripped && (Image->ImageContext.ImageAddress != DstBuffer)) {
584 //
585 // If the image relocations were stripped, and the caller provided a
586 // destination buffer address that does not match the address that the
587 // image is linked at, then the image cannot be loaded.
588 //
589 return EFI_INVALID_PARAMETER;
590 }
591
592 if (Image->NumberOfPages != 0 &&
593 Image->NumberOfPages <
594 (EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment))) {
595 Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);
596 return EFI_BUFFER_TOO_SMALL;
597 }
598
599 Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);
600 Image->ImageContext.ImageAddress = DstBuffer;
601 }
602
603 Image->ImageBasePage = Image->ImageContext.ImageAddress;
604 if (!Image->ImageContext.IsTeImage) {
605 Image->ImageContext.ImageAddress =
606 (Image->ImageContext.ImageAddress + Image->ImageContext.SectionAlignment - 1) &
607 ~((UINTN)Image->ImageContext.SectionAlignment - 1);
608 }
609
610 //
611 // Load the image from the file into the allocated memory
612 //
613 Status = PeCoffLoaderLoadImage (&Image->ImageContext);
614 if (EFI_ERROR (Status)) {
615 goto Done;
616 }
617
618 //
619 // If this is a Runtime Driver, then allocate memory for the FixupData that
620 // is used to relocate the image when SetVirtualAddressMap() is called. The
621 // relocation is done by the Runtime AP.
622 //
623 if ((Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) != 0) {
624 if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {
625 Image->ImageContext.FixupData = AllocateRuntimePool ((UINTN)(Image->ImageContext.FixupDataSize));
626 if (Image->ImageContext.FixupData == NULL) {
627 Status = EFI_OUT_OF_RESOURCES;
628 goto Done;
629 }
630 }
631 }
632
633 //
634 // Relocate the image in memory
635 //
636 Status = PeCoffLoaderRelocateImage (&Image->ImageContext);
637 if (EFI_ERROR (Status)) {
638 goto Done;
639 }
640
641 //
642 // Flush the Instruction Cache
643 //
644 InvalidateInstructionCacheRange ((VOID *)(UINTN)Image->ImageContext.ImageAddress, (UINTN)Image->ImageContext.ImageSize);
645
646 //
647 // Copy the machine type from the context to the image private data. This
648 // is needed during image unload to know if we should call an EBC protocol
649 // to unload the image.
650 //
651 Image->Machine = Image->ImageContext.Machine;
652
653 //
654 // Get the image entry point. If it's an EBC image, then call into the
655 // interpreter to create a thunk for the entry point and use the returned
656 // value for the entry point.
657 //
658 Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)Image->ImageContext.EntryPoint;
659 if (Image->ImageContext.Machine == EFI_IMAGE_MACHINE_EBC) {
660 //
661 // Locate the EBC interpreter protocol
662 //
663 Status = CoreLocateProtocol (&gEfiEbcProtocolGuid, NULL, (VOID **)&Image->Ebc);
664 if (EFI_ERROR(Status) || Image->Ebc == NULL) {
665 DEBUG ((DEBUG_LOAD | DEBUG_ERROR, "CoreLoadPeImage: There is no EBC interpreter for an EBC image.\n"));
666 goto Done;
667 }
668
669 //
670 // Register a callback for flushing the instruction cache so that created
671 // thunks can be flushed.
672 //
673 Status = Image->Ebc->RegisterICacheFlush (Image->Ebc, (EBC_ICACHE_FLUSH)InvalidateInstructionCacheRange);
674 if (EFI_ERROR(Status)) {
675 goto Done;
676 }
677
678 //
679 // Create a thunk for the image's entry point. This will be the new
680 // entry point for the image.
681 //
682 Status = Image->Ebc->CreateThunk (
683 Image->Ebc,
684 Image->Handle,
685 (VOID *)(UINTN) Image->ImageContext.EntryPoint,
686 (VOID **) &Image->EntryPoint
687 );
688 if (EFI_ERROR(Status)) {
689 goto Done;
690 }
691 }
692
693 //
694 // Fill in the image information for the Loaded Image Protocol
695 //
696 Image->Type = Image->ImageContext.ImageType;
697 Image->Info.ImageBase = (VOID *)(UINTN)Image->ImageContext.ImageAddress;
698 Image->Info.ImageSize = Image->ImageContext.ImageSize;
699 Image->Info.ImageCodeType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType);
700 Image->Info.ImageDataType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageDataMemoryType);
701 if ((Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) != 0) {
702 if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {
703 //
704 // Make a list off all the RT images so we can let the RT AP know about them.
705 //
706 Image->RuntimeData = AllocateRuntimePool (sizeof(EFI_RUNTIME_IMAGE_ENTRY));
707 if (Image->RuntimeData == NULL) {
708 goto Done;
709 }
710 Image->RuntimeData->ImageBase = Image->Info.ImageBase;
711 Image->RuntimeData->ImageSize = (UINT64) (Image->Info.ImageSize);
712 Image->RuntimeData->RelocationData = Image->ImageContext.FixupData;
713 Image->RuntimeData->Handle = Image->Handle;
714 InsertTailList (&gRuntime->ImageHead, &Image->RuntimeData->Link);
715 InsertImageRecord (Image->RuntimeData);
716 }
717 }
718
719 //
720 // Fill in the entry point of the image if it is available
721 //
722 if (EntryPoint != NULL) {
723 *EntryPoint = Image->ImageContext.EntryPoint;
724 }
725
726 //
727 // Print the load address and the PDB file name if it is available
728 //
729
730 DEBUG_CODE_BEGIN ();
731
732 UINTN Index;
733 UINTN StartIndex;
734 CHAR8 EfiFileName[256];
735
736
737 DEBUG ((DEBUG_INFO | DEBUG_LOAD,
738 "Loading driver at 0x%11p EntryPoint=0x%11p ",
739 (VOID *)(UINTN) Image->ImageContext.ImageAddress,
740 FUNCTION_ENTRY_POINT (Image->ImageContext.EntryPoint)));
741
742
743 //
744 // Print Module Name by Pdb file path.
745 // Windows and Unix style file path are all trimmed correctly.
746 //
747 if (Image->ImageContext.PdbPointer != NULL) {
748 StartIndex = 0;
749 for (Index = 0; Image->ImageContext.PdbPointer[Index] != 0; Index++) {
750 if ((Image->ImageContext.PdbPointer[Index] == '\\') || (Image->ImageContext.PdbPointer[Index] == '/')) {
751 StartIndex = Index + 1;
752 }
753 }
754 //
755 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
756 // The PDB file name is limited in the range of 0~255.
757 // If the length is bigger than 255, trim the redudant characters to avoid overflow in array boundary.
758 //
759 for (Index = 0; Index < sizeof (EfiFileName) - 4; Index++) {
760 EfiFileName[Index] = Image->ImageContext.PdbPointer[Index + StartIndex];
761 if (EfiFileName[Index] == 0) {
762 EfiFileName[Index] = '.';
763 }
764 if (EfiFileName[Index] == '.') {
765 EfiFileName[Index + 1] = 'e';
766 EfiFileName[Index + 2] = 'f';
767 EfiFileName[Index + 3] = 'i';
768 EfiFileName[Index + 4] = 0;
769 break;
770 }
771 }
772
773 if (Index == sizeof (EfiFileName) - 4) {
774 EfiFileName[Index] = 0;
775 }
776 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex]));
777 }
778 DEBUG ((DEBUG_INFO | DEBUG_LOAD, "\n"));
779
780 DEBUG_CODE_END ();
781
782 return EFI_SUCCESS;
783
784 Done:
785
786 //
787 // Free memory.
788 //
789
790 if (DstBufAlocated) {
791 CoreFreePages (Image->ImageContext.ImageAddress, Image->NumberOfPages);
792 }
793
794 if (Image->ImageContext.FixupData != NULL) {
795 CoreFreePool (Image->ImageContext.FixupData);
796 }
797
798 return Status;
799 }
800
801
802
803 /**
804 Get the image's private data from its handle.
805
806 @param ImageHandle The image handle
807
808 @return Return the image private data associated with ImageHandle.
809
810 **/
811 LOADED_IMAGE_PRIVATE_DATA *
812 CoreLoadedImageInfo (
813 IN EFI_HANDLE ImageHandle
814 )
815 {
816 EFI_STATUS Status;
817 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
818 LOADED_IMAGE_PRIVATE_DATA *Image;
819
820 Status = CoreHandleProtocol (
821 ImageHandle,
822 &gEfiLoadedImageProtocolGuid,
823 (VOID **)&LoadedImage
824 );
825 if (!EFI_ERROR (Status)) {
826 Image = LOADED_IMAGE_PRIVATE_DATA_FROM_THIS (LoadedImage);
827 } else {
828 DEBUG ((DEBUG_LOAD, "CoreLoadedImageInfo: Not an ImageHandle %p\n", ImageHandle));
829 Image = NULL;
830 }
831
832 return Image;
833 }
834
835
836 /**
837 Unloads EFI image from memory.
838
839 @param Image EFI image
840 @param FreePage Free allocated pages
841
842 **/
843 VOID
844 CoreUnloadAndCloseImage (
845 IN LOADED_IMAGE_PRIVATE_DATA *Image,
846 IN BOOLEAN FreePage
847 )
848 {
849 EFI_STATUS Status;
850 UINTN HandleCount;
851 EFI_HANDLE *HandleBuffer;
852 UINTN HandleIndex;
853 EFI_GUID **ProtocolGuidArray;
854 UINTN ArrayCount;
855 UINTN ProtocolIndex;
856 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo;
857 UINTN OpenInfoCount;
858 UINTN OpenInfoIndex;
859
860 HandleBuffer = NULL;
861 ProtocolGuidArray = NULL;
862
863 if (Image->Started) {
864 UnregisterMemoryProfileImage (Image);
865 }
866
867 UnprotectUefiImage (&Image->Info, Image->LoadedImageDevicePath);
868
869 if (Image->Ebc != NULL) {
870 //
871 // If EBC protocol exists we must perform cleanups for this image.
872 //
873 Image->Ebc->UnloadImage (Image->Ebc, Image->Handle);
874 }
875
876 //
877 // Unload image, free Image->ImageContext->ModHandle
878 //
879 PeCoffLoaderUnloadImage (&Image->ImageContext);
880
881 //
882 // Free our references to the image handle
883 //
884 if (Image->Handle != NULL) {
885
886 Status = CoreLocateHandleBuffer (
887 AllHandles,
888 NULL,
889 NULL,
890 &HandleCount,
891 &HandleBuffer
892 );
893 if (!EFI_ERROR (Status)) {
894 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
895 Status = CoreProtocolsPerHandle (
896 HandleBuffer[HandleIndex],
897 &ProtocolGuidArray,
898 &ArrayCount
899 );
900 if (!EFI_ERROR (Status)) {
901 for (ProtocolIndex = 0; ProtocolIndex < ArrayCount; ProtocolIndex++) {
902 Status = CoreOpenProtocolInformation (
903 HandleBuffer[HandleIndex],
904 ProtocolGuidArray[ProtocolIndex],
905 &OpenInfo,
906 &OpenInfoCount
907 );
908 if (!EFI_ERROR (Status)) {
909 for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) {
910 if (OpenInfo[OpenInfoIndex].AgentHandle == Image->Handle) {
911 Status = CoreCloseProtocol (
912 HandleBuffer[HandleIndex],
913 ProtocolGuidArray[ProtocolIndex],
914 Image->Handle,
915 OpenInfo[OpenInfoIndex].ControllerHandle
916 );
917 }
918 }
919 if (OpenInfo != NULL) {
920 CoreFreePool(OpenInfo);
921 }
922 }
923 }
924 if (ProtocolGuidArray != NULL) {
925 CoreFreePool(ProtocolGuidArray);
926 }
927 }
928 }
929 if (HandleBuffer != NULL) {
930 CoreFreePool (HandleBuffer);
931 }
932 }
933
934 CoreRemoveDebugImageInfoEntry (Image->Handle);
935
936 Status = CoreUninstallProtocolInterface (
937 Image->Handle,
938 &gEfiLoadedImageDevicePathProtocolGuid,
939 Image->LoadedImageDevicePath
940 );
941
942 Status = CoreUninstallProtocolInterface (
943 Image->Handle,
944 &gEfiLoadedImageProtocolGuid,
945 &Image->Info
946 );
947
948 if (Image->ImageContext.HiiResourceData != 0) {
949 Status = CoreUninstallProtocolInterface (
950 Image->Handle,
951 &gEfiHiiPackageListProtocolGuid,
952 (VOID *) (UINTN) Image->ImageContext.HiiResourceData
953 );
954 }
955
956 }
957
958 if (Image->RuntimeData != NULL) {
959 if (Image->RuntimeData->Link.ForwardLink != NULL) {
960 //
961 // Remove the Image from the Runtime Image list as we are about to Free it!
962 //
963 RemoveEntryList (&Image->RuntimeData->Link);
964 RemoveImageRecord (Image->RuntimeData);
965 }
966 CoreFreePool (Image->RuntimeData);
967 }
968
969 //
970 // Free the Image from memory
971 //
972 if ((Image->ImageBasePage != 0) && FreePage) {
973 CoreFreePages (Image->ImageBasePage, Image->NumberOfPages);
974 }
975
976 //
977 // Done with the Image structure
978 //
979 if (Image->Info.FilePath != NULL) {
980 CoreFreePool (Image->Info.FilePath);
981 }
982
983 if (Image->LoadedImageDevicePath != NULL) {
984 CoreFreePool (Image->LoadedImageDevicePath);
985 }
986
987 if (Image->FixupData != NULL) {
988 CoreFreePool (Image->FixupData);
989 }
990
991 CoreFreePool (Image);
992 }
993
994
995 /**
996 Loads an EFI image into memory and returns a handle to the image.
997
998 @param BootPolicy If TRUE, indicates that the request originates
999 from the boot manager, and that the boot
1000 manager is attempting to load FilePath as a
1001 boot selection.
1002 @param ParentImageHandle The caller's image handle.
1003 @param FilePath The specific file path from which the image is
1004 loaded.
1005 @param SourceBuffer If not NULL, a pointer to the memory location
1006 containing a copy of the image to be loaded.
1007 @param SourceSize The size in bytes of SourceBuffer.
1008 @param DstBuffer The buffer to store the image
1009 @param NumberOfPages If not NULL, it inputs a pointer to the page
1010 number of DstBuffer and outputs a pointer to
1011 the page number of the image. If this number is
1012 not enough, return EFI_BUFFER_TOO_SMALL and
1013 this parameter contains the required number.
1014 @param ImageHandle Pointer to the returned image handle that is
1015 created when the image is successfully loaded.
1016 @param EntryPoint A pointer to the entry point
1017 @param Attribute The bit mask of attributes to set for the load
1018 PE image
1019
1020 @retval EFI_SUCCESS The image was loaded into memory.
1021 @retval EFI_NOT_FOUND The FilePath was not found.
1022 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1023 @retval EFI_BUFFER_TOO_SMALL The buffer is too small
1024 @retval EFI_UNSUPPORTED The image type is not supported, or the device
1025 path cannot be parsed to locate the proper
1026 protocol for loading the file.
1027 @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient
1028 resources.
1029 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
1030 understood.
1031 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
1032 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
1033 image from being loaded. NULL is returned in *ImageHandle.
1034 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
1035 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
1036 platform policy specifies that the image should not be started.
1037
1038 **/
1039 EFI_STATUS
1040 CoreLoadImageCommon (
1041 IN BOOLEAN BootPolicy,
1042 IN EFI_HANDLE ParentImageHandle,
1043 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1044 IN VOID *SourceBuffer OPTIONAL,
1045 IN UINTN SourceSize,
1046 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
1047 IN OUT UINTN *NumberOfPages OPTIONAL,
1048 OUT EFI_HANDLE *ImageHandle,
1049 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
1050 IN UINT32 Attribute
1051 )
1052 {
1053 LOADED_IMAGE_PRIVATE_DATA *Image;
1054 LOADED_IMAGE_PRIVATE_DATA *ParentImage;
1055 IMAGE_FILE_HANDLE FHand;
1056 EFI_STATUS Status;
1057 EFI_STATUS SecurityStatus;
1058 EFI_HANDLE DeviceHandle;
1059 UINT32 AuthenticationStatus;
1060 EFI_DEVICE_PATH_PROTOCOL *OriginalFilePath;
1061 EFI_DEVICE_PATH_PROTOCOL *HandleFilePath;
1062 EFI_DEVICE_PATH_PROTOCOL *InputFilePath;
1063 EFI_DEVICE_PATH_PROTOCOL *Node;
1064 UINTN FilePathSize;
1065 BOOLEAN ImageIsFromFv;
1066 BOOLEAN ImageIsFromLoadFile;
1067
1068 SecurityStatus = EFI_SUCCESS;
1069
1070 ASSERT (gEfiCurrentTpl < TPL_NOTIFY);
1071 ParentImage = NULL;
1072
1073 //
1074 // The caller must pass in a valid ParentImageHandle
1075 //
1076 if (ImageHandle == NULL || ParentImageHandle == NULL) {
1077 return EFI_INVALID_PARAMETER;
1078 }
1079
1080 ParentImage = CoreLoadedImageInfo (ParentImageHandle);
1081 if (ParentImage == NULL) {
1082 DEBUG((DEBUG_LOAD|DEBUG_ERROR, "LoadImageEx: Parent handle not an image handle\n"));
1083 return EFI_INVALID_PARAMETER;
1084 }
1085
1086 ZeroMem (&FHand, sizeof (IMAGE_FILE_HANDLE));
1087 FHand.Signature = IMAGE_FILE_HANDLE_SIGNATURE;
1088 OriginalFilePath = FilePath;
1089 InputFilePath = FilePath;
1090 HandleFilePath = FilePath;
1091 DeviceHandle = NULL;
1092 Status = EFI_SUCCESS;
1093 AuthenticationStatus = 0;
1094 ImageIsFromFv = FALSE;
1095 ImageIsFromLoadFile = FALSE;
1096
1097 //
1098 // If the caller passed a copy of the file, then just use it
1099 //
1100 if (SourceBuffer != NULL) {
1101 FHand.Source = SourceBuffer;
1102 FHand.SourceSize = SourceSize;
1103 Status = CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &HandleFilePath, &DeviceHandle);
1104 if (EFI_ERROR (Status)) {
1105 DeviceHandle = NULL;
1106 }
1107 if (SourceSize > 0) {
1108 Status = EFI_SUCCESS;
1109 } else {
1110 Status = EFI_LOAD_ERROR;
1111 }
1112 } else {
1113 if (FilePath == NULL) {
1114 return EFI_INVALID_PARAMETER;
1115 }
1116
1117 //
1118 // Try to get the image device handle by checking the match protocol.
1119 //
1120 Node = NULL;
1121 Status = CoreLocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &HandleFilePath, &DeviceHandle);
1122 if (!EFI_ERROR (Status)) {
1123 ImageIsFromFv = TRUE;
1124 } else {
1125 HandleFilePath = FilePath;
1126 Status = CoreLocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &HandleFilePath, &DeviceHandle);
1127 if (EFI_ERROR (Status)) {
1128 if (!BootPolicy) {
1129 HandleFilePath = FilePath;
1130 Status = CoreLocateDevicePath (&gEfiLoadFile2ProtocolGuid, &HandleFilePath, &DeviceHandle);
1131 }
1132 if (EFI_ERROR (Status)) {
1133 HandleFilePath = FilePath;
1134 Status = CoreLocateDevicePath (&gEfiLoadFileProtocolGuid, &HandleFilePath, &DeviceHandle);
1135 if (!EFI_ERROR (Status)) {
1136 ImageIsFromLoadFile = TRUE;
1137 Node = HandleFilePath;
1138 }
1139 }
1140 }
1141 }
1142
1143 //
1144 // Get the source file buffer by its device path.
1145 //
1146 FHand.Source = GetFileBufferByFilePath (
1147 BootPolicy,
1148 FilePath,
1149 &FHand.SourceSize,
1150 &AuthenticationStatus
1151 );
1152 if (FHand.Source == NULL) {
1153 Status = EFI_NOT_FOUND;
1154 } else {
1155 FHand.FreeBuffer = TRUE;
1156 if (ImageIsFromLoadFile) {
1157 //
1158 // LoadFile () may cause the device path of the Handle be updated.
1159 //
1160 OriginalFilePath = AppendDevicePath (DevicePathFromHandle (DeviceHandle), Node);
1161 }
1162 }
1163 }
1164
1165 if (EFI_ERROR (Status)) {
1166 Image = NULL;
1167 goto Done;
1168 }
1169
1170 if (gSecurity2 != NULL) {
1171 //
1172 // Verify File Authentication through the Security2 Architectural Protocol
1173 //
1174 SecurityStatus = gSecurity2->FileAuthentication (
1175 gSecurity2,
1176 OriginalFilePath,
1177 FHand.Source,
1178 FHand.SourceSize,
1179 BootPolicy
1180 );
1181 if (!EFI_ERROR (SecurityStatus) && ImageIsFromFv) {
1182 //
1183 // When Security2 is installed, Security Architectural Protocol must be published.
1184 //
1185 ASSERT (gSecurity != NULL);
1186
1187 //
1188 // Verify the Authentication Status through the Security Architectural Protocol
1189 // Only on images that have been read using Firmware Volume protocol.
1190 //
1191 SecurityStatus = gSecurity->FileAuthenticationState (
1192 gSecurity,
1193 AuthenticationStatus,
1194 OriginalFilePath
1195 );
1196 }
1197 } else if ((gSecurity != NULL) && (OriginalFilePath != NULL)) {
1198 //
1199 // Verify the Authentication Status through the Security Architectural Protocol
1200 //
1201 SecurityStatus = gSecurity->FileAuthenticationState (
1202 gSecurity,
1203 AuthenticationStatus,
1204 OriginalFilePath
1205 );
1206 }
1207
1208 //
1209 // Check Security Status.
1210 //
1211 if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {
1212 if (SecurityStatus == EFI_ACCESS_DENIED) {
1213 //
1214 // Image was not loaded because the platform policy prohibits the image from being loaded.
1215 // It's the only place we could meet EFI_ACCESS_DENIED.
1216 //
1217 *ImageHandle = NULL;
1218 }
1219 Status = SecurityStatus;
1220 Image = NULL;
1221 goto Done;
1222 }
1223
1224 //
1225 // Allocate a new image structure
1226 //
1227 Image = AllocateZeroPool (sizeof(LOADED_IMAGE_PRIVATE_DATA));
1228 if (Image == NULL) {
1229 Status = EFI_OUT_OF_RESOURCES;
1230 goto Done;
1231 }
1232
1233 //
1234 // Pull out just the file portion of the DevicePath for the LoadedImage FilePath
1235 //
1236 FilePath = OriginalFilePath;
1237 if (DeviceHandle != NULL) {
1238 Status = CoreHandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);
1239 if (!EFI_ERROR (Status)) {
1240 FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
1241 FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize );
1242 }
1243 }
1244 //
1245 // Initialize the fields for an internal driver
1246 //
1247 Image->Signature = LOADED_IMAGE_PRIVATE_DATA_SIGNATURE;
1248 Image->Info.SystemTable = gDxeCoreST;
1249 Image->Info.DeviceHandle = DeviceHandle;
1250 Image->Info.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
1251 Image->Info.FilePath = DuplicateDevicePath (FilePath);
1252 Image->Info.ParentHandle = ParentImageHandle;
1253
1254
1255 if (NumberOfPages != NULL) {
1256 Image->NumberOfPages = *NumberOfPages ;
1257 } else {
1258 Image->NumberOfPages = 0 ;
1259 }
1260
1261 //
1262 // Install the protocol interfaces for this image
1263 // don't fire notifications yet
1264 //
1265 Status = CoreInstallProtocolInterfaceNotify (
1266 &Image->Handle,
1267 &gEfiLoadedImageProtocolGuid,
1268 EFI_NATIVE_INTERFACE,
1269 &Image->Info,
1270 FALSE
1271 );
1272 if (EFI_ERROR (Status)) {
1273 goto Done;
1274 }
1275
1276 //
1277 // Load the image. If EntryPoint is Null, it will not be set.
1278 //
1279 Status = CoreLoadPeImage (BootPolicy, &FHand, Image, DstBuffer, EntryPoint, Attribute);
1280 if (EFI_ERROR (Status)) {
1281 if ((Status == EFI_BUFFER_TOO_SMALL) || (Status == EFI_OUT_OF_RESOURCES)) {
1282 if (NumberOfPages != NULL) {
1283 *NumberOfPages = Image->NumberOfPages;
1284 }
1285 }
1286 goto Done;
1287 }
1288
1289 if (NumberOfPages != NULL) {
1290 *NumberOfPages = Image->NumberOfPages;
1291 }
1292
1293 //
1294 // Register the image in the Debug Image Info Table if the attribute is set
1295 //
1296 if ((Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION) != 0) {
1297 CoreNewDebugImageInfoEntry (EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, &Image->Info, Image->Handle);
1298 }
1299
1300 //
1301 //Reinstall loaded image protocol to fire any notifications
1302 //
1303 Status = CoreReinstallProtocolInterface (
1304 Image->Handle,
1305 &gEfiLoadedImageProtocolGuid,
1306 &Image->Info,
1307 &Image->Info
1308 );
1309 if (EFI_ERROR (Status)) {
1310 goto Done;
1311 }
1312
1313 //
1314 // If DevicePath parameter to the LoadImage() is not NULL, then make a copy of DevicePath,
1315 // otherwise Loaded Image Device Path Protocol is installed with a NULL interface pointer.
1316 //
1317 if (OriginalFilePath != NULL) {
1318 Image->LoadedImageDevicePath = DuplicateDevicePath (OriginalFilePath);
1319 }
1320
1321 //
1322 // Install Loaded Image Device Path Protocol onto the image handle of a PE/COFE image
1323 //
1324 Status = CoreInstallProtocolInterface (
1325 &Image->Handle,
1326 &gEfiLoadedImageDevicePathProtocolGuid,
1327 EFI_NATIVE_INTERFACE,
1328 Image->LoadedImageDevicePath
1329 );
1330 if (EFI_ERROR (Status)) {
1331 goto Done;
1332 }
1333
1334 //
1335 // Install HII Package List Protocol onto the image handle
1336 //
1337 if (Image->ImageContext.HiiResourceData != 0) {
1338 Status = CoreInstallProtocolInterface (
1339 &Image->Handle,
1340 &gEfiHiiPackageListProtocolGuid,
1341 EFI_NATIVE_INTERFACE,
1342 (VOID *) (UINTN) Image->ImageContext.HiiResourceData
1343 );
1344 if (EFI_ERROR (Status)) {
1345 goto Done;
1346 }
1347 }
1348 ProtectUefiImage (&Image->Info, Image->LoadedImageDevicePath);
1349
1350 //
1351 // Success. Return the image handle
1352 //
1353 *ImageHandle = Image->Handle;
1354
1355 Done:
1356 //
1357 // All done accessing the source file
1358 // If we allocated the Source buffer, free it
1359 //
1360 if (FHand.FreeBuffer) {
1361 CoreFreePool (FHand.Source);
1362 }
1363 if (OriginalFilePath != InputFilePath) {
1364 CoreFreePool (OriginalFilePath);
1365 }
1366
1367 //
1368 // There was an error. If there's an Image structure, free it
1369 //
1370 if (EFI_ERROR (Status)) {
1371 if (Image != NULL) {
1372 CoreUnloadAndCloseImage (Image, (BOOLEAN)(DstBuffer == 0));
1373 Image = NULL;
1374 }
1375 } else if (EFI_ERROR (SecurityStatus)) {
1376 Status = SecurityStatus;
1377 }
1378
1379 //
1380 // Track the return status from LoadImage.
1381 //
1382 if (Image != NULL) {
1383 Image->LoadImageStatus = Status;
1384 }
1385
1386 return Status;
1387 }
1388
1389
1390
1391
1392 /**
1393 Loads an EFI image into memory and returns a handle to the image.
1394
1395 @param BootPolicy If TRUE, indicates that the request originates
1396 from the boot manager, and that the boot
1397 manager is attempting to load FilePath as a
1398 boot selection.
1399 @param ParentImageHandle The caller's image handle.
1400 @param FilePath The specific file path from which the image is
1401 loaded.
1402 @param SourceBuffer If not NULL, a pointer to the memory location
1403 containing a copy of the image to be loaded.
1404 @param SourceSize The size in bytes of SourceBuffer.
1405 @param ImageHandle Pointer to the returned image handle that is
1406 created when the image is successfully loaded.
1407
1408 @retval EFI_SUCCESS The image was loaded into memory.
1409 @retval EFI_NOT_FOUND The FilePath was not found.
1410 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1411 @retval EFI_UNSUPPORTED The image type is not supported, or the device
1412 path cannot be parsed to locate the proper
1413 protocol for loading the file.
1414 @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient
1415 resources.
1416 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
1417 understood.
1418 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
1419 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
1420 image from being loaded. NULL is returned in *ImageHandle.
1421 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
1422 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
1423 platform policy specifies that the image should not be started.
1424
1425 **/
1426 EFI_STATUS
1427 EFIAPI
1428 CoreLoadImage (
1429 IN BOOLEAN BootPolicy,
1430 IN EFI_HANDLE ParentImageHandle,
1431 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1432 IN VOID *SourceBuffer OPTIONAL,
1433 IN UINTN SourceSize,
1434 OUT EFI_HANDLE *ImageHandle
1435 )
1436 {
1437 EFI_STATUS Status;
1438 UINT64 Tick;
1439 EFI_HANDLE Handle;
1440
1441 Tick = 0;
1442 PERF_CODE (
1443 Tick = GetPerformanceCounter ();
1444 );
1445
1446 Status = CoreLoadImageCommon (
1447 BootPolicy,
1448 ParentImageHandle,
1449 FilePath,
1450 SourceBuffer,
1451 SourceSize,
1452 (EFI_PHYSICAL_ADDRESS) (UINTN) NULL,
1453 NULL,
1454 ImageHandle,
1455 NULL,
1456 EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION | EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION
1457 );
1458
1459 Handle = NULL;
1460 if (!EFI_ERROR (Status)) {
1461 //
1462 // ImageHandle will be valid only Status is success.
1463 //
1464 Handle = *ImageHandle;
1465 }
1466
1467 PERF_START (Handle, "LoadImage:", NULL, Tick);
1468 PERF_END (Handle, "LoadImage:", NULL, 0);
1469
1470 return Status;
1471 }
1472
1473
1474
1475 /**
1476 Loads an EFI image into memory and returns a handle to the image with extended parameters.
1477
1478 @param This Calling context
1479 @param ParentImageHandle The caller's image handle.
1480 @param FilePath The specific file path from which the image is
1481 loaded.
1482 @param SourceBuffer If not NULL, a pointer to the memory location
1483 containing a copy of the image to be loaded.
1484 @param SourceSize The size in bytes of SourceBuffer.
1485 @param DstBuffer The buffer to store the image.
1486 @param NumberOfPages For input, specifies the space size of the
1487 image by caller if not NULL. For output,
1488 specifies the actual space size needed.
1489 @param ImageHandle Image handle for output.
1490 @param EntryPoint Image entry point for output.
1491 @param Attribute The bit mask of attributes to set for the load
1492 PE image.
1493
1494 @retval EFI_SUCCESS The image was loaded into memory.
1495 @retval EFI_NOT_FOUND The FilePath was not found.
1496 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1497 @retval EFI_UNSUPPORTED The image type is not supported, or the device
1498 path cannot be parsed to locate the proper
1499 protocol for loading the file.
1500 @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient
1501 resources.
1502 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
1503 understood.
1504 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
1505 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
1506 image from being loaded. NULL is returned in *ImageHandle.
1507 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
1508 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
1509 platform policy specifies that the image should not be started.
1510
1511 **/
1512 EFI_STATUS
1513 EFIAPI
1514 CoreLoadImageEx (
1515 IN EFI_PE32_IMAGE_PROTOCOL *This,
1516 IN EFI_HANDLE ParentImageHandle,
1517 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1518 IN VOID *SourceBuffer OPTIONAL,
1519 IN UINTN SourceSize,
1520 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
1521 OUT UINTN *NumberOfPages OPTIONAL,
1522 OUT EFI_HANDLE *ImageHandle,
1523 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
1524 IN UINT32 Attribute
1525 )
1526 {
1527 EFI_STATUS Status;
1528 UINT64 Tick;
1529 EFI_HANDLE Handle;
1530
1531 Tick = 0;
1532 PERF_CODE (
1533 Tick = GetPerformanceCounter ();
1534 );
1535
1536 Status = CoreLoadImageCommon (
1537 TRUE,
1538 ParentImageHandle,
1539 FilePath,
1540 SourceBuffer,
1541 SourceSize,
1542 DstBuffer,
1543 NumberOfPages,
1544 ImageHandle,
1545 EntryPoint,
1546 Attribute
1547 );
1548
1549 Handle = NULL;
1550 if (!EFI_ERROR (Status)) {
1551 //
1552 // ImageHandle will be valid only Status is success.
1553 //
1554 Handle = *ImageHandle;
1555 }
1556
1557 PERF_START (Handle, "LoadImage:", NULL, Tick);
1558 PERF_END (Handle, "LoadImage:", NULL, 0);
1559
1560 return Status;
1561 }
1562
1563
1564 /**
1565 Transfer control to a loaded image's entry point.
1566
1567 @param ImageHandle Handle of image to be started.
1568 @param ExitDataSize Pointer of the size to ExitData
1569 @param ExitData Pointer to a pointer to a data buffer that
1570 includes a Null-terminated string,
1571 optionally followed by additional binary data.
1572 The string is a description that the caller may
1573 use to further indicate the reason for the
1574 image's exit.
1575
1576 @retval EFI_INVALID_PARAMETER Invalid parameter
1577 @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate
1578 @retval EFI_SECURITY_VIOLATION The current platform policy specifies that the image should not be started.
1579 @retval EFI_SUCCESS Successfully transfer control to the image's
1580 entry point.
1581
1582 **/
1583 EFI_STATUS
1584 EFIAPI
1585 CoreStartImage (
1586 IN EFI_HANDLE ImageHandle,
1587 OUT UINTN *ExitDataSize,
1588 OUT CHAR16 **ExitData OPTIONAL
1589 )
1590 {
1591 EFI_STATUS Status;
1592 LOADED_IMAGE_PRIVATE_DATA *Image;
1593 LOADED_IMAGE_PRIVATE_DATA *LastImage;
1594 UINT64 HandleDatabaseKey;
1595 UINTN SetJumpFlag;
1596 UINT64 Tick;
1597 EFI_HANDLE Handle;
1598
1599 Tick = 0;
1600 Handle = ImageHandle;
1601
1602 Image = CoreLoadedImageInfo (ImageHandle);
1603 if (Image == NULL || Image->Started) {
1604 return EFI_INVALID_PARAMETER;
1605 }
1606 if (EFI_ERROR (Image->LoadImageStatus)) {
1607 return Image->LoadImageStatus;
1608 }
1609
1610 //
1611 // The image to be started must have the machine type supported by DxeCore.
1612 //
1613 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->Machine)) {
1614 //
1615 // Do not ASSERT here, because image might be loaded via EFI_IMAGE_MACHINE_CROSS_TYPE_SUPPORTED
1616 // But it can not be started.
1617 //
1618 DEBUG ((EFI_D_ERROR, "Image type %s can't be started ", GetMachineTypeName(Image->Machine)));
1619 DEBUG ((EFI_D_ERROR, "on %s UEFI system.\n", GetMachineTypeName(mDxeCoreImageMachineType)));
1620 return EFI_UNSUPPORTED;
1621 }
1622
1623 PERF_CODE (
1624 Tick = GetPerformanceCounter ();
1625 );
1626
1627
1628 //
1629 // Push the current start image context, and
1630 // link the current image to the head. This is the
1631 // only image that can call Exit()
1632 //
1633 HandleDatabaseKey = CoreGetHandleDatabaseKey ();
1634 LastImage = mCurrentImage;
1635 mCurrentImage = Image;
1636 Image->Tpl = gEfiCurrentTpl;
1637
1638 //
1639 // Set long jump for Exit() support
1640 // JumpContext must be aligned on a CPU specific boundary.
1641 // Overallocate the buffer and force the required alignment
1642 //
1643 Image->JumpBuffer = AllocatePool (sizeof (BASE_LIBRARY_JUMP_BUFFER) + BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
1644 if (Image->JumpBuffer == NULL) {
1645 //
1646 // Image may be unloaded after return with failure,
1647 // then ImageHandle may be invalid, so use NULL handle to record perf log.
1648 //
1649 PERF_START (NULL, "StartImage:", NULL, Tick);
1650 PERF_END (NULL, "StartImage:", NULL, 0);
1651 return EFI_OUT_OF_RESOURCES;
1652 }
1653 Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
1654
1655 SetJumpFlag = SetJump (Image->JumpContext);
1656 //
1657 // The initial call to SetJump() must always return 0.
1658 // Subsequent calls to LongJump() cause a non-zero value to be returned by SetJump().
1659 //
1660 if (SetJumpFlag == 0) {
1661 RegisterMemoryProfileImage (Image, (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION ? EFI_FV_FILETYPE_APPLICATION : EFI_FV_FILETYPE_DRIVER));
1662 //
1663 // Call the image's entry point
1664 //
1665 Image->Started = TRUE;
1666 Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable);
1667
1668 //
1669 // Add some debug information if the image returned with error.
1670 // This make the user aware and check if the driver image have already released
1671 // all the resource in this situation.
1672 //
1673 DEBUG_CODE_BEGIN ();
1674 if (EFI_ERROR (Image->Status)) {
1675 DEBUG ((DEBUG_ERROR, "Error: Image at %11p start failed: %r\n", Image->Info.ImageBase, Image->Status));
1676 }
1677 DEBUG_CODE_END ();
1678
1679 //
1680 // If the image returns, exit it through Exit()
1681 //
1682 CoreExit (ImageHandle, Image->Status, 0, NULL);
1683 }
1684
1685 //
1686 // Image has completed. Verify the tpl is the same
1687 //
1688 ASSERT (Image->Tpl == gEfiCurrentTpl);
1689 CoreRestoreTpl (Image->Tpl);
1690
1691 CoreFreePool (Image->JumpBuffer);
1692
1693 //
1694 // Pop the current start image context
1695 //
1696 mCurrentImage = LastImage;
1697
1698 //
1699 // Go connect any handles that were created or modified while the image executed.
1700 //
1701 CoreConnectHandlesByKey (HandleDatabaseKey);
1702
1703 //
1704 // Handle the image's returned ExitData
1705 //
1706 DEBUG_CODE_BEGIN ();
1707 if (Image->ExitDataSize != 0 || Image->ExitData != NULL) {
1708
1709 DEBUG ((DEBUG_LOAD, "StartImage: ExitDataSize %d, ExitData %p", (UINT32)Image->ExitDataSize, Image->ExitData));
1710 if (Image->ExitData != NULL) {
1711 DEBUG ((DEBUG_LOAD, " (%hs)", Image->ExitData));
1712 }
1713 DEBUG ((DEBUG_LOAD, "\n"));
1714 }
1715 DEBUG_CODE_END ();
1716
1717 //
1718 // Return the exit data to the caller
1719 //
1720 if (ExitData != NULL && ExitDataSize != NULL) {
1721 *ExitDataSize = Image->ExitDataSize;
1722 *ExitData = Image->ExitData;
1723 } else {
1724 //
1725 // Caller doesn't want the exit data, free it
1726 //
1727 CoreFreePool (Image->ExitData);
1728 Image->ExitData = NULL;
1729 }
1730
1731 //
1732 // Save the Status because Image will get destroyed if it is unloaded.
1733 //
1734 Status = Image->Status;
1735
1736 //
1737 // If the image returned an error, or if the image is an application
1738 // unload it
1739 //
1740 if (EFI_ERROR (Image->Status) || Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1741 CoreUnloadAndCloseImage (Image, TRUE);
1742 //
1743 // ImageHandle may be invalid after the image is unloaded, so use NULL handle to record perf log.
1744 //
1745 Handle = NULL;
1746 }
1747
1748 //
1749 // Done
1750 //
1751 PERF_START (Handle, "StartImage:", NULL, Tick);
1752 PERF_END (Handle, "StartImage:", NULL, 0);
1753 return Status;
1754 }
1755
1756 /**
1757 Terminates the currently loaded EFI image and returns control to boot services.
1758
1759 @param ImageHandle Handle that identifies the image. This
1760 parameter is passed to the image on entry.
1761 @param Status The image's exit code.
1762 @param ExitDataSize The size, in bytes, of ExitData. Ignored if
1763 ExitStatus is EFI_SUCCESS.
1764 @param ExitData Pointer to a data buffer that includes a
1765 Null-terminated Unicode string, optionally
1766 followed by additional binary data. The string
1767 is a description that the caller may use to
1768 further indicate the reason for the image's
1769 exit.
1770
1771 @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current
1772 image.
1773 @retval EFI_SUCCESS Successfully terminates the currently loaded
1774 EFI image.
1775 @retval EFI_ACCESS_DENIED Should never reach there.
1776 @retval EFI_OUT_OF_RESOURCES Could not allocate pool
1777
1778 **/
1779 EFI_STATUS
1780 EFIAPI
1781 CoreExit (
1782 IN EFI_HANDLE ImageHandle,
1783 IN EFI_STATUS Status,
1784 IN UINTN ExitDataSize,
1785 IN CHAR16 *ExitData OPTIONAL
1786 )
1787 {
1788 LOADED_IMAGE_PRIVATE_DATA *Image;
1789 EFI_TPL OldTpl;
1790
1791 //
1792 // Prevent possible reentrance to this function
1793 // for the same ImageHandle
1794 //
1795 OldTpl = CoreRaiseTpl (TPL_NOTIFY);
1796
1797 Image = CoreLoadedImageInfo (ImageHandle);
1798 if (Image == NULL) {
1799 Status = EFI_INVALID_PARAMETER;
1800 goto Done;
1801 }
1802
1803 if (!Image->Started) {
1804 //
1805 // The image has not been started so just free its resources
1806 //
1807 CoreUnloadAndCloseImage (Image, TRUE);
1808 Status = EFI_SUCCESS;
1809 goto Done;
1810 }
1811
1812 //
1813 // Image has been started, verify this image can exit
1814 //
1815 if (Image != mCurrentImage) {
1816 DEBUG ((DEBUG_LOAD|DEBUG_ERROR, "Exit: Image is not exitable image\n"));
1817 Status = EFI_INVALID_PARAMETER;
1818 goto Done;
1819 }
1820
1821 //
1822 // Set status
1823 //
1824 Image->Status = Status;
1825
1826 //
1827 // If there's ExitData info, move it
1828 //
1829 if (ExitData != NULL) {
1830 Image->ExitDataSize = ExitDataSize;
1831 Image->ExitData = AllocatePool (Image->ExitDataSize);
1832 if (Image->ExitData == NULL) {
1833 Status = EFI_OUT_OF_RESOURCES;
1834 goto Done;
1835 }
1836 CopyMem (Image->ExitData, ExitData, Image->ExitDataSize);
1837 }
1838
1839 CoreRestoreTpl (OldTpl);
1840 //
1841 // return to StartImage
1842 //
1843 LongJump (Image->JumpContext, (UINTN)-1);
1844
1845 //
1846 // If we return from LongJump, then it is an error
1847 //
1848 ASSERT (FALSE);
1849 Status = EFI_ACCESS_DENIED;
1850 Done:
1851 CoreRestoreTpl (OldTpl);
1852 return Status;
1853 }
1854
1855
1856
1857
1858 /**
1859 Unloads an image.
1860
1861 @param ImageHandle Handle that identifies the image to be
1862 unloaded.
1863
1864 @retval EFI_SUCCESS The image has been unloaded.
1865 @retval EFI_UNSUPPORTED The image has been started, and does not support
1866 unload.
1867 @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle.
1868
1869 **/
1870 EFI_STATUS
1871 EFIAPI
1872 CoreUnloadImage (
1873 IN EFI_HANDLE ImageHandle
1874 )
1875 {
1876 EFI_STATUS Status;
1877 LOADED_IMAGE_PRIVATE_DATA *Image;
1878
1879 Image = CoreLoadedImageInfo (ImageHandle);
1880 if (Image == NULL ) {
1881 //
1882 // The image handle is not valid
1883 //
1884 Status = EFI_INVALID_PARAMETER;
1885 goto Done;
1886 }
1887
1888 if (Image->Started) {
1889 //
1890 // The image has been started, request it to unload.
1891 //
1892 Status = EFI_UNSUPPORTED;
1893 if (Image->Info.Unload != NULL) {
1894 Status = Image->Info.Unload (ImageHandle);
1895 }
1896
1897 } else {
1898 //
1899 // This Image hasn't been started, thus it can be unloaded
1900 //
1901 Status = EFI_SUCCESS;
1902 }
1903
1904
1905 if (!EFI_ERROR (Status)) {
1906 //
1907 // if the Image was not started or Unloaded O.K. then clean up
1908 //
1909 CoreUnloadAndCloseImage (Image, TRUE);
1910 }
1911
1912 Done:
1913 return Status;
1914 }
1915
1916
1917
1918 /**
1919 Unload the specified image.
1920
1921 @param This Indicates the calling context.
1922 @param ImageHandle The specified image handle.
1923
1924 @retval EFI_INVALID_PARAMETER Image handle is NULL.
1925 @retval EFI_UNSUPPORTED Attempt to unload an unsupported image.
1926 @retval EFI_SUCCESS Image successfully unloaded.
1927
1928 **/
1929 EFI_STATUS
1930 EFIAPI
1931 CoreUnloadImageEx (
1932 IN EFI_PE32_IMAGE_PROTOCOL *This,
1933 IN EFI_HANDLE ImageHandle
1934 )
1935 {
1936 return CoreUnloadImage (ImageHandle);
1937 }