]> git.proxmox.com Git - mirror_edk2.git/blob - MdeModulePkg/Core/Dxe/Image/Image.c
Updates function description per UEFI2.3d. No impact is for functionality. The main...
[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 - 2011, 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 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
963 understood.
964 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
965 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
966 image from being loaded. NULL is returned in *ImageHandle.
967 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
968 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
969 platform policy specifies that the image should not be started.
970
971 **/
972 EFI_STATUS
973 CoreLoadImageCommon (
974 IN BOOLEAN BootPolicy,
975 IN EFI_HANDLE ParentImageHandle,
976 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
977 IN VOID *SourceBuffer OPTIONAL,
978 IN UINTN SourceSize,
979 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
980 IN OUT UINTN *NumberOfPages OPTIONAL,
981 OUT EFI_HANDLE *ImageHandle,
982 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
983 IN UINT32 Attribute
984 )
985 {
986 LOADED_IMAGE_PRIVATE_DATA *Image;
987 LOADED_IMAGE_PRIVATE_DATA *ParentImage;
988 IMAGE_FILE_HANDLE FHand;
989 EFI_STATUS Status;
990 EFI_STATUS SecurityStatus;
991 EFI_HANDLE DeviceHandle;
992 UINT32 AuthenticationStatus;
993 EFI_DEVICE_PATH_PROTOCOL *OriginalFilePath;
994 EFI_DEVICE_PATH_PROTOCOL *HandleFilePath;
995 UINTN FilePathSize;
996
997 SecurityStatus = EFI_SUCCESS;
998
999 ASSERT (gEfiCurrentTpl < TPL_NOTIFY);
1000 ParentImage = NULL;
1001
1002 //
1003 // The caller must pass in a valid ParentImageHandle
1004 //
1005 if (ImageHandle == NULL || ParentImageHandle == NULL) {
1006 return EFI_INVALID_PARAMETER;
1007 }
1008
1009 ParentImage = CoreLoadedImageInfo (ParentImageHandle);
1010 if (ParentImage == NULL) {
1011 DEBUG((DEBUG_LOAD|DEBUG_ERROR, "LoadImageEx: Parent handle not an image handle\n"));
1012 return EFI_INVALID_PARAMETER;
1013 }
1014
1015 ZeroMem (&FHand, sizeof (IMAGE_FILE_HANDLE));
1016 FHand.Signature = IMAGE_FILE_HANDLE_SIGNATURE;
1017 OriginalFilePath = FilePath;
1018 HandleFilePath = FilePath;
1019 DeviceHandle = NULL;
1020 Status = EFI_SUCCESS;
1021 AuthenticationStatus = 0;
1022 //
1023 // If the caller passed a copy of the file, then just use it
1024 //
1025 if (SourceBuffer != NULL) {
1026 FHand.Source = SourceBuffer;
1027 FHand.SourceSize = SourceSize;
1028 CoreLocateDevicePath (&gEfiDevicePathProtocolGuid, &HandleFilePath, &DeviceHandle);
1029 if (SourceSize > 0) {
1030 Status = EFI_SUCCESS;
1031 } else {
1032 Status = EFI_LOAD_ERROR;
1033 }
1034 } else {
1035 if (FilePath == NULL) {
1036 return EFI_INVALID_PARAMETER;
1037 }
1038 //
1039 // Get the source file buffer by its device path.
1040 //
1041 FHand.Source = GetFileBufferByFilePath (
1042 BootPolicy,
1043 FilePath,
1044 &FHand.SourceSize,
1045 &AuthenticationStatus
1046 );
1047 if (FHand.Source == NULL) {
1048 Status = EFI_NOT_FOUND;
1049 } else {
1050 //
1051 // Try to get the image device handle by checking the match protocol.
1052 //
1053 FHand.FreeBuffer = TRUE;
1054 Status = CoreLocateDevicePath (&gEfiFirmwareVolume2ProtocolGuid, &HandleFilePath, &DeviceHandle);
1055 if (EFI_ERROR (Status)) {
1056 HandleFilePath = FilePath;
1057 Status = CoreLocateDevicePath (&gEfiSimpleFileSystemProtocolGuid, &HandleFilePath, &DeviceHandle);
1058 if (EFI_ERROR (Status)) {
1059 if (!BootPolicy) {
1060 HandleFilePath = FilePath;
1061 Status = CoreLocateDevicePath (&gEfiLoadFile2ProtocolGuid, &HandleFilePath, &DeviceHandle);
1062 }
1063 if (EFI_ERROR (Status)) {
1064 HandleFilePath = FilePath;
1065 Status = CoreLocateDevicePath (&gEfiLoadFileProtocolGuid, &HandleFilePath, &DeviceHandle);
1066 }
1067 }
1068 }
1069 }
1070 }
1071
1072 if (Status == EFI_ALREADY_STARTED) {
1073 Image = NULL;
1074 goto Done;
1075 } else if (EFI_ERROR (Status)) {
1076 return Status;
1077 }
1078
1079 //
1080 // Verify the Authentication Status through the Security Architectural Protocol
1081 //
1082 if ((gSecurity != NULL) && (OriginalFilePath != NULL)) {
1083 SecurityStatus = gSecurity->FileAuthenticationState (
1084 gSecurity,
1085 AuthenticationStatus,
1086 OriginalFilePath
1087 );
1088 if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {
1089 Status = SecurityStatus;
1090 Image = NULL;
1091 goto Done;
1092 }
1093 }
1094
1095
1096 //
1097 // Allocate a new image structure
1098 //
1099 Image = AllocateZeroPool (sizeof(LOADED_IMAGE_PRIVATE_DATA));
1100 if (Image == NULL) {
1101 return EFI_OUT_OF_RESOURCES;
1102 }
1103
1104 //
1105 // Pull out just the file portion of the DevicePath for the LoadedImage FilePath
1106 //
1107 FilePath = OriginalFilePath;
1108 if (DeviceHandle != NULL) {
1109 Status = CoreHandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);
1110 if (!EFI_ERROR (Status)) {
1111 FilePathSize = GetDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
1112 FilePath = (EFI_DEVICE_PATH_PROTOCOL *) (((UINT8 *)FilePath) + FilePathSize );
1113 }
1114 }
1115 //
1116 // Initialize the fields for an internal driver
1117 //
1118 Image->Signature = LOADED_IMAGE_PRIVATE_DATA_SIGNATURE;
1119 Image->Info.SystemTable = gDxeCoreST;
1120 Image->Info.DeviceHandle = DeviceHandle;
1121 Image->Info.Revision = EFI_LOADED_IMAGE_PROTOCOL_REVISION;
1122 Image->Info.FilePath = DuplicateDevicePath (FilePath);
1123 Image->Info.ParentHandle = ParentImageHandle;
1124
1125
1126 if (NumberOfPages != NULL) {
1127 Image->NumberOfPages = *NumberOfPages ;
1128 } else {
1129 Image->NumberOfPages = 0 ;
1130 }
1131
1132 //
1133 // Install the protocol interfaces for this image
1134 // don't fire notifications yet
1135 //
1136 Status = CoreInstallProtocolInterfaceNotify (
1137 &Image->Handle,
1138 &gEfiLoadedImageProtocolGuid,
1139 EFI_NATIVE_INTERFACE,
1140 &Image->Info,
1141 FALSE
1142 );
1143 if (EFI_ERROR (Status)) {
1144 goto Done;
1145 }
1146
1147 //
1148 // Load the image. If EntryPoint is Null, it will not be set.
1149 //
1150 Status = CoreLoadPeImage (BootPolicy, &FHand, Image, DstBuffer, EntryPoint, Attribute);
1151 if (EFI_ERROR (Status)) {
1152 if ((Status == EFI_BUFFER_TOO_SMALL) || (Status == EFI_OUT_OF_RESOURCES)) {
1153 if (NumberOfPages != NULL) {
1154 *NumberOfPages = Image->NumberOfPages;
1155 }
1156 }
1157 goto Done;
1158 }
1159
1160 if (NumberOfPages != NULL) {
1161 *NumberOfPages = Image->NumberOfPages;
1162 }
1163
1164 //
1165 // Register the image in the Debug Image Info Table if the attribute is set
1166 //
1167 if ((Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION) != 0) {
1168 CoreNewDebugImageInfoEntry (EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, &Image->Info, Image->Handle);
1169 }
1170
1171 //
1172 //Reinstall loaded image protocol to fire any notifications
1173 //
1174 Status = CoreReinstallProtocolInterface (
1175 Image->Handle,
1176 &gEfiLoadedImageProtocolGuid,
1177 &Image->Info,
1178 &Image->Info
1179 );
1180 if (EFI_ERROR (Status)) {
1181 goto Done;
1182 }
1183
1184 //
1185 // If DevicePath parameter to the LoadImage() is not NULL, then make a copy of DevicePath,
1186 // otherwise Loaded Image Device Path Protocol is installed with a NULL interface pointer.
1187 //
1188 if (OriginalFilePath != NULL) {
1189 Image->LoadedImageDevicePath = DuplicateDevicePath (OriginalFilePath);
1190 }
1191
1192 //
1193 // Install Loaded Image Device Path Protocol onto the image handle of a PE/COFE image
1194 //
1195 Status = CoreInstallProtocolInterface (
1196 &Image->Handle,
1197 &gEfiLoadedImageDevicePathProtocolGuid,
1198 EFI_NATIVE_INTERFACE,
1199 Image->LoadedImageDevicePath
1200 );
1201 if (EFI_ERROR (Status)) {
1202 goto Done;
1203 }
1204
1205 //
1206 // Install HII Package List Protocol onto the image handle
1207 //
1208 if (Image->ImageContext.HiiResourceData != 0) {
1209 Status = CoreInstallProtocolInterface (
1210 &Image->Handle,
1211 &gEfiHiiPackageListProtocolGuid,
1212 EFI_NATIVE_INTERFACE,
1213 (VOID *) (UINTN) Image->ImageContext.HiiResourceData
1214 );
1215 if (EFI_ERROR (Status)) {
1216 goto Done;
1217 }
1218 }
1219
1220 //
1221 // Success. Return the image handle
1222 //
1223 *ImageHandle = Image->Handle;
1224
1225 Done:
1226 //
1227 // All done accessing the source file
1228 // If we allocated the Source buffer, free it
1229 //
1230 if (FHand.FreeBuffer) {
1231 CoreFreePool (FHand.Source);
1232 }
1233
1234 //
1235 // There was an error. If there's an Image structure, free it
1236 //
1237 if (EFI_ERROR (Status)) {
1238 if (Image != NULL) {
1239 CoreUnloadAndCloseImage (Image, (BOOLEAN)(DstBuffer == 0));
1240 *ImageHandle = NULL;
1241 }
1242 } else if (EFI_ERROR (SecurityStatus)) {
1243 Status = SecurityStatus;
1244 }
1245
1246 return Status;
1247 }
1248
1249
1250
1251
1252 /**
1253 Loads an EFI image into memory and returns a handle to the image.
1254
1255 @param BootPolicy If TRUE, indicates that the request originates
1256 from the boot manager, and that the boot
1257 manager is attempting to load FilePath as a
1258 boot selection.
1259 @param ParentImageHandle The caller's image handle.
1260 @param FilePath The specific file path from which the image is
1261 loaded.
1262 @param SourceBuffer If not NULL, a pointer to the memory location
1263 containing a copy of the image to be loaded.
1264 @param SourceSize The size in bytes of SourceBuffer.
1265 @param ImageHandle Pointer to the returned image handle that is
1266 created when the image is successfully loaded.
1267
1268 @retval EFI_SUCCESS The image was loaded into memory.
1269 @retval EFI_NOT_FOUND The FilePath was not found.
1270 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1271 @retval EFI_UNSUPPORTED The image type is not supported, or the device
1272 path cannot be parsed to locate the proper
1273 protocol for loading the file.
1274 @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient
1275 resources.
1276 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
1277 understood.
1278 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
1279 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
1280 image from being loaded. NULL is returned in *ImageHandle.
1281 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
1282 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
1283 platform policy specifies that the image should not be started.
1284
1285 **/
1286 EFI_STATUS
1287 EFIAPI
1288 CoreLoadImage (
1289 IN BOOLEAN BootPolicy,
1290 IN EFI_HANDLE ParentImageHandle,
1291 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1292 IN VOID *SourceBuffer OPTIONAL,
1293 IN UINTN SourceSize,
1294 OUT EFI_HANDLE *ImageHandle
1295 )
1296 {
1297 EFI_STATUS Status;
1298 UINT64 Tick;
1299
1300 Tick = 0;
1301 PERF_CODE (
1302 Tick = GetPerformanceCounter ();
1303 );
1304
1305 Status = CoreLoadImageCommon (
1306 BootPolicy,
1307 ParentImageHandle,
1308 FilePath,
1309 SourceBuffer,
1310 SourceSize,
1311 (EFI_PHYSICAL_ADDRESS) (UINTN) NULL,
1312 NULL,
1313 ImageHandle,
1314 NULL,
1315 EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION | EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION
1316 );
1317
1318 PERF_START (*ImageHandle, "LoadImage:", NULL, Tick);
1319 PERF_END (*ImageHandle, "LoadImage:", NULL, 0);
1320
1321 return Status;
1322 }
1323
1324
1325
1326 /**
1327 Loads an EFI image into memory and returns a handle to the image with extended parameters.
1328
1329 @param This Calling context
1330 @param ParentImageHandle The caller's image handle.
1331 @param FilePath The specific file path from which the image is
1332 loaded.
1333 @param SourceBuffer If not NULL, a pointer to the memory location
1334 containing a copy of the image to be loaded.
1335 @param SourceSize The size in bytes of SourceBuffer.
1336 @param DstBuffer The buffer to store the image.
1337 @param NumberOfPages For input, specifies the space size of the
1338 image by caller if not NULL. For output,
1339 specifies the actual space size needed.
1340 @param ImageHandle Image handle for output.
1341 @param EntryPoint Image entry point for output.
1342 @param Attribute The bit mask of attributes to set for the load
1343 PE image.
1344
1345 @retval EFI_SUCCESS The image was loaded into memory.
1346 @retval EFI_NOT_FOUND The FilePath was not found.
1347 @retval EFI_INVALID_PARAMETER One of the parameters has an invalid value.
1348 @retval EFI_UNSUPPORTED The image type is not supported, or the device
1349 path cannot be parsed to locate the proper
1350 protocol for loading the file.
1351 @retval EFI_OUT_OF_RESOURCES Image was not loaded due to insufficient
1352 resources.
1353 @retval EFI_LOAD_ERROR Image was not loaded because the image format was corrupt or not
1354 understood.
1355 @retval EFI_DEVICE_ERROR Image was not loaded because the device returned a read error.
1356 @retval EFI_ACCESS_DENIED Image was not loaded because the platform policy prohibits the
1357 image from being loaded. NULL is returned in *ImageHandle.
1358 @retval EFI_SECURITY_VIOLATION Image was loaded and an ImageHandle was created with a
1359 valid EFI_LOADED_IMAGE_PROTOCOL. However, the current
1360 platform policy specifies that the image should not be started.
1361
1362 **/
1363 EFI_STATUS
1364 EFIAPI
1365 CoreLoadImageEx (
1366 IN EFI_PE32_IMAGE_PROTOCOL *This,
1367 IN EFI_HANDLE ParentImageHandle,
1368 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
1369 IN VOID *SourceBuffer OPTIONAL,
1370 IN UINTN SourceSize,
1371 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
1372 OUT UINTN *NumberOfPages OPTIONAL,
1373 OUT EFI_HANDLE *ImageHandle,
1374 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
1375 IN UINT32 Attribute
1376 )
1377 {
1378 return CoreLoadImageCommon (
1379 TRUE,
1380 ParentImageHandle,
1381 FilePath,
1382 SourceBuffer,
1383 SourceSize,
1384 DstBuffer,
1385 NumberOfPages,
1386 ImageHandle,
1387 EntryPoint,
1388 Attribute
1389 );
1390 }
1391
1392
1393 /**
1394 Transfer control to a loaded image's entry point.
1395
1396 @param ImageHandle Handle of image to be started.
1397 @param ExitDataSize Pointer of the size to ExitData
1398 @param ExitData Pointer to a pointer to a data buffer that
1399 includes a Null-terminated string,
1400 optionally followed by additional binary data.
1401 The string is a description that the caller may
1402 use to further indicate the reason for the
1403 image's exit.
1404
1405 @retval EFI_INVALID_PARAMETER Invalid parameter
1406 @retval EFI_OUT_OF_RESOURCES No enough buffer to allocate
1407 @retval EFI_SUCCESS Successfully transfer control to the image's
1408 entry point.
1409
1410 **/
1411 EFI_STATUS
1412 EFIAPI
1413 CoreStartImage (
1414 IN EFI_HANDLE ImageHandle,
1415 OUT UINTN *ExitDataSize,
1416 OUT CHAR16 **ExitData OPTIONAL
1417 )
1418 {
1419 EFI_STATUS Status;
1420 LOADED_IMAGE_PRIVATE_DATA *Image;
1421 LOADED_IMAGE_PRIVATE_DATA *LastImage;
1422 UINT64 HandleDatabaseKey;
1423 UINTN SetJumpFlag;
1424
1425 Image = CoreLoadedImageInfo (ImageHandle);
1426 if (Image == NULL || Image->Started) {
1427 return EFI_INVALID_PARAMETER;
1428 }
1429
1430 //
1431 // The image to be started must have the machine type supported by DxeCore.
1432 //
1433 ASSERT (EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->Machine));
1434 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->Machine)) {
1435 return EFI_UNSUPPORTED;
1436 }
1437
1438 //
1439 // Don't profile Objects or invalid start requests
1440 //
1441 PERF_START (ImageHandle, "StartImage:", NULL, 0);
1442
1443
1444 //
1445 // Push the current start image context, and
1446 // link the current image to the head. This is the
1447 // only image that can call Exit()
1448 //
1449 HandleDatabaseKey = CoreGetHandleDatabaseKey ();
1450 LastImage = mCurrentImage;
1451 mCurrentImage = Image;
1452 Image->Tpl = gEfiCurrentTpl;
1453
1454 //
1455 // Set long jump for Exit() support
1456 // JumpContext must be aligned on a CPU specific boundary.
1457 // Overallocate the buffer and force the required alignment
1458 //
1459 Image->JumpBuffer = AllocatePool (sizeof (BASE_LIBRARY_JUMP_BUFFER) + BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
1460 if (Image->JumpBuffer == NULL) {
1461 PERF_END (ImageHandle, "StartImage:", NULL, 0);
1462 return EFI_OUT_OF_RESOURCES;
1463 }
1464 Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
1465
1466 SetJumpFlag = SetJump (Image->JumpContext);
1467 //
1468 // The initial call to SetJump() must always return 0.
1469 // Subsequent calls to LongJump() cause a non-zero value to be returned by SetJump().
1470 //
1471 if (SetJumpFlag == 0) {
1472 //
1473 // Call the image's entry point
1474 //
1475 Image->Started = TRUE;
1476 Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable);
1477
1478 //
1479 // Add some debug information if the image returned with error.
1480 // This make the user aware and check if the driver image have already released
1481 // all the resource in this situation.
1482 //
1483 DEBUG_CODE_BEGIN ();
1484 if (EFI_ERROR (Image->Status)) {
1485 DEBUG ((DEBUG_ERROR, "Error: Image at %11p start failed: %r\n", Image->Info.ImageBase, Image->Status));
1486 }
1487 DEBUG_CODE_END ();
1488
1489 //
1490 // If the image returns, exit it through Exit()
1491 //
1492 CoreExit (ImageHandle, Image->Status, 0, NULL);
1493 }
1494
1495 //
1496 // Image has completed. Verify the tpl is the same
1497 //
1498 ASSERT (Image->Tpl == gEfiCurrentTpl);
1499 CoreRestoreTpl (Image->Tpl);
1500
1501 CoreFreePool (Image->JumpBuffer);
1502
1503 //
1504 // Pop the current start image context
1505 //
1506 mCurrentImage = LastImage;
1507
1508 //
1509 // Go connect any handles that were created or modified while the image executed.
1510 //
1511 CoreConnectHandlesByKey (HandleDatabaseKey);
1512
1513 //
1514 // Handle the image's returned ExitData
1515 //
1516 DEBUG_CODE_BEGIN ();
1517 if (Image->ExitDataSize != 0 || Image->ExitData != NULL) {
1518
1519 DEBUG ((DEBUG_LOAD, "StartImage: ExitDataSize %d, ExitData %p", (UINT32)Image->ExitDataSize, Image->ExitData));
1520 if (Image->ExitData != NULL) {
1521 DEBUG ((DEBUG_LOAD, " (%hs)", Image->ExitData));
1522 }
1523 DEBUG ((DEBUG_LOAD, "\n"));
1524 }
1525 DEBUG_CODE_END ();
1526
1527 //
1528 // Return the exit data to the caller
1529 //
1530 if (ExitData != NULL && ExitDataSize != NULL) {
1531 *ExitDataSize = Image->ExitDataSize;
1532 *ExitData = Image->ExitData;
1533 } else {
1534 //
1535 // Caller doesn't want the exit data, free it
1536 //
1537 CoreFreePool (Image->ExitData);
1538 Image->ExitData = NULL;
1539 }
1540
1541 //
1542 // Save the Status because Image will get destroyed if it is unloaded.
1543 //
1544 Status = Image->Status;
1545
1546 //
1547 // If the image returned an error, or if the image is an application
1548 // unload it
1549 //
1550 if (EFI_ERROR (Image->Status) || Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1551 CoreUnloadAndCloseImage (Image, TRUE);
1552 }
1553
1554 //
1555 // Done
1556 //
1557 PERF_END (ImageHandle, "StartImage:", NULL, 0);
1558 return Status;
1559 }
1560
1561 /**
1562 Terminates the currently loaded EFI image and returns control to boot services.
1563
1564 @param ImageHandle Handle that identifies the image. This
1565 parameter is passed to the image on entry.
1566 @param Status The image's exit code.
1567 @param ExitDataSize The size, in bytes, of ExitData. Ignored if
1568 ExitStatus is EFI_SUCCESS.
1569 @param ExitData Pointer to a data buffer that includes a
1570 Null-terminated Unicode string, optionally
1571 followed by additional binary data. The string
1572 is a description that the caller may use to
1573 further indicate the reason for the image's
1574 exit.
1575
1576 @retval EFI_INVALID_PARAMETER Image handle is NULL or it is not current
1577 image.
1578 @retval EFI_SUCCESS Successfully terminates the currently loaded
1579 EFI image.
1580 @retval EFI_ACCESS_DENIED Should never reach there.
1581 @retval EFI_OUT_OF_RESOURCES Could not allocate pool
1582
1583 **/
1584 EFI_STATUS
1585 EFIAPI
1586 CoreExit (
1587 IN EFI_HANDLE ImageHandle,
1588 IN EFI_STATUS Status,
1589 IN UINTN ExitDataSize,
1590 IN CHAR16 *ExitData OPTIONAL
1591 )
1592 {
1593 LOADED_IMAGE_PRIVATE_DATA *Image;
1594 EFI_TPL OldTpl;
1595
1596 //
1597 // Prevent possible reentrance to this function
1598 // for the same ImageHandle
1599 //
1600 OldTpl = CoreRaiseTpl (TPL_NOTIFY);
1601
1602 Image = CoreLoadedImageInfo (ImageHandle);
1603 if (Image == NULL) {
1604 Status = EFI_INVALID_PARAMETER;
1605 goto Done;
1606 }
1607
1608 if (!Image->Started) {
1609 //
1610 // The image has not been started so just free its resources
1611 //
1612 CoreUnloadAndCloseImage (Image, TRUE);
1613 Status = EFI_SUCCESS;
1614 goto Done;
1615 }
1616
1617 //
1618 // Image has been started, verify this image can exit
1619 //
1620 if (Image != mCurrentImage) {
1621 DEBUG ((DEBUG_LOAD|DEBUG_ERROR, "Exit: Image is not exitable image\n"));
1622 Status = EFI_INVALID_PARAMETER;
1623 goto Done;
1624 }
1625
1626 //
1627 // Set status
1628 //
1629 Image->Status = Status;
1630
1631 //
1632 // If there's ExitData info, move it
1633 //
1634 if (ExitData != NULL) {
1635 Image->ExitDataSize = ExitDataSize;
1636 Image->ExitData = AllocatePool (Image->ExitDataSize);
1637 if (Image->ExitData == NULL) {
1638 Status = EFI_OUT_OF_RESOURCES;
1639 goto Done;
1640 }
1641 CopyMem (Image->ExitData, ExitData, Image->ExitDataSize);
1642 }
1643
1644 CoreRestoreTpl (OldTpl);
1645 //
1646 // return to StartImage
1647 //
1648 LongJump (Image->JumpContext, (UINTN)-1);
1649
1650 //
1651 // If we return from LongJump, then it is an error
1652 //
1653 ASSERT (FALSE);
1654 Status = EFI_ACCESS_DENIED;
1655 Done:
1656 CoreRestoreTpl (OldTpl);
1657 return Status;
1658 }
1659
1660
1661
1662
1663 /**
1664 Unloads an image.
1665
1666 @param ImageHandle Handle that identifies the image to be
1667 unloaded.
1668
1669 @retval EFI_SUCCESS The image has been unloaded.
1670 @retval EFI_UNSUPPORTED The image has been sarted, and does not support
1671 unload.
1672 @retval EFI_INVALID_PARAMPETER ImageHandle is not a valid image handle.
1673
1674 **/
1675 EFI_STATUS
1676 EFIAPI
1677 CoreUnloadImage (
1678 IN EFI_HANDLE ImageHandle
1679 )
1680 {
1681 EFI_STATUS Status;
1682 LOADED_IMAGE_PRIVATE_DATA *Image;
1683
1684 Image = CoreLoadedImageInfo (ImageHandle);
1685 if (Image == NULL ) {
1686 //
1687 // The image handle is not valid
1688 //
1689 Status = EFI_INVALID_PARAMETER;
1690 goto Done;
1691 }
1692
1693 if (Image->Started) {
1694 //
1695 // The image has been started, request it to unload.
1696 //
1697 Status = EFI_UNSUPPORTED;
1698 if (Image->Info.Unload != NULL) {
1699 Status = Image->Info.Unload (ImageHandle);
1700 }
1701
1702 } else {
1703 //
1704 // This Image hasn't been started, thus it can be unloaded
1705 //
1706 Status = EFI_SUCCESS;
1707 }
1708
1709
1710 if (!EFI_ERROR (Status)) {
1711 //
1712 // if the Image was not started or Unloaded O.K. then clean up
1713 //
1714 CoreUnloadAndCloseImage (Image, TRUE);
1715 }
1716
1717 Done:
1718 return Status;
1719 }
1720
1721
1722
1723 /**
1724 Unload the specified image.
1725
1726 @param This Indicates the calling context.
1727 @param ImageHandle The specified image handle.
1728
1729 @retval EFI_INVALID_PARAMETER Image handle is NULL.
1730 @retval EFI_UNSUPPORTED Attempt to unload an unsupported image.
1731 @retval EFI_SUCCESS Image successfully unloaded.
1732
1733 **/
1734 EFI_STATUS
1735 EFIAPI
1736 CoreUnloadImageEx (
1737 IN EFI_PE32_IMAGE_PROTOCOL *This,
1738 IN EFI_HANDLE ImageHandle
1739 )
1740 {
1741 return CoreUnloadImage (ImageHandle);
1742 }