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