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