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