UEFI shell - 标准应用程序的编译和加载过程

一、标准应用工程编译

首先了解下,应用程序是怎么被编译成.efi文件:

  1. UefiMain.c首先被编译成目标文件UefiMain.obj
  2. 连接器将目标文件UefiMain.obj和其他库连接成UefiMain.dll
  3. GenFw工具将UefiMain.dll转换成UefiMain.efi

说明:连接器在生成UefiMain.dll时使用了/dll/entry:_ModuleEntryPoint..efi是遵循PE32格式的二进制文件,_ModuleEntryPoint是这个二进制的入口函数

模块入口函数一般为UefiMain,但在inf工程文件里面可以更改

ENTRY_POINT                    = UefiMain

那么_ModuleEntryPoint跟UefiMain有什么关系呢?

让我们带着这个疑问来看应用程序的加载过程

二、标准应用程序加载

2.1将UefiMain.efi加载到内存

在shell下执行UefiMain.c时,shell执行的大致步骤:

  1. 首先用gBS->LoadImage()将UefiMain.efi文件加载到内存生成Image对象
  2. 然后调用gBS->StartImage(Image)启动这个对象.
    代码清单如下:
edk2/ShellPkg/Application/Shell/ShellProtocol.c
EFI_STATUS
InternalShellExecuteDevicePath(
  IN CONST EFI_HANDLE               *ParentImageHandle, //正在执行命令行的句柄
  IN CONST EFI_DEVICE_PATH_PROTOCOL *DevicePath, //UefiMain.efi的设备路径
  IN CONST CHAR16                   *CommandLine OPTIONAL, //应用程序所需的命令行参数
  IN CONST CHAR16                   **Environment OPTIONAL, //UEFI环境变量
  OUT EFI_STATUS                    *StartImageStatus OPTIONAL  //程序UefiMain.efi的返回值
  )
{
...
  //第一步:将UefiMain.efi文件加载到内存, 生成Image对象,NewHandle是这个对象的句柄
  Status = gBS->LoadImage(
    FALSE,
    *ParentImageHandle,
    (EFI_DEVICE_PATH_PROTOCOL*)DevicePath,
    NULL,
    0,
    &NewHandle);

  if (EFI_ERROR(Status)) {
    if (NewHandle != NULL) {
      gBS->UnloadImage(NewHandle);
    }
    FreePool (NewCmdLine);
    return (Status);
  }

//第二步:取得命令行参数,并将命令行参数交给UefiMain.efi的Image对象,即NewHandle
  Status = gBS->OpenProtocol(
    NewHandle,
    &gEfiLoadedImageProtocolGuid,
    (VOID**)&LoadedImage,
    gImageHandle,
    NULL,
    EFI_OPEN_PROTOCOL_GET_PROTOCOL);

  if (!EFI_ERROR(Status)) {
    ASSERT(LoadedImage->LoadOptionsSize == 0);
    if (NewCmdLine != NULL) {
      LoadedImage->LoadOptionsSize  = (UINT32)StrSize(NewCmdLine);
      LoadedImage->LoadOptions      = (VOID*)NewCmdLine;
    }
...省略
//第三步:启动所加载的Image
  if (!EFI_ERROR(Status)) {
      StartStatus      = gBS->StartImage(
                          NewHandle,
                          0,
                          NULL
                          );
      if (StartImageStatus != NULL) {
        *StartImageStatus = StartStatus;
      }
      
}

加载应用程序最重要的一步,就是gBS->StartImage(NewHandle, 0,NULL)。StartImage主要作用就是找出可执行映象(Image)的入口函数并执行找到的入口函数。gBS-》StartImage是一个函数指针,它实际指向CoreStartImage函数

2.2进入映象的入口函数

CoreStartImage的主要作用调用映象的入口函数。CoreStartImage如下:

edk2/MdeModulePkg/Core/Dxe/Image/Image.c
/**
  Transfer control to a loaded image's entry point.

  @param  ImageHandle             Handle of image to be started.
  @param  ExitDataSize            Pointer of the size to ExitData
  @param  ExitData                Pointer to a pointer to a data buffer that
                                  includes a Null-terminated string,
                                  optionally followed by additional binary data.
                                  The string is a description that the caller may
                                  use to further indicate the reason for the
                                  image's exit.

  @retval EFI_INVALID_PARAMETER   Invalid parameter
  @retval EFI_OUT_OF_RESOURCES    No enough buffer to allocate
  @retval EFI_SECURITY_VIOLATION  The current platform policy specifies that the image should not be started.
  @retval EFI_SUCCESS             Successfully transfer control to the image's
                                  entry point.

**/
EFI_STATUS
EFIAPI
CoreStartImage (
  IN EFI_HANDLE  ImageHandle,
  OUT UINTN      *ExitDataSize,
  OUT CHAR16     **ExitData  OPTIONAL
  )
{
...省略
//设置LongJump,用于退出此程序
  Image->JumpBuffer = AllocatePool (sizeof (BASE_LIBRARY_JUMP_BUFFER) + BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);
  if (Image->JumpBuffer == NULL) {
  ...
    return EFI_OUT_OF_RESOURCES;
  }
  Image->JumpContext = ALIGN_POINTER (Image->JumpBuffer, BASE_LIBRARY_JUMP_BUFFER_ALIGNMENT);

  SetJumpFlag = SetJump (Image->JumpContext);
  //首次调用SetJump()返回0。通过LongJump(Image->JumpContext)跳转到此处时返回非零值
   if (SetJumpFlag == 0) {
    RegisterMemoryProfileImage (Image, (Image->ImageContext.ImageType == EFI_IMAGE_SUBSYSTEM_EFI_APPLICATION ? EFI_FV_FILETYPE_APPLICATION : EFI_FV_FILETYPE_DRIVER));
    //调用Image的入口函数
    Image->Started = TRUE;
    Image->Status = Image->EntryPoint (ImageHandle, Image->Info.SystemTable);
    //设置执行后的状态,然后通过LongJump跳到应用程序退出点
    CoreExit (ImageHandle, Image->Status, 0, NULL);
  }
//此处是应用程序退出点
//程序通过LongJump跳转到此处,然后根据Image->进行错误处理
...
}

在gBS->StartImge中,SetJump/LongJump为应用程序提供了一种错误处理机制,如下:
在这里插入图片描述
gBS->StartImge的核心是Image->EntryPoint(),它就是程序映象的入口函数,对应用程序来说,就是_ModuleEntryPoint后,控制权才转交给应用程序(此处就是我们的UefiMain.efi),_ModuleEntryPoint代码如下:

edk2/MdePkg/Library/UefiApplicationEntryPoint/ApplicationEntryPoint.c
/**
  Entry point to UEFI Application.

  This function is the entry point for a UEFI Application. This function must call
  ProcessLibraryConstructorList(), ProcessModuleEntryPointList(), and ProcessLibraryDestructorList().
  The return value from ProcessModuleEntryPointList() is returned.
  If _gUefiDriverRevision is not zero and SystemTable->Hdr.Revision is less than _gUefiDriverRevison,
  then return EFI_INCOMPATIBLE_VERSION.

  @param  ImageHandle                The image handle of the UEFI Application.
  @param  SystemTable                A pointer to the EFI System Table.

  @retval  EFI_SUCCESS               The UEFI Application exited normally.
  @retval  EFI_INCOMPATIBLE_VERSION  _gUefiDriverRevision is greater than SystemTable->Hdr.Revision.
  @retval  Other                     Return value from ProcessModuleEntryPointList().

**/
EFI_STATUS
EFIAPI
_ModuleEntryPoint (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS                 Status;

  if (_gUefiDriverRevision != 0) {
    //确保系统平台的UEFI版本号大于或者等于ImageHandle的UEFI版本号
    if (SystemTable->Hdr.Revision < _gUefiDriverRevision) {
      return EFI_INCOMPATIBLE_VERSION;
    }
  }
  //所有将被使用的库的构造函数
  ProcessLibraryConstructorList (ImageHandle, SystemTable);
  //调用Image的入口函数
  Status = ProcessModuleEntryPointList (ImageHandle, SystemTable);
  //所有库的析构函数
  ProcessLibraryDestructorList (ImageHandle, SystemTable);
  // Return the return status code from the driver entry point
  return Status;
}

_ModuleEntryPoint主要处理三个事情:

  1. 初始化:在初始化函数ProcessLibraryConstructorList中会调用一系列的构造函数
  2. 调用本模块的入口函数:在ProcessModuleEntryPointList中会调用应用程序模块的真正入口函数(即我们在inf文件定义的入口函数UefiMain)
  3. 析构:在析构函数ProcessLibraryDestructorList中会调用一系列析构函数

那么上面这三个函数是在哪里定义的呢?

在执行build命令的时候,build命令会解析模块的工程文件(即inf文件),然后生成AutoGen.h和AutoGen.c,这三个函数就是在AutoGen.c中定义的。
一般而言,在inf文件的 [LibraryClasses] 段声明了某个库后,如果这个库有构造函数,AutoGen便会在ProcessLibraryConstructorList中加入这个库的构造函数,另外,ProcessLibraryConstructorList还会加入启动服务和运行时服务的构造函数。
这里看一个例子:
inf PATH:

edk2/MdeModulePkg/Application/HelloWorld/HelloWorld.inf

把该工程加到OvmfPkg中编译,找到它编译生成的AutoGen.c:

edk2/Build/OvmfX64/DEBUG_GCC5/X64/MdeModulePkg/Application/HelloWorld/HelloWorld/DEBUG/AutoGen.c
...省略

//库构造
VOID
EFIAPI
ProcessLibraryConstructorList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{
  EFI_STATUS  Status;

  Status = PlatformDebugLibIoPortConstructor ();
  ASSERT_RETURN_ERROR (Status);
  //初始化全局变量gBS、gST和gImageHandle
  Status = UefiBootServicesTableLibConstructor (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);
  //初始化全局变量gRT
  Status = UefiRuntimeServicesTableLibConstructor (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);

  Status = DevicePathLibConstructor (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);
  //初始化UefiLib,Print函数就是在UefiLib中实现的
  Status = UefiLibConstructor (ImageHandle, SystemTable);
  ASSERT_EFI_ERROR (Status);

}

//析构
VOID
EFIAPI
ProcessLibraryDestructorList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )
{

}

//入口
EFI_STATUS
EFIAPI
ProcessModuleEntryPointList (
  IN EFI_HANDLE        ImageHandle,
  IN EFI_SYSTEM_TABLE  *SystemTable
  )

{
  //工程入口函数
  return UefiMain (ImageHandle, SystemTable);
}

...省略

gBS指向启动服务表,gST指向系统表(System Table),gImageHandle指向正在执行的驱动或者服务程序,gRT指向运行时服务表,这几个全局变量在开发应用程序和驱动程序是会经常用到。使用gBS、gST、gImageHandle钱需加 #include <Library/UefiBootServicesTableLib.h>。使用gRT之前需加 #include <Library/UefiRuntimeServicesTableLib.h>

与构造函数相似,AutoGen会在ProcessLibraryDestructorList调用相应的析构函数。在这里里面是空的,是因为UefiBootServiceTableLib、UefiRuntimeServicesTableLib、UefiLib这三个Library都没有析构函数。

最后在ProcessModuleEntryPointList中调用应用程序工程模块的真正入口函数UefiMain

回顾下标准应用程序工程模块的调用过程:
LoadImage -> StartImage -> _ModuleEntryPoint -> ProcessModuleEntryPointList -> UefiMain

本文来源:
《UEFI原理与编程》戴正华著

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值