f1b2c7a1056a45459f3c92b5b8e0c0c4660eb166
[mirror_edk2.git] / EdkModulePkg / Core / Dxe / Image / Image.c
1 /*++
2
3 Copyright (c) 2006 - 2007, Intel Corporation
4 All rights reserved. This program and the accompanying materials
5 are licensed and made available under the terms and conditions of the BSD License
6 which accompanies this distribution. The full text of the license may be found at
7 http://opensource.org/licenses/bsd-license.php
8
9 THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
10 WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
11
12 Module Name:
13
14 Image.c
15
16 Abstract:
17
18 Core image handling services
19
20 --*/
21
22 #include <DxeMain.h>
23 //
24 // Module Globals
25 //
26
27 EFI_LOCK mBsExitLock = EFI_INITIALIZE_LOCK_VARIABLE(EFI_TPL_NOTIFY);
28 EFI_LOCK mBsUnloadImageLock = EFI_INITIALIZE_LOCK_VARIABLE(EFI_TPL_NOTIFY);
29
30 LOADED_IMAGE_PRIVATE_DATA *mCurrentImage = NULL;
31
32 LOAD_PE32_IMAGE_PRIVATE_DATA mLoadPe32PrivateData = {
33 LOAD_PE32_IMAGE_PRIVATE_DATA_SIGNATURE,
34 NULL,
35 {
36 CoreLoadImageEx,
37 CoreUnloadImageEx
38 }
39 };
40
41
42 //
43 // This code is needed to build the Image handle for the DXE Core
44 //
45 LOADED_IMAGE_PRIVATE_DATA mCorePrivateImage = {
46 LOADED_IMAGE_PRIVATE_DATA_SIGNATURE, // Signature
47 NULL, // Image handle
48 EFI_IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER, // Image type
49 TRUE, // If entrypoint has been called
50 NULL, // EntryPoint
51 {
52 EFI_LOADED_IMAGE_INFORMATION_REVISION, // Revision
53 NULL, // Parent handle
54 NULL, // System handle
55
56 NULL, // Device handle
57 NULL, // File path
58 NULL, // Reserved
59
60 0, // LoadOptionsSize
61 NULL, // LoadOptions
62
63 NULL, // ImageBase
64 0, // ImageSize
65 EfiBootServicesCode, // ImageCodeType
66 EfiBootServicesData // ImageDataType
67 },
68 (EFI_PHYSICAL_ADDRESS)0, // ImageBasePage
69 0, // NumberOfPages
70 NULL, // FixupData
71 0, // Tpl
72 EFI_SUCCESS, // Status
73 0, // ExitDataSize
74 NULL, // ExitData
75 NULL, // JumpBuffer
76 NULL, // JumpContext
77 0, // Machine
78 NULL, // Ebc
79 NULL, // RuntimeData
80 };
81
82
83 EFI_STATUS
84 CoreInitializeImageServices (
85 IN VOID *HobStart
86 )
87 /*++
88
89 Routine Description:
90
91 Add the Image Services to EFI Boot Services Table and install the protocol
92 interfaces for this image.
93
94 Arguments:
95
96 HobStart - The HOB to initialize
97
98 Returns:
99
100 Status code.
101
102 --*/
103 {
104 EFI_STATUS Status;
105 LOADED_IMAGE_PRIVATE_DATA *Image;
106 EFI_PHYSICAL_ADDRESS DxeCoreImageBaseAddress;
107 UINT64 DxeCoreImageLength;
108 VOID *DxeCoreEntryPoint;
109 EFI_PEI_HOB_POINTERS DxeCoreHob;
110 //
111 // Searching for image hob
112 //
113 DxeCoreHob.Raw = HobStart;
114 while ((DxeCoreHob.Raw = GetNextHob (EFI_HOB_TYPE_MEMORY_ALLOCATION, DxeCoreHob.Raw)) != NULL) {
115 if (CompareGuid (&DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.Name, &gEfiHobMemoryAllocModuleGuid)) {
116 //
117 // Find Dxe Core HOB
118 //
119 break;
120 }
121 DxeCoreHob.Raw = GET_NEXT_HOB (DxeCoreHob);
122 }
123 ASSERT (DxeCoreHob.Raw != NULL);
124
125 DxeCoreImageBaseAddress = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryBaseAddress;
126 DxeCoreImageLength = DxeCoreHob.MemoryAllocationModule->MemoryAllocationHeader.MemoryLength;
127 DxeCoreEntryPoint = (VOID *) (UINTN) DxeCoreHob.MemoryAllocationModule->EntryPoint;
128 gDxeCoreFileName = &DxeCoreHob.MemoryAllocationModule->ModuleName;
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 = gST;
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 //
162 // Export DXE Core PE Loader functionality
163 //
164 return CoreInstallProtocolInterface (
165 &mLoadPe32PrivateData.Handle,
166 &gEfiLoadPeImageProtocolGuid,
167 EFI_NATIVE_INTERFACE,
168 &mLoadPe32PrivateData.Pe32Image
169 );
170 }
171
172 EFI_STATUS
173 CoreLoadPeImage (
174 IN VOID *Pe32Handle,
175 IN LOADED_IMAGE_PRIVATE_DATA *Image,
176 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
177 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
178 IN UINT32 Attribute
179 )
180 /*++
181
182 Routine Description:
183
184 Loads, relocates, and invokes a PE/COFF image
185
186 Arguments:
187
188 Pe32Handle - The handle of PE32 image
189 Image - PE image to be loaded
190 DstBuffer - The buffer to store the image
191 EntryPoint - A pointer to the entry point
192 Attribute - The bit mask of attributes to set for the load PE image
193
194 Returns:
195
196 EFI_SUCCESS - The file was loaded, relocated, and invoked
197
198 EFI_OUT_OF_RESOURCES - There was not enough memory to load and relocate the PE/COFF file
199
200 EFI_INVALID_PARAMETER - Invalid parameter
201
202 EFI_BUFFER_TOO_SMALL - Buffer for image is too small
203
204 --*/
205 {
206 EFI_STATUS Status;
207 BOOLEAN DstBufAlocated;
208 UINTN Size;
209
210 ZeroMem (&Image->ImageContext, sizeof (Image->ImageContext));
211
212 Image->ImageContext.Handle = Pe32Handle;
213 Image->ImageContext.ImageRead = (PE_COFF_LOADER_READ_FILE)CoreReadImageFile;
214
215 //
216 // Get information about the image being loaded
217 //
218 Status = gEfiPeiPeCoffLoader->GetImageInfo (gEfiPeiPeCoffLoader, &Image->ImageContext);
219 if (EFI_ERROR (Status)) {
220 return Status;
221 }
222
223 if (!EFI_IMAGE_MACHINE_TYPE_SUPPORTED (Image->ImageContext.Machine)) {
224 //
225 // The PE/COFF loader can support loading image types that can be executed.
226 // If we loaded an image type that we can not execute return EFI_UNSUPORTED.
227 //
228 return EFI_UNSUPPORTED;
229 }
230
231
232 //
233 // Allocate memory of the correct memory type aligned on the required image boundry
234 //
235 DstBufAlocated = FALSE;
236 if (DstBuffer == 0) {
237 //
238 // Allocate Destination Buffer as caller did not pass it in
239 //
240
241 if (Image->ImageContext.SectionAlignment > EFI_PAGE_SIZE) {
242 Size = (UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment;
243 } else {
244 Size = (UINTN)Image->ImageContext.ImageSize;
245 }
246
247 Image->NumberOfPages = EFI_SIZE_TO_PAGES (Size);
248
249 //
250 // If the image relocations have not been stripped, then load at any address.
251 // Otherwise load at the address at which it was linked.
252 //
253 // Memory below 1MB should be treated reserved for CSM and there should be
254 // no modules whose preferred load addresses are below 1MB.
255 //
256 Status = EFI_OUT_OF_RESOURCES;
257 if (Image->ImageContext.ImageAddress >= 0x100000 || Image->ImageContext.RelocationsStripped) {
258 Status = CoreAllocatePages (
259 AllocateAddress,
260 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),
261 Image->NumberOfPages,
262 &Image->ImageContext.ImageAddress
263 );
264 }
265 if (EFI_ERROR (Status) && !Image->ImageContext.RelocationsStripped) {
266 Status = CoreAllocatePages (
267 AllocateAnyPages,
268 (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType),
269 Image->NumberOfPages,
270 &Image->ImageContext.ImageAddress
271 );
272 }
273 if (EFI_ERROR (Status)) {
274 return Status;
275 }
276 DstBufAlocated = TRUE;
277 } else {
278 //
279 // Caller provided the destination buffer
280 //
281
282 if (Image->ImageContext.RelocationsStripped && (Image->ImageContext.ImageAddress != DstBuffer)) {
283 //
284 // If the image relocations were stripped, and the caller provided a
285 // destination buffer address that does not match the address that the
286 // image is linked at, then the image cannot be loaded.
287 //
288 return EFI_INVALID_PARAMETER;
289 }
290
291 if (Image->NumberOfPages != 0 &&
292 Image->NumberOfPages <
293 (EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment))) {
294 Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);
295 return EFI_BUFFER_TOO_SMALL;
296 }
297
298 Image->NumberOfPages = EFI_SIZE_TO_PAGES ((UINTN)Image->ImageContext.ImageSize + Image->ImageContext.SectionAlignment);
299 Image->ImageContext.ImageAddress = DstBuffer;
300 }
301
302 Image->ImageBasePage = Image->ImageContext.ImageAddress;
303 Image->ImageContext.ImageAddress =
304 (Image->ImageContext.ImageAddress + Image->ImageContext.SectionAlignment - 1) &
305 ~((UINTN)Image->ImageContext.SectionAlignment - 1);
306
307 //
308 // Load the image from the file into the allocated memory
309 //
310 Status = gEfiPeiPeCoffLoader->LoadImage (gEfiPeiPeCoffLoader, &Image->ImageContext);
311 if (EFI_ERROR (Status)) {
312 goto Done;
313 }
314
315 //
316 // If this is a Runtime Driver, then allocate memory for the FixupData that
317 // is used to relocate the image when SetVirtualAddressMap() is called. The
318 // relocation is done by the Runtime AP.
319 //
320 if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) {
321 if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {
322 Image->ImageContext.FixupData = CoreAllocateRuntimePool ((UINTN)(Image->ImageContext.FixupDataSize));
323 if (Image->ImageContext.FixupData == NULL) {
324 Status = EFI_OUT_OF_RESOURCES;
325 goto Done;
326 }
327 }
328 }
329
330 //
331 // Relocate the image in memory
332 //
333 Status = gEfiPeiPeCoffLoader->RelocateImage (gEfiPeiPeCoffLoader, &Image->ImageContext);
334 if (EFI_ERROR (Status)) {
335 goto Done;
336 }
337
338 //
339 // Flush the Instruction Cache
340 //
341 InvalidateInstructionCacheRange ((VOID *)(UINTN)Image->ImageContext.ImageAddress, (UINTN)Image->ImageContext.ImageSize);
342
343 //
344 // Copy the machine type from the context to the image private data. This
345 // is needed during image unload to know if we should call an EBC protocol
346 // to unload the image.
347 //
348 Image->Machine = Image->ImageContext.Machine;
349
350 //
351 // Get the image entry point. If it's an EBC image, then call into the
352 // interpreter to create a thunk for the entry point and use the returned
353 // value for the entry point.
354 //
355 Image->EntryPoint = (EFI_IMAGE_ENTRY_POINT)(UINTN)Image->ImageContext.EntryPoint;
356 if (Image->ImageContext.Machine == EFI_IMAGE_MACHINE_EBC) {
357 //
358 // Locate the EBC interpreter protocol
359 //
360 Status = CoreLocateProtocol (&gEfiEbcProtocolGuid, NULL, (VOID **)&Image->Ebc);
361 if (EFI_ERROR(Status)) {
362 goto Done;
363 }
364
365 //
366 // Register a callback for flushing the instruction cache so that created
367 // thunks can be flushed.
368 //
369 Status = Image->Ebc->RegisterICacheFlush (Image->Ebc, (EBC_ICACHE_FLUSH)InvalidateInstructionCacheRange);
370 if (EFI_ERROR(Status)) {
371 goto Done;
372 }
373
374 //
375 // Create a thunk for the image's entry point. This will be the new
376 // entry point for the image.
377 //
378 Status = Image->Ebc->CreateThunk (
379 Image->Ebc,
380 Image->Handle,
381 (VOID *)(UINTN)Image->ImageContext.EntryPoint,
382 (VOID **)&Image->EntryPoint
383 );
384 if (EFI_ERROR(Status)) {
385 goto Done;
386 }
387 }
388
389 //
390 // Fill in the image information for the Loaded Image Protocol
391 //
392 Image->Type = Image->ImageContext.ImageType;
393 Image->Info.ImageBase = (VOID *)(UINTN)Image->ImageContext.ImageAddress;
394 Image->Info.ImageSize = Image->ImageContext.ImageSize;
395 Image->Info.ImageCodeType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageCodeMemoryType);
396 Image->Info.ImageDataType = (EFI_MEMORY_TYPE) (Image->ImageContext.ImageDataMemoryType);
397 if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION) {
398 if (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER) {
399 //
400 // Make a list off all the RT images so we can let the RT AP know about them.
401 //
402 Image->RuntimeData = CoreAllocateRuntimePool (sizeof(EFI_RUNTIME_IMAGE_ENTRY));
403 if (Image->RuntimeData == NULL) {
404 goto Done;
405 }
406 Image->RuntimeData->ImageBase = Image->Info.ImageBase;
407 Image->RuntimeData->ImageSize = (UINT64) (Image->Info.ImageSize);
408 Image->RuntimeData->RelocationData = Image->ImageContext.FixupData;
409 Image->RuntimeData->Handle = Image->Handle;
410 InsertTailList (&gRuntime->ImageHead, &Image->RuntimeData->Link);
411 }
412 }
413
414 //
415 // Fill in the entry point of the image if it is available
416 //
417 if (EntryPoint != NULL) {
418 *EntryPoint = Image->ImageContext.EntryPoint;
419 }
420
421 //
422 // Print the load address and the PDB file name if it is available
423 //
424
425 DEBUG_CODE_BEGIN ();
426
427 UINTN Index;
428 UINTN StartIndex;
429 CHAR8 EfiFileName[256];
430
431 DEBUG ((EFI_D_INFO | EFI_D_LOAD, "Loading driver at 0x%10p EntryPoint=0x%10p ", (VOID *)(UINTN)Image->ImageContext.ImageAddress, (VOID *)(UINTN)Image->ImageContext.EntryPoint));
432 if (Image->ImageContext.PdbPointer != NULL) {
433 StartIndex = 0;
434 for (Index = 0; Image->ImageContext.PdbPointer[Index] != 0; Index++) {
435 if (Image->ImageContext.PdbPointer[Index] == '\\') {
436 StartIndex = Index + 1;
437 }
438 }
439 //
440 // Copy the PDB file name to our temporary string, and replace .pdb with .efi
441 //
442 for (Index = 0; Index < sizeof (EfiFileName); Index++) {
443 EfiFileName[Index] = Image->ImageContext.PdbPointer[Index + StartIndex];
444 if (EfiFileName[Index] == 0) {
445 EfiFileName[Index] = '.';
446 }
447 if (EfiFileName[Index] == '.') {
448 EfiFileName[Index + 1] = 'e';
449 EfiFileName[Index + 2] = 'f';
450 EfiFileName[Index + 3] = 'i';
451 EfiFileName[Index + 4] = 0;
452 break;
453 }
454 }
455 DEBUG ((EFI_D_INFO | EFI_D_LOAD, "%a", EfiFileName)); // &Image->ImageContext.PdbPointer[StartIndex]));
456 }
457 DEBUG ((EFI_D_INFO | EFI_D_LOAD, "\n"));
458
459 DEBUG_CODE_END ();
460
461 return EFI_SUCCESS;
462
463 Done:
464
465 //
466 // Free memory.
467 //
468
469 if (DstBufAlocated) {
470 CoreFreePages (Image->ImageContext.ImageAddress, Image->NumberOfPages);
471 }
472
473 if (Image->ImageContext.FixupData != NULL) {
474 CoreFreePool (Image->ImageContext.FixupData);
475 }
476
477 return Status;
478 }
479
480
481 LOADED_IMAGE_PRIVATE_DATA *
482 CoreLoadedImageInfo (
483 IN EFI_HANDLE ImageHandle
484 )
485 /*++
486
487 Routine Description:
488
489 Get the image's private data from its handle.
490
491 Arguments:
492
493 ImageHandle - The image handle
494
495 Returns:
496
497 Return the image private data associated with ImageHandle.
498
499 --*/
500 {
501 EFI_STATUS Status;
502 EFI_LOADED_IMAGE_PROTOCOL *LoadedImage;
503 LOADED_IMAGE_PRIVATE_DATA *Image;
504
505 Status = CoreHandleProtocol (
506 ImageHandle,
507 &gEfiLoadedImageProtocolGuid,
508 (VOID **)&LoadedImage
509 );
510 if (!EFI_ERROR (Status)) {
511 Image = LOADED_IMAGE_PRIVATE_DATA_FROM_THIS (LoadedImage);
512 } else {
513 DEBUG ((EFI_D_LOAD, "CoreLoadedImageInfo: Not an ImageHandle %x\n", ImageHandle));
514 Image = NULL;
515 }
516
517 return Image;
518 }
519
520 STATIC
521 EFI_STATUS
522 CoreLoadImageCommon (
523 IN BOOLEAN BootPolicy,
524 IN EFI_HANDLE ParentImageHandle,
525 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
526 IN VOID *SourceBuffer OPTIONAL,
527 IN UINTN SourceSize,
528 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
529 IN OUT UINTN *NumberOfPages OPTIONAL,
530 OUT EFI_HANDLE *ImageHandle,
531 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
532 IN UINT32 Attribute
533 )
534 /*++
535
536 Routine Description:
537
538 Loads an EFI image into memory and returns a handle to the image.
539
540 Arguments:
541
542 BootPolicy - If TRUE, indicates that the request originates from the boot manager,
543 and that the boot manager is attempting to load FilePath as a boot selection.
544 ParentImageHandle - The caller's image handle.
545 FilePath - The specific file path from which the image is loaded.
546 SourceBuffer - If not NULL, a pointer to the memory location containing a copy of
547 the image to be loaded.
548 SourceSize - The size in bytes of SourceBuffer.
549 DstBuffer - The buffer to store the image
550 NumberOfPages - If not NULL, a pointer to the image's page number, if this number
551 is not enough, return EFI_BUFFER_TOO_SMALL and this parameter contain
552 the required number.
553 ImageHandle - Pointer to the returned image handle that is created when the image
554 is successfully loaded.
555 EntryPoint - A pointer to the entry point
556 Attribute - The bit mask of attributes to set for the load PE image
557
558 Returns:
559
560 EFI_SUCCESS - The image was loaded into memory.
561 EFI_NOT_FOUND - The FilePath was not found.
562 EFI_INVALID_PARAMETER - One of the parameters has an invalid value.
563 EFI_BUFFER_TOO_SMALL - The buffer is too small
564 EFI_UNSUPPORTED - The image type is not supported, or the device path cannot be
565 parsed to locate the proper protocol for loading the file.
566 EFI_OUT_OF_RESOURCES - Image was not loaded due to insufficient resources.
567 --*/
568 {
569 LOADED_IMAGE_PRIVATE_DATA *Image;
570 LOADED_IMAGE_PRIVATE_DATA *ParentImage;
571 IMAGE_FILE_HANDLE FHand;
572 EFI_STATUS Status;
573 EFI_STATUS SecurityStatus;
574 EFI_HANDLE DeviceHandle;
575 UINT32 AuthenticationStatus;
576 EFI_DEVICE_PATH_PROTOCOL *OriginalFilePath;
577 EFI_DEVICE_PATH_PROTOCOL *HandleFilePath;
578 UINTN FilePathSize;
579
580 SecurityStatus = EFI_SUCCESS;
581
582 ASSERT (gEfiCurrentTpl < EFI_TPL_NOTIFY);
583 ParentImage = NULL;
584
585 //
586 // The caller must pass in a valid ParentImageHandle
587 //
588 if (ImageHandle == NULL || ParentImageHandle == NULL) {
589 return EFI_INVALID_PARAMETER;
590 }
591
592 ParentImage = CoreLoadedImageInfo (ParentImageHandle);
593 if (ParentImage == NULL) {
594 DEBUG((EFI_D_LOAD|EFI_D_ERROR, "LoadImageEx: Parent handle not an image handle\n"));
595 return EFI_INVALID_PARAMETER;
596 }
597
598 //
599 // Get simple read access to the source file
600 //
601 OriginalFilePath = FilePath;
602 Status = CoreOpenImageFile (
603 BootPolicy,
604 SourceBuffer,
605 SourceSize,
606 FilePath,
607 &DeviceHandle,
608 &FHand,
609 &AuthenticationStatus
610 );
611 if (Status == EFI_ALREADY_STARTED) {
612 Image = NULL;
613 goto Done;
614 } else if (EFI_ERROR (Status)) {
615 return Status;
616 }
617
618 //
619 // Verify the Authentication Status through the Security Architectural Protocol
620 //
621 if ((gSecurity != NULL) && (OriginalFilePath != NULL)) {
622 SecurityStatus = gSecurity->FileAuthenticationState (
623 gSecurity,
624 AuthenticationStatus,
625 OriginalFilePath
626 );
627 if (EFI_ERROR (SecurityStatus) && SecurityStatus != EFI_SECURITY_VIOLATION) {
628 Status = SecurityStatus;
629 Image = NULL;
630 goto Done;
631 }
632 }
633
634
635 //
636 // Allocate a new image structure
637 //
638 Image = CoreAllocateZeroBootServicesPool (sizeof(LOADED_IMAGE_PRIVATE_DATA));
639 if (Image == NULL) {
640 return EFI_OUT_OF_RESOURCES;
641 }
642
643 //
644 // Pull out just the file portion of the DevicePath for the LoadedImage FilePath
645 //
646 Status = CoreHandleProtocol (DeviceHandle, &gEfiDevicePathProtocolGuid, (VOID **)&HandleFilePath);
647 if (!EFI_ERROR (Status)) {
648 FilePathSize = CoreDevicePathSize (HandleFilePath) - sizeof(EFI_DEVICE_PATH_PROTOCOL);
649 FilePath = (EFI_DEVICE_PATH_PROTOCOL *) ( ((UINT8 *)FilePath) + FilePathSize );
650 }
651
652 //
653 // Initialize the fields for an internal driver
654 //
655 Image->Signature = LOADED_IMAGE_PRIVATE_DATA_SIGNATURE;
656 Image->Info.SystemTable = gST;
657 Image->Info.DeviceHandle = DeviceHandle;
658 Image->Info.Revision = EFI_LOADED_IMAGE_INFORMATION_REVISION;
659 Image->Info.FilePath = CoreDuplicateDevicePath (FilePath);
660 Image->Info.ParentHandle = ParentImageHandle;
661
662 if (NumberOfPages != NULL) {
663 Image->NumberOfPages = *NumberOfPages ;
664 } else {
665 Image->NumberOfPages = 0 ;
666 }
667
668 //
669 // Install the protocol interfaces for this image
670 // don't fire notifications yet
671 //
672 Status = CoreInstallProtocolInterfaceNotify (
673 &Image->Handle,
674 &gEfiLoadedImageProtocolGuid,
675 EFI_NATIVE_INTERFACE,
676 &Image->Info,
677 FALSE
678 );
679 if (EFI_ERROR (Status)) {
680 goto Done;
681 }
682
683 //
684 // Load the image. If EntryPoint is Null, it will not be set.
685 //
686 Status = CoreLoadPeImage (&FHand, Image, DstBuffer, EntryPoint, Attribute);
687 if (EFI_ERROR (Status)) {
688 if ((Status == EFI_BUFFER_TOO_SMALL) || (Status == EFI_OUT_OF_RESOURCES)) {
689 if (NumberOfPages != NULL) {
690 *NumberOfPages = Image->NumberOfPages;
691 }
692 }
693 goto Done;
694 }
695
696 //
697 // Register the image in the Debug Image Info Table if the attribute is set
698 //
699 if (Attribute & EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION) {
700 CoreNewDebugImageInfoEntry (EFI_DEBUG_IMAGE_INFO_TYPE_NORMAL, &Image->Info, Image->Handle);
701 }
702
703 //
704 //Reinstall loaded image protocol to fire any notifications
705 //
706 Status = CoreReinstallProtocolInterface (
707 Image->Handle,
708 &gEfiLoadedImageProtocolGuid,
709 &Image->Info,
710 &Image->Info
711 );
712 if (EFI_ERROR (Status)) {
713 goto Done;
714 }
715
716
717 //
718 // Success. Return the image handle
719 //
720 *ImageHandle = Image->Handle;
721
722 Done:
723 //
724 // All done accessing the source file
725 // If we allocated the Source buffer, free it
726 //
727 if (FHand.FreeBuffer) {
728 CoreFreePool (FHand.Source);
729 }
730
731 //
732 // There was an error. If there's an Image structure, free it
733 //
734 if (EFI_ERROR (Status)) {
735 if (Image != NULL) {
736 CoreUnloadAndCloseImage (Image, (BOOLEAN)(DstBuffer == 0));
737 *ImageHandle = NULL;
738 }
739 } else if (EFI_ERROR (SecurityStatus)) {
740 Status = SecurityStatus;
741 }
742
743 return Status;
744 }
745
746
747
748 EFI_STATUS
749 EFIAPI
750 CoreLoadImage (
751 IN BOOLEAN BootPolicy,
752 IN EFI_HANDLE ParentImageHandle,
753 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
754 IN VOID *SourceBuffer OPTIONAL,
755 IN UINTN SourceSize,
756 OUT EFI_HANDLE *ImageHandle
757 )
758 /*++
759
760 Routine Description:
761
762 Loads an EFI image into memory and returns a handle to the image.
763
764 Arguments:
765
766 BootPolicy - If TRUE, indicates that the request originates from the boot manager,
767 and that the boot manager is attempting to load FilePath as a boot selection.
768 ParentImageHandle - The caller's image handle.
769 FilePath - The specific file path from which the image is loaded.
770 SourceBuffer - If not NULL, a pointer to the memory location containing a copy of
771 the image to be loaded.
772 SourceSize - The size in bytes of SourceBuffer.
773 ImageHandle - Pointer to the returned image handle that is created when the image
774 is successfully loaded.
775
776 Returns:
777
778 EFI_SUCCESS - The image was loaded into memory.
779 EFI_NOT_FOUND - The FilePath was not found.
780 EFI_INVALID_PARAMETER - One of the parameters has an invalid value.
781 EFI_UNSUPPORTED - The image type is not supported, or the device path cannot be
782 parsed to locate the proper protocol for loading the file.
783 EFI_OUT_OF_RESOURCES - Image was not loaded due to insufficient resources.
784 --*/
785 {
786 EFI_STATUS Status;
787
788 PERF_START (NULL, "LoadImage", NULL, 0);
789
790 Status = CoreLoadImageCommon (
791 BootPolicy,
792 ParentImageHandle,
793 FilePath,
794 SourceBuffer,
795 SourceSize,
796 (EFI_PHYSICAL_ADDRESS)NULL,
797 NULL,
798 ImageHandle,
799 NULL,
800 EFI_LOAD_PE_IMAGE_ATTRIBUTE_RUNTIME_REGISTRATION | EFI_LOAD_PE_IMAGE_ATTRIBUTE_DEBUG_IMAGE_INFO_TABLE_REGISTRATION
801 );
802
803 PERF_END (NULL, "LoadImage", NULL, 0);
804
805 return Status;
806 }
807
808
809 EFI_STATUS
810 EFIAPI
811 CoreLoadImageEx (
812 IN EFI_PE32_IMAGE_PROTOCOL *This,
813 IN EFI_HANDLE ParentImageHandle,
814 IN EFI_DEVICE_PATH_PROTOCOL *FilePath,
815 IN VOID *SourceBuffer OPTIONAL,
816 IN UINTN SourceSize,
817 IN EFI_PHYSICAL_ADDRESS DstBuffer OPTIONAL,
818 OUT UINTN *NumberOfPages OPTIONAL,
819 OUT EFI_HANDLE *ImageHandle,
820 OUT EFI_PHYSICAL_ADDRESS *EntryPoint OPTIONAL,
821 IN UINT32 Attribute
822 )
823 /*++
824
825 Routine Description:
826
827 Loads an EFI image into memory and returns a handle to the image with extended parameters.
828
829 Arguments:
830
831 This - Calling context
832 ParentImageHandle - The caller's image handle.
833 FilePath - The specific file path from which the image is loaded.
834 SourceBuffer - If not NULL, a pointer to the memory location containing a copy of
835 the image to be loaded.
836 SourceSize - The size in bytes of SourceBuffer.
837 DstBuffer - The buffer to store the image.
838 NumberOfPages - For input, specifies the space size of the image by caller if not NULL.
839 For output, specifies the actual space size needed.
840 ImageHandle - Image handle for output.
841 EntryPoint - Image entry point for output.
842 Attribute - The bit mask of attributes to set for the load PE image.
843
844 Returns:
845
846 EFI_SUCCESS - The image was loaded into memory.
847 EFI_NOT_FOUND - The FilePath was not found.
848 EFI_INVALID_PARAMETER - One of the parameters has an invalid value.
849 EFI_UNSUPPORTED - The image type is not supported, or the device path cannot be
850 parsed to locate the proper protocol for loading the file.
851 EFI_OUT_OF_RESOURCES - Image was not loaded due to insufficient resources.
852 --*/
853 {
854 return CoreLoadImageCommon (
855 TRUE,
856 ParentImageHandle,
857 FilePath,
858 SourceBuffer,
859 SourceSize,
860 DstBuffer,
861 NumberOfPages,
862 ImageHandle,
863 EntryPoint,
864 Attribute
865 );
866 }
867
868
869
870
871 EFI_STATUS
872 EFIAPI
873 CoreStartImage (
874 IN EFI_HANDLE ImageHandle,
875 OUT UINTN *ExitDataSize,
876 OUT CHAR16 **ExitData OPTIONAL
877 )
878 /*++
879
880 Routine Description:
881
882 Transfer control to a loaded image's entry point.
883
884 Arguments:
885
886 ImageHandle - Handle of image to be started.
887
888 ExitDataSize - Pointer of the size to ExitData
889
890 ExitData - Pointer to a pointer to a data buffer that includes a Null-terminated
891 Unicode string, optionally followed by additional binary data. The string
892 is a description that the caller may use to further indicate the reason for
893 the image's exit.
894
895 Returns:
896
897 EFI_INVALID_PARAMETER - Invalid parameter
898
899 EFI_OUT_OF_RESOURCES - No enough buffer to allocate
900
901 EFI_SUCCESS - Successfully transfer control to the image's entry point.
902
903 --*/
904 {
905 EFI_STATUS Status;
906 LOADED_IMAGE_PRIVATE_DATA *Image;
907 LOADED_IMAGE_PRIVATE_DATA *LastImage;
908 UINT64 HandleDatabaseKey;
909 UINTN SetJumpFlag;
910
911 Image = CoreLoadedImageInfo (ImageHandle);
912 if (Image == NULL_HANDLE || Image->Started) {
913 return EFI_INVALID_PARAMETER;
914 }
915
916 //
917 // Don't profile Objects or invalid start requests
918 //
919 PERF_START (ImageHandle, START_IMAGE_TOK, NULL, 0);
920
921
922 //
923 // Push the current start image context, and
924 // link the current image to the head. This is the
925 // only image that can call Exit()
926 //
927 HandleDatabaseKey = CoreGetHandleDatabaseKey ();
928 LastImage = mCurrentImage;
929 mCurrentImage = Image;
930 Image->Tpl = gEfiCurrentTpl;
931
932 //
933 // Set long jump for Exit() support
934 // JumpContext must be aligned on a CPU specific boundary.
935 // Overallocate the buffer and force the required alignment
936 //
937 Image->JumpBuffer = CoreAllocateBootServicesPool (sizeof (BASE_LIBRARY_JUMP_BUFFER) + BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
938 if (Image->JumpBuffer == NULL) {
939 PERF_END (ImageHandle, START_IMAGE_TOK, NULL, 0);
940 return EFI_OUT_OF_RESOURCES;
941 }
942 Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
943
944 SetJumpFlag = SetJump (Image->JumpContext);
945 //
946 // The initial call to SetJump() must always return 0.
947 // Subsequent calls to LongJump() cause a non-zero value to be returned by SetJump().
948 //
949 if (!SetJumpFlag) {
950 //
951 // Call the image's entry point
952 //
953 Image->Started = TRUE;
954 Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable);
955
956 //
957 // Add some debug information if the image returned with error.
958 // This make the user aware and check if the driver image have already released
959 // all the resource in this situation.
960 //
961 DEBUG_CODE_BEGIN ();
962 if (EFI_ERROR (Image->Status)) {
963 DEBUG ((EFI_D_ERROR, "Error: Image at %10p start failed: %r\n", Image->Info.ImageBase, Image->Status));
964 }
965 DEBUG_CODE_END ();
966
967 //
968 // If the image returns, exit it through Exit()
969 //
970 CoreExit (ImageHandle, Image->Status, 0, NULL);
971 }
972
973 //
974 // Image has completed. Verify the tpl is the same
975 //
976 ASSERT (Image->Tpl == gEfiCurrentTpl);
977 CoreRestoreTpl (Image->Tpl);
978
979 CoreFreePool (Image->JumpBuffer);
980
981 //
982 // Pop the current start image context
983 //
984 mCurrentImage = LastImage;
985
986 //
987 // Go connect any handles that were created or modified while the image executed.
988 //
989 CoreConnectHandlesByKey (HandleDatabaseKey);
990
991 //
992 // Handle the image's returned ExitData
993 //
994 DEBUG_CODE_BEGIN ();
995 if (Image->ExitDataSize != 0 || Image->ExitData != NULL) {
996
997 DEBUG (
998 (EFI_D_LOAD,
999 "StartImage: ExitDataSize %d, ExitData %x",
1000 Image->ExitDataSize,
1001 Image->ExitData)
1002 );
1003 if (Image->ExitData != NULL) {
1004 DEBUG ((EFI_D_LOAD, " (%hs)", Image->ExitData));
1005 }
1006 DEBUG ((EFI_D_LOAD, "\n"));
1007 }
1008 DEBUG_CODE_END ();
1009
1010 //
1011 // Return the exit data to the caller
1012 //
1013 if (ExitData != NULL && ExitDataSize != NULL) {
1014 *ExitDataSize = Image->ExitDataSize;
1015 *ExitData = Image->ExitData;
1016 } else {
1017 //
1018 // Caller doesn't want the exit data, free it
1019 //
1020 CoreFreePool (Image->ExitData);
1021 Image->ExitData = NULL;
1022 }
1023
1024 //
1025 // Save the Status because Image will get destroyed if it is unloaded.
1026 //
1027 Status = Image->Status;
1028
1029 //
1030 // If the image returned an error, or if the image is an application
1031 // unload it
1032 //
1033 if (EFI_ERROR (Image->Status) || Image->Type == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION) {
1034 CoreUnloadAndCloseImage (Image, TRUE);
1035 }
1036
1037 //
1038 // Done
1039 //
1040 PERF_END (ImageHandle, START_IMAGE_TOK, NULL, 0);
1041 return Status;
1042 }
1043
1044
1045 VOID
1046 CoreUnloadAndCloseImage (
1047 IN LOADED_IMAGE_PRIVATE_DATA *Image,
1048 IN BOOLEAN FreePage
1049 )
1050 /*++
1051
1052 Routine Description:
1053
1054 Unloads EFI image from memory.
1055
1056 Arguments:
1057
1058 Image - EFI image
1059 FreePage - Free allocated pages
1060
1061 Returns:
1062
1063 None
1064
1065 --*/
1066 {
1067 EFI_STATUS Status;
1068 UINTN HandleCount;
1069 EFI_HANDLE *HandleBuffer;
1070 UINTN HandleIndex;
1071 EFI_GUID **ProtocolGuidArray;
1072 UINTN ArrayCount;
1073 UINTN ProtocolIndex;
1074 EFI_OPEN_PROTOCOL_INFORMATION_ENTRY *OpenInfo;
1075 UINTN OpenInfoCount;
1076 UINTN OpenInfoIndex;
1077
1078 if (Image->Ebc != NULL) {
1079 //
1080 // If EBC protocol exists we must perform cleanups for this image.
1081 //
1082 Image->Ebc->UnloadImage (Image->Ebc, Image->Handle);
1083 }
1084
1085 //
1086 // Unload image, free Image->ImageContext->ModHandle
1087 //
1088 gEfiPeiPeCoffLoader->UnloadImage (gEfiPeiPeCoffLoader, &Image->ImageContext);
1089
1090 //
1091 // Free our references to the image handle
1092 //
1093 if (Image->Handle != NULL_HANDLE) {
1094
1095 Status = CoreLocateHandleBuffer (
1096 AllHandles,
1097 NULL,
1098 NULL,
1099 &HandleCount,
1100 &HandleBuffer
1101 );
1102 if (!EFI_ERROR (Status)) {
1103 for (HandleIndex = 0; HandleIndex < HandleCount; HandleIndex++) {
1104 Status = CoreProtocolsPerHandle (
1105 HandleBuffer[HandleIndex],
1106 &ProtocolGuidArray,
1107 &ArrayCount
1108 );
1109 if (!EFI_ERROR (Status)) {
1110 for (ProtocolIndex = 0; ProtocolIndex < ArrayCount; ProtocolIndex++) {
1111 Status = CoreOpenProtocolInformation (
1112 HandleBuffer[HandleIndex],
1113 ProtocolGuidArray[ProtocolIndex],
1114 &OpenInfo,
1115 &OpenInfoCount
1116 );
1117 if (!EFI_ERROR (Status)) {
1118 for (OpenInfoIndex = 0; OpenInfoIndex < OpenInfoCount; OpenInfoIndex++) {
1119 if (OpenInfo[OpenInfoIndex].AgentHandle == Image->Handle) {
1120 Status = CoreCloseProtocol (
1121 HandleBuffer[HandleIndex],
1122 ProtocolGuidArray[ProtocolIndex],
1123 Image->Handle,
1124 OpenInfo[OpenInfoIndex].ControllerHandle
1125 );
1126 }
1127 }
1128 if (OpenInfo != NULL) {
1129 CoreFreePool(OpenInfo);
1130 }
1131 }
1132 }
1133 if (ProtocolGuidArray != NULL) {
1134 CoreFreePool(ProtocolGuidArray);
1135 }
1136 }
1137 }
1138 if (HandleBuffer != NULL) {
1139 CoreFreePool (HandleBuffer);
1140 }
1141 }
1142
1143 CoreRemoveDebugImageInfoEntry (Image->Handle);
1144
1145 Status = CoreUninstallProtocolInterface (
1146 Image->Handle,
1147 &gEfiLoadedImageProtocolGuid,
1148 &Image->Info
1149 );
1150 }
1151
1152 if (Image->RuntimeData != NULL) {
1153 if (Image->RuntimeData->Link.ForwardLink != NULL) {
1154 //
1155 // Remove the Image from the Runtime Image list as we are about to Free it!
1156 //
1157 RemoveEntryList (&Image->RuntimeData->Link);
1158 }
1159 CoreFreePool (Image->RuntimeData);
1160 }
1161
1162 //
1163 // Free the Image from memory
1164 //
1165 if ((Image->ImageBasePage != 0) && FreePage) {
1166 CoreFreePages (Image->ImageBasePage, Image->NumberOfPages);
1167 }
1168
1169 //
1170 // Done with the Image structure
1171 //
1172 if (Image->Info.FilePath != NULL) {
1173 CoreFreePool (Image->Info.FilePath);
1174 }
1175
1176 if (Image->FixupData != NULL) {
1177 CoreFreePool (Image->FixupData);
1178 }
1179
1180 CoreFreePool (Image);
1181 }
1182
1183
1184
1185 EFI_STATUS
1186 EFIAPI
1187 CoreExit (
1188 IN EFI_HANDLE ImageHandle,
1189 IN EFI_STATUS Status,
1190 IN UINTN ExitDataSize,
1191 IN CHAR16 *ExitData OPTIONAL
1192 )
1193 /*++
1194
1195 Routine Description:
1196
1197 Terminates the currently loaded EFI image and returns control to boot services.
1198
1199 Arguments:
1200
1201 ImageHandle - Handle that identifies the image. This parameter is passed to the image
1202 on entry.
1203 Status - The image's exit code.
1204 ExitDataSize - The size, in bytes, of ExitData. Ignored if ExitStatus is
1205 EFI_SUCCESS.
1206 ExitData - Pointer to a data buffer that includes a Null-terminated Unicode string,
1207 optionally followed by additional binary data. The string is a
1208 description that the caller may use to further indicate the reason for
1209 the image's exit.
1210
1211 Returns:
1212
1213 EFI_INVALID_PARAMETER - Image handle is NULL or it is not current image.
1214
1215 EFI_SUCCESS - Successfully terminates the currently loaded EFI image.
1216
1217 EFI_ACCESS_DENIED - Should never reach there.
1218
1219 EFI_OUT_OF_RESOURCES - Could not allocate pool
1220
1221 --*/
1222 {
1223 LOADED_IMAGE_PRIVATE_DATA *Image;
1224
1225 EfiAcquireLock (&mBsExitLock);
1226
1227 Image = CoreLoadedImageInfo (ImageHandle);
1228 if (Image == NULL_HANDLE) {
1229 Status = EFI_INVALID_PARAMETER;
1230 goto Done;
1231 }
1232
1233 if (!Image->Started) {
1234 //
1235 // The image has not been started so just free its resources
1236 //
1237 CoreUnloadAndCloseImage (Image, TRUE);
1238 Status = EFI_SUCCESS;
1239 goto Done;
1240 }
1241
1242 //
1243 // Image has been started, verify this image can exit
1244 //
1245 if (Image != mCurrentImage) {
1246 DEBUG ((EFI_D_LOAD|EFI_D_ERROR, "Exit: Image is not exitable image\n"));
1247 Status = EFI_INVALID_PARAMETER;
1248 goto Done;
1249 }
1250
1251 //
1252 // Set status
1253 //
1254 Image->Status = Status;
1255
1256 //
1257 // If there's ExitData info, move it
1258 //
1259 if (ExitData != NULL) {
1260 Image->ExitDataSize = ExitDataSize;
1261 Image->ExitData = CoreAllocateBootServicesPool (Image->ExitDataSize);
1262 if (Image->ExitData == NULL) {
1263 Status = EFI_OUT_OF_RESOURCES;
1264 goto Done;
1265 }
1266 CopyMem (Image->ExitData, ExitData, Image->ExitDataSize);
1267 }
1268
1269 EfiReleaseLock (&mBsExitLock);
1270 //
1271 // return to StartImage
1272 //
1273 LongJump (Image->JumpContext, (UINTN)-1);
1274
1275 //
1276 // If we return from LongJump, then it is an error
1277 //
1278 ASSERT (FALSE);
1279 Status = EFI_ACCESS_DENIED;
1280 Done:
1281 EfiReleaseLock (&mBsExitLock);
1282 return Status;
1283 }
1284
1285
1286
1287 EFI_STATUS
1288 EFIAPI
1289 CoreUnloadImage (
1290 IN EFI_HANDLE ImageHandle
1291 )
1292 /*++
1293
1294 Routine Description:
1295
1296 Unloads an image.
1297
1298 Arguments:
1299
1300 ImageHandle - Handle that identifies the image to be unloaded.
1301
1302 Returns:
1303
1304 EFI_SUCCESS - The image has been unloaded.
1305 EFI_UNSUPPORTED - The image has been sarted, and does not support unload.
1306 EFI_INVALID_PARAMPETER - ImageHandle is not a valid image handle.
1307
1308 --*/
1309 {
1310 EFI_STATUS Status;
1311 LOADED_IMAGE_PRIVATE_DATA *Image;
1312
1313 EfiAcquireLock (&mBsUnloadImageLock);
1314
1315 Image = CoreLoadedImageInfo (ImageHandle);
1316 if (Image == NULL ) {
1317 //
1318 // The image handle is not valid
1319 //
1320 Status = EFI_INVALID_PARAMETER;
1321 goto Done;
1322 }
1323
1324 if (Image->Started) {
1325 //
1326 // The image has been started, request it to unload.
1327 //
1328 Status = EFI_UNSUPPORTED;
1329 if (Image->Info.Unload != NULL) {
1330 Status = Image->Info.Unload (ImageHandle);
1331 }
1332
1333 } else {
1334 //
1335 // This Image hasn't been started, thus it can be unloaded
1336 //
1337 Status = EFI_SUCCESS;
1338 }
1339
1340
1341 if (!EFI_ERROR (Status)) {
1342 //
1343 // if the Image was not started or Unloaded O.K. then clean up
1344 //
1345 CoreUnloadAndCloseImage (Image, TRUE);
1346 }
1347
1348 Done:
1349 EfiReleaseLock (&mBsUnloadImageLock);
1350 return Status;
1351 }
1352
1353
1354 EFI_STATUS
1355 EFIAPI
1356 CoreUnloadImageEx (
1357 IN EFI_PE32_IMAGE_PROTOCOL *This,
1358 IN EFI_HANDLE ImageHandle
1359 )
1360 /*++
1361
1362 Routine Description:
1363
1364 Unload the specified image.
1365
1366 Arguments:
1367
1368 This - Indicates the calling context.
1369
1370 ImageHandle - The specified image handle.
1371
1372 Returns:
1373
1374 EFI_INVALID_PARAMETER - Image handle is NULL.
1375
1376 EFI_UNSUPPORTED - Attempt to unload an unsupported image.
1377
1378 EFI_SUCCESS - Image successfully unloaded.
1379
1380 --*/
1381 {
1382 return CoreUnloadImage (ImageHandle);
1383 }