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