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