Arduino Leonardo 板子上的 LED 分析

正经的 Arduino Leonardo 上面有四个LED(DFrobot 的Leonardo&XBEE V1.2 上面有5个LED)。长得是下面这个样子:

led1

对照电路图 LED 连接如下:

led2

LED 控制Pin 说明
L D13 (PC7) GPIO 控制
TX PD5 USB发送数据亮
RX PB0 USB接收数据亮
ON 5V 上电就亮

初始化在 \arduino-1.8.4\hardware\arduino\avr\cores\arduino\USBCore.cpp 有定义

void USBDevice_::attach()
{
	_usbConfiguration = 0;
	_usbCurrentStatus = 0;
	_usbSuspendState = 0;
	USB_ClockEnable();

	UDINT &= ~((1<<WAKEUPI) | (1<<SUSPI)); // clear already pending WAKEUP / SUSPEND requests
	UDIEN = (1<<EORSTE) | (1<<SOFE) | (1<<SUSPE);	// Enable interrupts for EOR (End of Reset), SOF (start of frame) and SUSPEND
	
	TX_RX_LED_INIT;

#if MAGIC_KEY_POS != (RAMEND-1)
	if (pgm_read_word(FLASHEND - 1) == NEW_LUFA_SIGNATURE) {
		_updatedLUFAbootloader = true;
	}
#endif
}

 

其中的 一些宏定义在 \arduino-1.8.4\hardware\arduino\avr\variants\leonardo\pins_arduino.h

#define TX_RX_LED_INIT	DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED0			PORTD |= (1<<5)
#define TXLED1			PORTD &= ~(1<<5)
#define RXLED0			PORTB |= (1<<0)
#define RXLED1			PORTB &= ~(1<<0)

 

Tx/Rx 的作用是用来指示传输,而实际上传输是一下就发生和结束的,因此,设计上使用了一个延时

/** Pulse generation counters to keep track of the number of milliseconds remaining for each pulse type */
#define TX_RX_LED_PULSE_MS 100
volatile u8 TxLEDPulse; /**< Milliseconds remaining for data Tx LED pulse */
volatile u8 RxLEDPulse; /**< Milliseconds remaining for data Rx LED pulse */

 

当收到数据时,就Enable Led,同时重置计时器

static inline void Recv(volatile u8* data, u8 count)
{
	while (count--)


		*data++ = UEDATX;
	
	RXLED1;					// light the RX LED
	RxLEDPulse = TX_RX_LED_PULSE_MS;	
}

static inline u8 Recv8()
{
	RXLED1;					// light the RX LED
	RxLEDPulse = TX_RX_LED_PULSE_MS;

	return UEDATX;	
}
在每一个 SOF 的时候检查LED
	//	Start of Frame - happens every millisecond so we use it for TX and RX LED one-shot timing, too
	if (udint & (1<<SOFI))
	{
		USB_Flush(CDC_TX);				// Send a tx frame if found
		
		// check whether the one-shot period has elapsed.  if so, turn off the LED
		if (TxLEDPulse && !(--TxLEDPulse))
			TXLED0;
		if (RxLEDPulse && !(--RxLEDPulse))
			RXLED0;
	}

 

例子:

arduino-1.8.4\hardware\arduino\avr\variants\leonardo\pins_arduino.h

#define NUM_DIGITAL_PINS  31
#define NUM_ANALOG_INPUTS 12

/*
#define TX_RX_LED_INIT	DDRD |= (1<<5), DDRB |= (1<<0)
#define TXLED0			PORTD |= (1<<5)
#define TXLED1			PORTD &= ~(1<<5)
#define RXLED0			PORTB |= (1<<0)
#define RXLED1			PORTB &= ~(1<<0)
*/

//labz_Start
#define TX_RX_LED_INIT	DDRD |= (1<<5), DDRB |= (1<<0),DDRF = 0x81
#define TXLED0			PORTD |= (1<<5);PORTF &= ~ 0x01
#define TXLED1			PORTD &= ~(1<<5);PORTF |= 0x01
#define RXLED0			PORTB |= (1<<0);PORTF &= ~ 0x80 
#define RXLED1			PORTB &= ~(1<<0);PORTF |= 0x80
// labz _End

#define PIN_WIRE_SDA         (2)
#define PIN_WIRE_SCL         (3)


// the setup function runs once when you press reset or power the board
void setup() {
  // initialize digital pin LED_BUILTIN as an output.
  pinMode(LED_BUILTIN, OUTPUT);
}

// the loop function runs over and over again forever
void loop() {
  while (Serial.available())
    {  byte c=Serial.read();
       Serial.write(c);
      }
}

 

参考:
1.Leonardo 电路图
https://www.arduino.cc/en/uploads/Main/arduino-leonardo-schematic_3b.pdf
2.引脚关系
http://www.zembedded.com/wp-content/uploads/2013/04/Ardunio_leonardo.png

Step to UEFI (133)再试验 EFI_CPU_ARCH_PROTOCOL

前面提到了 EFI_CPU_ARCH_PROTOCOL ,这次试试这个Protocol的 EnableInterrput 和 DisableInterrupt。

ma1

实验的方法是使用 CpuSleep() 这个函数,在 \UDK2017\MdePkg\Library\BaseCpuLib\X64\CpuSleep.asm 中可以看到具体实现:

    .code
;------------------------------------------------------------------------------
; VOID
; EFIAPI
; CpuSleep (
;   VOID
;   );
;------------------------------------------------------------------------------
CpuSleep    PROC
    hlt
    ret
CpuSleep    ENDP

END

 

就是说他调用了 hlt 这个指令,这个指令的介绍如下,执行这个指令后 CPU 会停机,只有中断才能唤醒CPU。我们在这个函数之后再编写输出字符串的代码,如果能看到就说明CPU被中断唤醒了(更简单的判断:没唤醒就会死机)。
cpp2

最终的代码如下:

/** @file
    A simple, basic, application showing how the Hello application could be
    built using the "Standard C Libraries" from StdLib.

    Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
    This program and the accompanying materials
    are licensed and made available under the terms and conditions of the BSD License
    which accompanies this distribution. The full text of the license may be found at
    http://opensource.org/licenses/bsd-license.

    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Library/BaseLib.h>
#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/PrintLib.h>
#include <Library/ShellCEntryLib.h>

#include <Protocol/Cpu.h>
#include <Library/CpuLib.h>

EFI_GUID gEfiCpuArchProtocolGuid = 
                { 0x26BACCB1, 0x6F42, 0x11D4, 
                        { 0xBC, 0xE7, 0x00, 0x80, 0xC7, 0x3C, 0x88, 0x81 }};
                        
extern EFI_BOOT_SERVICES         *gBS;

/***
  Demonstrates basic workings of the main() function by displaying a
  welcoming message.

  Note that the UEFI command line is composed of 16-bit UCS2 wide characters.
  The easiest way to access the command line parameters is to cast Argv as:
      wchar_t **wArgv = (wchar_t **)Argv;

  @param[in]  Argc    Number of argument tokens pointed to by Argv.
  @param[in]  Argv    Array of Argc pointers to command line tokens.

  @retval  0         The application exited normally.
  @retval  Other     An error occurred.
***/
int
main (
  IN int Argc,
  IN char **Argv
  )
{
  EFI_CPU_ARCH_PROTOCOL  *Cpu;
  EFI_STATUS             Status;
  
  //
  // Locate the Cpu Arch Protocol.
  //
  Status = gBS->LocateProtocol (&gEfiCpuArchProtocolGuid, NULL, &Cpu);
  if (EFI_ERROR (Status)) {
    Print(L"Can't find EFI_CPU_ARCH_PROTOCOL\n");
    return Status;
  }

  Print(L"Running CpuSleep\n");
  CpuSleep();
  Print(L"CpuSleep Exit\n");

  Print(L"Disable CPU interrupt by EFI_CPU_ARCH_PROTOCOL\n");  
  Cpu->DisableInterrupt(Cpu);
  Print(L"Running CpuSleep\n");
  CpuSleep();
  Print(L"CpuSleep Exit\n");
  
  Print(L"Disable CPU interrupt by CLI\n");  
  Print(L"Running CpuSleep\n");  
  DisableInterrupts();
  CpuSleep();  
  EnableInterrupts();  
  Print(L"CpuSleep Exit\n");
  
  return 0;
}

 

运行结果如下(这是在实体机运行的结果):
cpp3
代码中调用了 CpuSleep 函数三次,第一次应该是被UEFI 中的Timer唤醒了,所以运行一下就出来了;第二次调用 CpuSleep函数之前,先用EFI_CPU_ARCH_PROTOCOL 的 DisableInterrupt,但是并没有作用;第三次,我们用CLI 指令关闭所有的中断,于是,程序停下来了,也死机了。

完整的代码下载:

CPUArchTest2

结论: 保险起见,如果你想 Disable Interrupt,那么请使用 cli 这样的指令。后面有空再探究一下为什么这两个函数没有效果。

使用 USB3.0 线 做WinDBG debug

Windows App Store 中推出了新版的 WinDBG,功能上应该和 WDK之类的相同,界面变化很大。

image001
image002

首先用 WinDBG USB 3.0 线将Host(控制端,运行 WinDBG)和Slave(被控制端)连接起来;和之前 USB2.0 的Debug完全不同,Slave上任何一个USB3.0端口都可以,不需要特别查找 Debug Port 。

下图为 Intel Kabylake HDK 平台
image004

下图为我使用的笔记本工作机
image003

之后,需要在 Slave 上MSCONFIG里面做一些设置:
image005

USB target name 设定为 labz,后面 WinDBG的设置也会使用到。设置之后,Slave会要求重启。
启动Host上面的 WinDBG,使用搜索功能,找到长这样的(一个系统中可以安装多个版本的 WinDBG)

image006

界面和之前相比变化很大,看起来没有那么死板了

image007

在 File 中连接的选项,选择 Attach to kernel, USB 页面Target Name 填写上 labz

image008

点击OK按钮之后,HOST和SLAVE即连接起来了

image009

使用 Break 按钮可以停下来
如果发现无法连接,请检查 HOST 的设备管理器 USB Debug Connection Device设备是否有Yellow Bang。 我遇到了这样的情况,显示的错误信息是驱动未签名

image010

例如:

image011

解决方法是:找一个有签名的驱动安装一下。这里放一个我目前在用的,可以试试看

WinDBGUSBDriver(旧版本)

====================================================

20201124 最近开始使用 WinDBG 惊奇的发现又出现了上面提到的问题,经过研究(https://answersweb.azurewebsites.net/MVC/Post/Thread/045cf703-1dbc-4f3f-9557-cba72af2f548?category=wdk),同样应该是驱动版本导致的。

解决方法是找到最新的 SDK 安装之,然后在安装目录下(默认在C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\usb)可以找到最新的驱动。然后问题就可以解决了。

Step to UEFI (132)RamDisk Application 例子

前面提到过 Ram Disk Protocol,这次尝试编写一个 Application 来完成创建 RamDisk 的动作。
首先看一下 Specification:

rd1
rd2

这个 Protocol 提供了2个函数,一个用来注册 RAM Disk 的Register,一个用来销毁 RAM Disk 的 Unregister。对于我们来说,注册的函数是最重要的。

rd3

注册一个Ram Disk 需要给定:
RamDiskBase: 新的 Ram Disk 的基地址
RamDiskSize: 新的 Ram Disk 的大小
RamDiskType: 新的 Ram Disk 的类型(似乎可以定义 ISO/RAW之类的)
ParentDevicePath: 指向父设备的 Device Path(不明白这个功能有什么意义)。如果没有可以设置为 NULL
DevicePath: 返回的创建的 Ram Disk 的 Device Path

有了上面的信息,我们即可完成创建工作。

编写一个测试代码,步骤如下:
1. 查找 RamDiskProtocol
2. 读取 “”MemTest.Img”到内存中
3. 用 RamDiskProtocol 的 Register 函数将上面的内存注册为 Ram Disk

完整代码:

/** @file
    A simple, basic, application showing how the Hello application could be
    built using the "Standard C Libraries" from StdLib.

    Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
    This program and the accompanying materials
    are licensed and made available under the terms and conditions of the BSD License
    which accompanies this distribution. The full text of the license may be found at
    http://opensource.org/licenses/bsd-license.

    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Library/BaseLib.h>
#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/PrintLib.h>
#include <Library/ShellCEntryLib.h>

#include <Protocol/RamDisk.h>

#include <Protocol/DevicePathToText.h>

#include <Protocol/EfiShell.h>
#include <Library/ShellLib.h>

extern EFI_BOOT_SERVICES         *gBS;

/*
EFI_GUID gEfiVirtualDiskGuid = 
           { 0x77AB535A, 0x45FC, 0x624B, 
                {0x55, 0x60, 0xF7, 0xB2, 0x81, 0xD1, 0xF9, 0x6E }};
   */             
/***
  Demonstrates basic workings of the main() function by displaying a
  welcoming message.

  Note that the UEFI command line is composed of 16-bit UCS2 wide characters.
  The easiest way to access the command line parameters is to cast Argv as:
      wchar_t **wArgv = (wchar_t **)Argv;

  @param[in]  Argc    Number of argument tokens pointed to by Argv.
  @param[in]  Argv    Array of Argc pointers to command line tokens.

  @retval  0         The application exited normally.
  @retval  Other     An error occurred.
***/
int
main (
  IN int Argc,
  IN char **Argv
  )
{
        EFI_STATUS               Status;
        EFI_RAM_DISK_PROTOCOL    *MyRamDisk;
        UINT64                   *StartingAddr;
        EFI_DEVICE_PATH_PROTOCOL *DevicePath;
        EFI_FILE_HANDLE          FileHandle;
        EFI_FILE_INFO            *FileInfo;  
        UINTN                    ReadSize; 
  
  // Look for Ram Disk Protocol
        Status = gBS->LocateProtocol (
                        &gEfiRamDiskProtocolGuid,
                        NULL,
                        &MyRamDisk
                 );
        if (EFI_ERROR (Status)) {
            Print(L"Couldn't find RamDiskProtocol\n");
            return EFI_ALREADY_STARTED;
        }

  //Open one Image and load it to the memory
        //Open the file given by the parameter
        Status = ShellOpenFileByName(
                        L"MemTest.IMG", 
                        (SHELL_FILE_HANDLE *)&FileHandle,
                        EFI_FILE_MODE_READ, 
                        0);
        if(EFI_ERROR (Status)) {
                Print(L"OpenFile failed! Error=[%r]\n",Status);
                return EFI_SUCCESS;
        }                                                        
  
        //Get file size
        FileInfo = ShellGetFileInfo((SHELL_FILE_HANDLE)FileHandle);    
        
        //Allocate a memory for Image
        Status = gBS->AllocatePool (
                    EfiReservedMemoryType,
                    (UINTN)FileInfo-> FileSize,
                    (VOID**)&StartingAddr
                    ); 
        if(EFI_ERROR (Status)) {
                Print(L"Allocate Memory failed!\n");
                return EFI_SUCCESS;
        } 
        
        //Load the whole file to the buffer
        Status = ShellReadFile(FileHandle,&ReadSize,StartingAddr);
        if(EFI_ERROR (Status)) {
                Print(L"Read file failed!\n");
                return EFI_SUCCESS;
        } 
        
        //
        // Register the newly created RAM disk.
        //
        Status = MyRamDisk->Register (
             ((UINT64)(UINTN) StartingAddr),
             FileInfo-> FileSize,
             &gEfiVirtualDiskGuid,
             NULL,
             &DevicePath
             );
        if (EFI_ERROR (Status)) {
                Print(L"Can't create RAM Disk!\n");
                return EFI_SUCCESS;
        }

        //Show RamDisk DevicePath
        {
                EFI_DEVICE_PATH_TO_TEXT_PROTOCOL* Device2TextProtocol;
                CHAR16*                           TextDevicePath = 0;
                Status = gBS->LocateProtocol(
                             &gEfiDevicePathToTextProtocolGuid,
                             NULL,
                             (VOID**)&Device2TextProtocol
                        );  
                TextDevicePath = 
                        Device2TextProtocol->ConvertDevicePathToText(DevicePath, FALSE, TRUE); 
                Print(L"DevicePath=%s\n", TextDevicePath);
                Print(L"Disk Size =%d Bytes\n", FileInfo-> FileSize);
                if(TextDevicePath)gBS->FreePool(TextDevicePath);
        }      
  
  Print(L"Creat Ram Disk success!\n");
  return 0;
}

 

运行结果:
rd4

首先,可以看到系统中只有一个 Fs0:, 运行 mrd.efi 之后,系统中多了一个 Fs1,其中的内容就是 MemTest.Img的内容(使用的文件和之前的MemTest.Img 是相同的)。

编译生成的 X64 Application:
mrd

完整的代码:
MyRamDisk

Step to UEFI (131)gBS 的 Stall 探究

gBS 提供的 Stall 函数是我们经常用来做延时的过程。下面就介绍一下这个函数在NT32Pkg 中的具体实现。因为涉及到了具体的实现代码,所以列出来篇幅很长,对于大多数朋友来说直接看中文部分介绍就足够了。

首先,找到原型的定义,在 \MdeModulePkg\Core\Dxe\DxeMain\DxeMain.c

//
// DXE Core Module Variables
//
EFI_BOOT_SERVICES mBootServices = {
.........
  (EFI_EXIT_BOOT_SERVICES)                      CoreExitBootServices,                     // ExitBootServices
  (EFI_GET_NEXT_MONOTONIC_COUNT)                CoreEfiNotAvailableYetArg1,               // GetNextMonotonicCount
  (EFI_STALL)                                   CoreStall,                                // Stall
  (EFI_SET_WATCHDOG_TIMER)                      CoreSetWatchdogTimer,                     // SetWatchdogTimer
  (EFI_CONNECT_CONTROLLER)                      CoreConnectController,                    // ConnectController
.........

 

CoreStall 定义在 \MdeModulePkg\Core\Dxe\Misc\Stall.c 文件中。他接收的参数是暂停多少微秒,在这个函数中,防止计算溢出分别处理了休眠的事件很短和很长的情况,实际完成每一个单位的暂停是同一个函数:CoreInternalWaitForTick

EFI_STATUS
EFIAPI
CoreStall (
  IN UINTN            Microseconds
  )
{
  UINT64  Counter;
  UINT32  Remainder;
  UINTN   Index;

  if (gMetronome == NULL) {
    return EFI_NOT_AVAILABLE_YET;
  }

  //
  // Counter = Microseconds * 10 / gMetronome->TickPeriod
  // 0x1999999999999999 = (2^64 - 1) / 10
  //
  if ((UINT64) Microseconds > 0x1999999999999999ULL) {
    //
    // Microseconds is too large to multiple by 10 first.  Perform the divide 
    // operation first and loop 10 times to avoid 64-bit math overflow.
    //
    Counter = DivU64x32Remainder (
                Microseconds,
                gMetronome->TickPeriod,
                &Remainder
                );
    for (Index = 0; Index < 10; Index++) {
      CoreInternalWaitForTick (Counter);
    }      

    if (Remainder != 0) {
      //
      // If Remainder was not zero, then normally, Counter would be rounded 
      // up by 1 tick.  In this case, since a loop for 10 counts was used
      // to emulate the multiply by 10 operation, Counter needs to be rounded
      // up by 10 counts.
      //
      CoreInternalWaitForTick (10);
    }
  } else {
    //
    // Calculate the number of ticks by dividing the number of microseconds by
    // the TickPeriod.  Calculation is based on 100ns unit.
    //
    Counter = DivU64x32Remainder (
                MultU64x32 (Microseconds, 10),
                gMetronome->TickPeriod,
                &Remainder
                );
    if (Remainder != 0) {
      //
      // If Remainder is not zero, then round Counter up by one tick.
      //
      Counter++;
    }
    CoreInternalWaitForTick (Counter);
  }

  return EFI_SUCCESS;
}

 

做每一个单位休眠的函数是CoreInternalWaitForTick,他调用的是 Metronome Architectural Protocol。

/**
  Internal worker function to call the Metronome Architectural Protocol for 
  the number of ticks specified by the UINT64 Counter value.  WaitForTick() 
  service of the Metronome Architectural Protocol uses a UINT32 for the number
  of ticks to wait, so this function loops when Counter is larger than 0xffffffff.

  @param  Counter           Number of ticks to wait.

**/
VOID
CoreInternalWaitForTick (
  IN UINT64  Counter
  )
{
  while (RShiftU64 (Counter, 32) > 0) {
    gMetronome->WaitForTick (gMetronome, 0xffffffff);
    Counter -= 0xffffffff;
  }
  gMetronome->WaitForTick (gMetronome, (UINT32)Counter);
}

 

gMetronome 是EFI_METRONOME_ARCH_PROTOCOL ,在 \MdeModulePkg\Core\Dxe\DxeMain\DxeMain.c 中

EFI_METRONOME_ARCH_PROTOCOL       *gMetronome     = NULL;

 

具体这个 Protocol 可以在 PI Specification 中找到:
ma1

他的成员包括一个函数和一个变量, WaitForTick 是用来做实际延时的, TickPeriod 是用来说明WaitForTick函数的单位的。TickPeriod的单位是100ns,最长不能超过 200us。为了实验,编写下面的Application:

/** @file
    A simple, basic, application showing how the Hello application could be
    built using the "Standard C Libraries" from StdLib.

    Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.<BR>
    This program and the accompanying materials
    are licensed and made available under the terms and conditions of the BSD License
    which accompanies this distribution. The full text of the license may be found at
    http://opensource.org/licenses/bsd-license.

    THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,
    WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.
**/
#include <Library/BaseLib.h>
#include <Uefi.h>
#include <Library/UefiLib.h>
#include <Library/PrintLib.h>
#include <Library/ShellCEntryLib.h>

#include <Protocol/Metronome.h>

EFI_GUID gEfiMetronomeArchProtocolGuid  = 
                { 0x26BACCB2, 0x6F42, 0x11D4, 
                        { 0xBC, 0xE7, 0x00, 0x80, 0xC7, 0x3C, 0x88, 0x81 }};
                        
extern EFI_BOOT_SERVICES         *gBS;

/***
  Demonstrates basic workings of the main() function by displaying a
  welcoming message.

  Note that the UEFI command line is composed of 16-bit UCS2 wide characters.
  The easiest way to access the command line parameters is to cast Argv as:
      wchar_t **wArgv = (wchar_t **)Argv;

  @param[in]  Argc    Number of argument tokens pointed to by Argv.
  @param[in]  Argv    Array of Argc pointers to command line tokens.

  @retval  0         The application exited normally.
  @retval  Other     An error occurred.
***/
int
main (
  IN int Argc,
  IN char **Argv
  )
{
  EFI_METRONOME_ARCH_PROTOCOL   *Metronome;
  EFI_STATUS                    Status;
  
  //
  // Locate the Cpu Arch Protocol.
  //
  Status = gBS->LocateProtocol (&gEfiMetronomeArchProtocolGuid, NULL, &Metronome);
  if (EFI_ERROR (Status)) {
    Print(L"Can't find EFI_METRONOME_ARCH_PROTOCOL\n");
    return Status;
  }

  Print(L"TickPeriod=%d\n",Metronome->TickPeriod);
  
  return 0;
}

 

运行之后输出结果如下:
ma2
意思是,在 NT32 模拟环境中,一个Tick的时长是 2000*100ns=200us。在Code中,这个值是固定的,在\Nt32Pkg\MetronomeDxe\Metronome.c 定了下面这个结构体:

//
// Global Variables
//
EFI_METRONOME_ARCH_PROTOCOL mMetronome = {
  WinNtMetronomeDriverWaitForTick,
  TICK_PERIOD
};

 

在 \Nt32Pkg\MetronomeDxe\Metronome.h 中给定了TICK_PERIOD 的值,如果把这个定义修改为 2001,那么再次运行 Application ,输出值也会变化

//
// Period of on tick in 100 nanosecond units
//
#define TICK_PERIOD 2000

 

同样的,处理NT32 “硬件”延时相关的代码就是WinNtMetronomeDriverWaitForTick,在\Nt32Pkg\MetronomeDxe\Metronome.c 文件中:

EFI_STATUS
EFIAPI
WinNtMetronomeDriverWaitForTick (
  IN EFI_METRONOME_ARCH_PROTOCOL  *This,
  IN UINT32                       TickNumber
  )
/*++

Routine Description:

  The WaitForTick() function waits for the number of ticks specified by
  TickNumber from a known time source in the platform.  If TickNumber of
  ticks are detected, then EFI_SUCCESS is returned.  The actual time passed
  between entry of this function and the first tick is between 0 and
  TickPeriod 100 nS units.  If you want to guarantee that at least TickPeriod
  time has elapsed, wait for two ticks.  This function waits for a hardware
  event to determine when a tick occurs.  It is possible for interrupt
  processing, or exception processing to interrupt the execution of the
  WaitForTick() function.  Depending on the hardware source for the ticks, it
  is possible for a tick to be missed.  This function cannot guarantee that
  ticks will not be missed.  If a timeout occurs waiting for the specified
  number of ticks, then EFI_TIMEOUT is returned.

Arguments:

  This       - The EFI_METRONOME_ARCH_PROTOCOL instance.
  TickNumber - Number of ticks to wait.

Returns:

  EFI_SUCCESS - The wait for the number of ticks specified by TickNumber
                succeeded.

--*/
{
  UINT64  SleepTime;

  //
  // Calculate the time to sleep.  Win API smallest unit to sleep is 1 millisec
  // Tick Period is in 100ns units, divide by 10000 to convert to ms
  //
  SleepTime = DivU64x32 (MultU64x32 ((UINT64) TickNumber, TICK_PERIOD) + 9999, 10000);
  gWinNt->Sleep ((UINT32) SleepTime);

  return EFI_SUCCESS;
}

 

可以看到,Nt32 虚拟机中最终是使用 Sleep 来实现的,这个Api 最小取值为 1毫秒(千分之一),在编写一些在 NT32模拟环境下运行的程序时,也要特别注意他延时的最小单位只有1毫秒。

对应在具体的实体机上,会有更加精确的延时,有兴趣的朋友不妨追踪一下手中的代码,看看具体是如何实现的。

本文提到的 Application 下载:

METRONOMEARCHTest

zVirtualBattery

This software can simulate a battery under Windows 10 x64. It will install WDTF (Windows Device Testing Framework) to your system. After that you can switch DC/AC or set the battery percent in your system.

zvb

download : https://pan.baidu.com/s/1jHAzoXK
password: jz93

Usage:

1.This utility only works in Windows 10 X64. And it requires administrator privileges for running.

bat2

2.If you has’t installed WDTF, zVirtualBattery will install one for you.
bat3

bat4

3.After WDTF installation, you’d better restart your system

bat5

4. You can switch between virtual and real Battery

bat6

Switch between AC and DC mode

bata

bat7

bat9

bat8

5.You can set the virtual battery percent by track bar and “set” button.

batb

========================================================

2024/03/12

I have tried it in Windows 11. It works well.

Step to UEFI (130)NT32 模拟器中的 Debug Message 输出

一年多以前,提出了个奇怪的想法:是否可以在自己编写的Application中输出到 NT32 的模拟器LOG中?当时遇到的问题是,如果想直接输出必须调用 WinNtThunkDxe 这样的Protocol,而在定义Protocol的时候必须使用Windows.h 的头文件,但是 AppPkg 中无法做到这一点,最终找到的解决方法是修改gST->Reset 。但是很显然,这并非完美的解决方法【参考1】。

最近,忽然想起来,可以重新定义一个自己的 Protocol 头,只要需要用到的函数偏移正确,调用时放入正确的参数同样能正常工作。需要用到的最重要的 Protocol 结构体在  \UDK2017\Nt32Pkg\Include\Protocol\WinNtThunk.h :

typedef struct {
  UINT64                              Signature;

  //
  // Win32 Process APIs
  //
  WinNtGetProcAddress                 GetProcAddress;
  WinNtGetTickCount                   GetTickCount;
  WinNtLoadLibraryEx                  LoadLibraryEx;
  WinNtFreeLibrary                    FreeLibrary;

  WinNtSetPriorityClass               SetPriorityClass;
  WinNtSetThreadPriority              SetThreadPriority;
  WinNtSleep                          Sleep;

  WinNtSuspendThread                  SuspendThread;
  WinNtGetCurrentThread               GetCurrentThread;
  WinNtGetCurrentThreadId             GetCurrentThreadId;
  WinNtGetCurrentProcess              GetCurrentProcess;
  WinNtCreateThread                   CreateThread;
  WinNtTerminateThread                TerminateThread;
  WinNtSendMessage                    SendMessage;
  WinNtExitThread                     ExitThread;
  WinNtResumeThread                   ResumeThread;
  WinNtDuplicateHandle                DuplicateHandle;

  //
  // Wint32 Mutex primitive
  //
  WinNtInitializeCriticalSection      InitializeCriticalSection;
  WinNtEnterCriticalSection           EnterCriticalSection;
  WinNtLeaveCriticalSection           LeaveCriticalSection;
  WinNtDeleteCriticalSection          DeleteCriticalSection;
  WinNtTlsAlloc                       TlsAlloc;
  WinNtTlsFree                        TlsFree;
  WinNtTlsSetValue                    TlsSetValue;
  WinNtTlsGetValue                    TlsGetValue;
  WinNtCreateSemaphore                CreateSemaphore;
  WinNtWaitForSingleObject            WaitForSingleObject;
  WinNtReleaseSemaphore               ReleaseSemaphore;

  //
  // Win32 Console APIs
  //
  WinNtCreateConsoleScreenBuffer      CreateConsoleScreenBuffer;
  WinNtFillConsoleOutputAttribute     FillConsoleOutputAttribute;
  WinNtFillConsoleOutputCharacter     FillConsoleOutputCharacter;
  WinNtGetConsoleCursorInfo           GetConsoleCursorInfo;
  WinNtGetNumberOfConsoleInputEvents  GetNumberOfConsoleInputEvents;
  WinNtPeekConsoleInput               PeekConsoleInput;
  WinNtScrollConsoleScreenBuffer      ScrollConsoleScreenBuffer;
  WinNtReadConsoleInput               ReadConsoleInput;

  WinNtSetConsoleActiveScreenBuffer   SetConsoleActiveScreenBuffer;
  WinNtSetConsoleCursorInfo           SetConsoleCursorInfo;
  WinNtSetConsoleCursorPosition       SetConsoleCursorPosition;
  WinNtSetConsoleScreenBufferSize     SetConsoleScreenBufferSize;
  WinNtSetConsoleTitleW               SetConsoleTitleW;
  WinNtWriteConsoleInput              WriteConsoleInput;
  WinNtWriteConsoleOutput             WriteConsoleOutput;

  //
  // Win32 File APIs
  //
  WinNtCreateFile                     CreateFile;
  WinNtDeviceIoControl                DeviceIoControl;
  WinNtCreateDirectory                CreateDirectory;
  WinNtRemoveDirectory                RemoveDirectory;
  WinNtGetFileAttributes              GetFileAttributes;
  WinNtSetFileAttributes              SetFileAttributes;
  WinNtCreateFileMapping              CreateFileMapping;
  WinNtCloseHandle                    CloseHandle;
  WinNtDeleteFile                     DeleteFile;
  WinNtFindFirstFile                  FindFirstFile;
  WinNtFindNextFile                   FindNextFile;
  WinNtFindClose                      FindClose;
  WinNtFlushFileBuffers               FlushFileBuffers;
  WinNtGetEnvironmentVariable         GetEnvironmentVariable;
  WinNtGetLastError                   GetLastError;
  WinNtSetErrorMode                   SetErrorMode;
  WinNtGetStdHandle                   GetStdHandle;
  WinNtMapViewOfFileEx                MapViewOfFileEx;
  WinNtReadFile                       ReadFile;
  WinNtSetEndOfFile                   SetEndOfFile;
  WinNtSetFilePointer                 SetFilePointer;
  WinNtWriteFile                      WriteFile;
  WinNtGetFileInformationByHandle     GetFileInformationByHandle;
  WinNtGetDiskFreeSpace               GetDiskFreeSpace;
  WinNtGetDiskFreeSpaceEx             GetDiskFreeSpaceEx;
  WinNtMoveFile                       MoveFile;
  WinNtSetFileTime                    SetFileTime;
  WinNtSystemTimeToFileTime           SystemTimeToFileTime;

  //
  // Win32 Time APIs
  //
  WinNtLocalFileTimeToFileTime        LocalFileTimeToFileTime;
  WinNtFileTimeToLocalFileTime        FileTimeToLocalFileTime;
  WinNtFileTimeToSystemTime           FileTimeToSystemTime;
  WinNtGetSystemTime                  GetSystemTime;
  WinNtSetSystemTime                  SetSystemTime;
  WinNtGetLocalTime                   GetLocalTime;
  WinNtSetLocalTime                   SetLocalTime;
  WinNtGetTimeZoneInformation         GetTimeZoneInformation;
  WinNtSetTimeZoneInformation         SetTimeZoneInformation;
  WinNttimeSetEvent                   timeSetEvent;
  WinNttimeKillEvent                  timeKillEvent;

  //
  // Win32 Serial APIs
  //
  WinNtClearCommError                 ClearCommError;
  WinNtEscapeCommFunction             EscapeCommFunction;
  WinNtGetCommModemStatus             GetCommModemStatus;
  WinNtGetCommState                   GetCommState;
  WinNtSetCommState                   SetCommState;
  WinNtPurgeComm                      PurgeComm;
  WinNtSetCommTimeouts                SetCommTimeouts;

  WinNtExitProcess                    ExitProcess;

  WinNtSprintf                        SPrintf;

  WinNtGetDesktopWindow               GetDesktopWindow;
  WinNtGetForegroundWindow            GetForegroundWindow;
  WinNtCreateWindowEx                 CreateWindowEx;
  WinNtShowWindow                     ShowWindow;
  WinNtUpdateWindow                   UpdateWindow;
  WinNtDestroyWindow                  DestroyWindow;
  WinNtInvalidateRect                 InvalidateRect;
  WinNtGetWindowDC                    GetWindowDC;
  WinNtGetClientRect                  GetClientRect;
  WinNtAdjustWindowRect               AdjustWindowRect;
  WinNtSetDIBitsToDevice              SetDIBitsToDevice;
  WinNtBitBlt                         BitBlt;
  WinNtGetDC                          GetDC;
  WinNtReleaseDC                      ReleaseDC;
  WinNtRegisterClassEx                RegisterClassEx;
  WinNtUnregisterClass                UnregisterClass;

  WinNtBeginPaint                     BeginPaint;
  WinNtEndPaint                       EndPaint;
  WinNtPostQuitMessage                PostQuitMessage;
  WinNtDefWindowProc                  DefWindowProc;
  WinNtLoadIcon                       LoadIcon;
  WinNtLoadCursor                     LoadCursor;
  WinNtGetStockObject                 GetStockObject;
  WinNtSetViewportOrgEx               SetViewportOrgEx;
  WinNtSetWindowOrgEx                 SetWindowOrgEx;
  WinNtMoveWindow                     MoveWindow;
  WinNtGetWindowRect                  GetWindowRect;

  WinNtGetMessage                     GetMessage;
  WinNtTranslateMessage               TranslateMessage;
  WinNtDispatchMessage                DispatchMessage;

  WinNtGetProcessHeap                 GetProcessHeap;
  WinNtHeapAlloc                      HeapAlloc;
  WinNtHeapFree                       HeapFree;
  
  WinNtQueryPerformanceCounter        QueryPerformanceCounter;
  WinNtQueryPerformanceFrequency      QueryPerformanceFrequency;
  
} EFI_WIN_NT_THUNK_PROTOCOL;

修改之后的可以直接在 UEFI Application 中进行定义的结构体如下

typedef struct {
  UINT64                              Signature;
  //
  // Win32 Process APIs
  //
  UINTN API1[17];
  //
  // Wint32 Mutex primitive
  //
  UINTN API2[11];  
  //
  // Win32 Console APIs
  //
  UINTN API3[15];    
  //
  // Win32 File APIs
  //
  UINTN API41[16];  
  MyWinNtGetStdHandle                 GetStdHandle;
  UINTN API42[4];   
  MyWinNtWriteFile                    WriteFile;
  UINTN API5[6];   
  //
  // Win32 Time APIs
  //
  UINTN API6[10];   
  //
  // Win32 Serial APIs
  //
  UINTN API7[44];     
} MY_EFI_WIN_NT_THUNK_PROTOCOL;

 

这个结构体中,对我们有用的是  WinNtWriteFile   WriteFile  还有  WinNtGetStdHandle GetStdHandle。只要这两个的偏移正确即可进行调用。对于这两个函数,我们还需要重新改写一下原型,比如之前的定义为:

typedef
WINBASEAPI
BOOL
(WINAPI *WinNtWriteFile) (
  HANDLE        FileHandle,
  LPCVOID       Buffer,
  DWORD         NumberOfBytesToWrite,
  LPDWORD       NumberOfBytesWritten,
  LPOVERLAPPED  Overlapped
  );

 

经过修改之后的如下

typedef
EFI_STATUS
(EFIAPI *MyWinNtWriteFile) (
  IN EFI_HANDLE FileHandle,
  CHAR8*        Buffer,
  UINT32        NumberOfBytesToWrite,
  UINT32*       NumberOfBytesWritten,
  UINT32        Overlapped  
  );

 

就是这样,只要我们定义出正确的函数偏移,再喂给他正确的参数就能够完成调用。最后,完整的代码如下:

/** @file

A simple, basic, application showing how the Hello application could be

built using the "Standard C Libraries" from StdLib.

&nbsp;

Copyright (c) 2010 - 2011, Intel Corporation. All rights reserved.&lt;BR&gt;

This program and the accompanying materials

are licensed and made available under the terms and conditions of the BSD License

which accompanies this distribution. The full text of the license may be found at

http://opensource.org/licenses/bsd-license.

&nbsp;

THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS,

WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED.

**/

#include &lt;Library/BaseLib.h&gt;

#include &lt;Uefi.h&gt;

#include &lt;Library/UefiLib.h&gt;

#include &lt;Library/PrintLib.h&gt;

#include &lt;Library/ShellCEntryLib.h&gt;

&nbsp;

#define STD_OUTPUT_HANDLE -11

&nbsp;

extern EFI_BOOT_SERVICES         *gBS;

&nbsp;

EFI_GUID gEfiWinNtThunkProtocolGuid     =

{ 0x58C518B1, 0x76F3, 0x11D4,

{ 0xBC, 0xEA, 0x00, 0x80, 0xC7, 0x3C, 0x88, 0x81 }};

&nbsp;

typedef

EFI_STATUS

(EFIAPI *MyWinNtWriteFile) (

IN EFI_HANDLE FileHandle,

CHAR8*        Buffer,

UINT32        NumberOfBytesToWrite,

UINT32*       NumberOfBytesWritten,

UINT32        Overlapped

);

&nbsp;

typedef

EFI_HANDLE

(EFIAPI *MyWinNtGetStdHandle) (

EFI_HANDLE   StdHandle

);

typedef struct {

UINT64                              Signature;

//

// Win32 Process APIs

//

UINTN API1[17];

//

// Wint32 Mutex primitive

//

UINTN API2[11];

//

// Win32 Console APIs

//

UINTN API3[15];

//

// Win32 File APIs

//

UINTN API41[16];

MyWinNtGetStdHandle                 GetStdHandle;

UINTN API42[4];

MyWinNtWriteFile                    WriteFile;

UINTN API5[6];

//

// Win32 Time APIs

//

UINTN API6[10];

//

// Win32 Serial APIs

//

UINTN API7[44];

} MY_EFI_WIN_NT_THUNK_PROTOCOL;

&nbsp;

/***

Demonstrates basic workings of the main() function by displaying a

welcoming message.

&nbsp;

Note that the UEFI command line is composed of 16-bit UCS2 wide characters.

The easiest way to access the command line parameters is to cast Argv as:

wchar_t **wArgv = (wchar_t **)Argv;

&nbsp;

@param[in]  Argc    Number of argument tokens pointed to by Argv.

@param[in]  Argv    Array of Argc pointers to command line tokens.

&nbsp;

@retval  0         The application exited normally.

@retval  Other     An error occurred.

***/

int

main (

IN int Argc,

IN char **Argv

)

{

EFI_STATUS                      Status;

MY_EFI_WIN_NT_THUNK_PROTOCOL    *MyWinNTThunkProtocol;

//

// Cache of standard output handle .

//

EFI_HANDLE                      mStdOut;

&nbsp;

CHAR8           Buffer[200];

UINT32          CharCount;

&nbsp;

//

// Look for Ram Disk Protocol

//

Status = gBS-&gt;LocateProtocol (

&amp;gEfiWinNtThunkProtocolGuid,

NULL,

(VOID **)&amp;MyWinNTThunkProtocol

&nbsp;

);

if (EFI_ERROR (Status)) {

Print(L"Couldn't find WinNtThunkProtocol\n");

return EFI_ALREADY_STARTED;

}

&nbsp;

Print(L"Found WinNt Thunk\n");

//

// Cache standard output handle.

//

mStdOut = MyWinNTThunkProtocol-&gt; GetStdHandle

((EFI_HANDLE)STD_OUTPUT_HANDLE);

Print(L"mStdOut=%X\n",mStdOut);

&nbsp;

CharCount = (UINT32)AsciiSPrint (

Buffer,

sizeof (Buffer),

"www.lab-z.com %X\n\r",

2017

);

&nbsp;

//

// Callout to standard output.

//

MyWinNTThunkProtocol-&gt;WriteFile (

mStdOut,

Buffer,

CharCount,

&amp;CharCount,

0

);

&nbsp;

return EFI_SUCCESS;

}

 

我们在 NT32 的Shell中调用编写好的 Application 2次:

nt1

对应在Log中可以看到有2次输出
nt2

参考:

  1. http://www.lab-z.com/stu82/ NT32Pkg的Debug Message

2018年1月4日 krishnaLee 给出了一个更简单高效的方法,亲测有效:

1,在Nt32Pkg.dsc的【component】区域写:
SampleAppDebug/SampleApp.inf {

gEfiMdePkgTokenSpaceGuid.PcdDebugPropertyMask|0xff
gEfiMdePkgTokenSpaceGuid.PcdDebugPrintErrorLevel|0xffffffff
}
2,编译:build -p Nt32Pkg\Nt32Pkg.dsc -m SampleAppDebug\SampleApp.inf
3,运行。

附件是例子的 application:

SampleAppDebug