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