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