Smart AMP

最近研究了一下 Audio 方面的 Smart AMP ,这里简单做一个总结。如果有不准确的地方欢迎大家讨论指出。

Smart AMP 是 TI 在 CES 2015上公布的一种音频技术【参考1】。

简单的说:Smart Amp 表示 Smart Amplifiers,是一种用来在功率小喇叭上播放更大声音的技术。比如:笔记本安装 2W 的喇叭(成本限制或者机构限制只能使用这个功率的),使用这种技术之后可以播放出来 10W 的声音。2W喇叭的意思是:这款只能按照2W功率使用,如果超过这个功率可能会导致喇叭烧毁。Smart Amp 的技术类似于 CPU Turbo,长时间可能会烧毁,我短时间使用偶尔冲上去一次就不会烧毁;我一直监视喇叭的温度和电压更加保证它不会损坏(这句话来自【参考2】,感觉这个功能是通过计算提供给喇叭的电压电流来实现的,并没有外部的温度传感器)

比如,图中左侧是未使用这个技术的时候,2W的喇叭只能按照2W的功率使用,超过2W会有损坏之虞;右侧是这使用这个技术之后,可以看到短时间可以让喇叭功率冲到30W。图片来自【参考3】.

参考:

  1. https://semiaccurate.com/2015/02/02/tis-smart-amp-tunes-signals-avoid-speaker-problems/ TI’s Smart Amp tunes signals to avoid speaker problems
  2. https://www.ti.com/lit/an/slaa757/slaa757.pdf
  3. https://www.notebookcheck.net/Laptops-101-Designing-a-capable-laptop-audio-subsystem.430253.0.html

FireBeetle 帮你把手机变成键盘鼠标

这次做的项目能够帮你把手上的手机变成能够控制电脑的键盘和鼠标。

基本原理上是:用户通过手机应用程序经由BLE蓝牙和FireBeetle 进行通讯,FireBeetle收到之后再通过USB接口将数据发送到电脑上。从原理上看整体分作三部分:硬件的选择和设计,Arduino 代码的编写和手机端程序设计。

首先介绍硬件的选择和设计。FireBeetle是DFRobot 出品的基于 ESP32 的开发板,它能够支持蓝牙和 WIFI 的通讯,它带有USB转串口芯片但是无法将自身模拟为USB键盘鼠标设备,为了实现这个功能,还需要设计一个USB键盘鼠标Shield。经过研究,最终选择了 WCH 出品的CH9329芯片进行实现。CH9329是一款串口转标准 USB HID 设备(键盘、鼠标、自定义 HID)芯片,根据不同的工作模式,在电脑上可被识别为标准的 USB 键盘设备、 USB 鼠标设备或自定义 HID 类设备。该芯片接收客户端发送过来的串口数据,并按照 HID 类设备规范,将数据先进行打包再通过 USB 口上传给计算机。这款芯片基本特性如下:

●支持 12Mbps 全速 USB 传输,兼容 USB V2.0,内置晶振。
● 默认串口通信波特率为 9600bps,支持各种常见波特率。
● 支持 5V 电源电压和 3.3V 电源电压。
● 多种芯片工作模式, 适应不同应用需求。
● 多种串口通信模式,灵活切换。
● 支持普通键盘和多媒体键盘功能,支持全键盘功能。
● 支持相对鼠标和绝对鼠标功能。
● 支持自定义 HID 类设备功能,可用于单纯数据传输。
● 支持 ASCII 码字符输入和区位码汉字输入。
● 支持远程唤醒电脑功能。
● 支持串口或 USB 口配置芯片参数。
● 可自行配置芯片的 VID、 PID,以及芯片各种字符串描述符。
● 可自行配置芯片的默认波特率。
● 可自行配置芯片通信地址,实现同一个串口下挂载多个芯片。
● 可自行配置回车字符。
● 可自行配置过滤字符串,以便进行无效字符过滤。
● 符合 USB 相关规范,符合 HID 类设备相关规范。
● 采用小体积的 SOP-16 无铅封装,兼容 RoHS。

对于这次的设计来说,通过串口就能实现USB键盘鼠标,非常方便。确定了芯片之后,接下来即可着手Shield设计了。电路设计如下:

左侧和中间是 FireBeetle 的接口,右侧是USB 公头,右下是CH9329芯片。

下面是CH9329 的最小系统电路,芯片内置了晶振,外部只需要一个0.1uf(C1)的电容即可正常工作。

图中的 Pin1 是用来标志芯片配置完成的引脚(#ACT),Pin2、3、4、5是用来配置芯片功能的引脚,通过组合可以在上电的时候实现芯片的功能选择。

工作模式MODE1电平MODE0 电平功能说明
模式011模拟标准USB键盘+USB鼠标设备+USB自定义HID类设备(默认)
该模式下CH9329芯片在电脑上识别为USB键盘、USB鼠标和自定义HID类设备的多功能复合设备,USB键盘包含普通键和多媒体键, USB鼠标包含相对鼠标和绝对鼠标。
该模式功能最全,可以实现USB键盘和USB鼠标的全部功能。 MODE0引脚和MODE1引脚内置了上拉电阻,当这两个引脚悬空时,芯片处于本模式。
模式110模拟标准USB键盘设备
该模式下CH9329芯片在电脑上识别为单一USB键盘设备, USB键盘只包含普通键,不包含多媒体键,支持全键盘模式,适用于部分不支持复合设备的系统。
模式201模拟标准USB键盘+USB鼠标设备
该模式下CH9329芯片在电脑上识别为USB键盘和USB鼠标的多功能复合设备, USB键盘包含普通键和多媒体键, USB鼠标包含相对鼠标和绝对鼠标。
注: Linux/Android/苹果等操作系统下, 出于兼容性考虑,建议使用该模式。  
模式300模拟标准USB自定义HID类设 该模式下CH9329芯片在电脑上识别为单一USB自定义HID类设备,具有上传和下传2个通道,可以实现串口和HID数据透传功能。CH9329芯片如果接收到串口数据,则打包通过USB上传,如果接收到USB下传数据,则通过串口进行发送。 这个模式可以方便用户实现串口转HID。  
串口通信模式CFG1电平CFG0电平功能
模式011协议传输模式(默认)
该模式一般适用于既需要使用USB键盘功能,又
需要使用USB鼠标功能的应用。如果需要使用全
键盘功能,也建议采用该模式。 CFG0引脚和CFG1引脚内置了上拉电阻,当这两个引脚悬空时,芯片处于本模式。
模式110ASCII模式
该模式下客户串口设备向CH9329芯片发送串口
数据时,可以发送ASCII码字符数据,也可以发
送区位码汉字数据。
该模式适用于只需要使用USB键盘中可见ASCII
字符的应用。
模式201透传模式
该模式下客户串口设备向CH9329芯片发送串口
数据时,可以是任意16进制数据。
该模式适用于CH9329芯片处于芯片工作模式3的
应用。  

PCB 设计如下:

3D预览:

接下来开始手机端程序的设计。经过考察,选择了点灯科技出品的 Blinker,这是一套专业且易用物联网解决方案,提供了服务器、应用、设备端SDK支持。简单便捷的应用配合多设备支持的SDK,可以让开发者在3分钟内实现设备的接入。 点灯服务有三个版本,社区版开源且免费,让大家可以体验到点灯方案的特点和优势;云服务版提供更多增值服务与功能,且有效降低客户的项目实施成本,让客户更快的进行物联网升级;商业版可进行独立部署,可以满足客户更多样的需求。这次我们使用它提供的ESP32 支持通过蓝牙连接FireBeetle 开发板。首先,安装 Arduino 的库,在https://diandeng.tech/dev 页面下载 Arduino 库。之后解压放到 Arduino 的 Library目录下。

之后,烧写示例文件:

\blinker-library\examples\Blinker_Widgets\Blinker_Button\Button_BLE\Button_BLE.ino

打开手机上的“点灯 Blinker”程序之后开始创建控制设备的应用:

1.创建一个新设备:

2.添加一个独立设备

3.选择蓝牙接入

4.这时手机会执行一个搜索蓝牙设备的动作,这也是为什么要提前刷上一个示例代码的原因

5.在界面上放置一个输入框(当作键盘用于输入字符),一个摇杆组件(用于控制鼠标)和六个按钮(分别用于实现鼠标左键单击,左键双击,中键单击,右键单击,以及输入键盘回车键)

6.每个组件可以进行属性的调整,包括显示的文字和名称。

设置好了之后,在界面上操作数据可以在Arduino 的串口监视器中看到当有事件信息,其中有摇杆的动作、按钮事件和文本框的输入内容。

接下来就可以进行 Arduino 代码的编写了, 关键代码有:

  1. 代码首部加入#define BLINKER_BLE这个定义后, Blinker 库能够帮助用户完成大部分的蓝牙操作,使用者只需要专注于“收到数据如何处理”而不必关心“如何收到数据”。
  2. Setup函数中通过Button1.attach(button1_callback); 绑定按键和处理函数,当按键发生后会自动调用 button1_callback() 函数来处理;
  3.  Setup函数中通过Blinker.attachData(dataRead);绑定数据处理函数, dataRead() 函数能够收到输入框和摇杆的数据;
  4. 收到的输入框数据是 ASCII 码,通过Asc2Scancode() 函数转化为HID Scancode 再发送给 CH9329 芯片;
#define BLINKER_PRINT Serial
#define BLINKER_BLE
#include <Blinker.h>

//键盘数据
char keypress[]  = {0x57, 0xAB, 0x00, 0x02, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10};
//鼠标数据
char mousemove[] = {0x57, 0xAB, 0x00, 0x05, 0x05, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00};

// 左键单击
BlinkerButton Button1("btn-l1");
// 左键双击
BlinkerButton Button2("btn-l2");
// 右键单击
BlinkerButton Button3("btn-r1");
// 中键单击
BlinkerButton Button4("btn-m1");
// 回车
BlinkerButton Button5("btn-rtn");

// 左键单击
void button1_callback(const String & state) {
  BLINKER_LOG("Left Click ", state);
  // 触发鼠标左键
  mousemove[6] = 0x01;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
  // 鼠标左键抬起
  mousemove[6] = 0x00;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
}
// 左键双击
void button2_callback(const String & state) {
  BLINKER_LOG("Left Double Click ", state);
  // 触发鼠标左键
  mousemove[6] = 0x01;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
  // 鼠标左键抬起
  mousemove[6] = 0x00;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(20);
  // 再来一次
  mousemove[6] = 0x01;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
  mousemove[6] = 0x00;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(20);
}
// 右键单击
void button3_callback(const String & state) {
  BLINKER_LOG("Right Click ", state);
  // 触发鼠标右键
  mousemove[6] = 0x02;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
  mousemove[6] = 0x00;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
}
// 中键双击
void button4_callback(const String & state) {
  BLINKER_LOG("Middle Click ", state);
  // 触发鼠标中键
  mousemove[6] = 0x04;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
  mousemove[6] = 0x00;
  SendData((byte*)mousemove, sizeof(mousemove));
  delay(10);
}
// 回车
void button5_callback(const String & state) {
  BLINKER_LOG("Enter ", state);
  // 键盘回车
  keypress[7] = 0x28;
  SendData((byte*)keypress, sizeof(keypress));
  delay(10);
  keypress[7] = 0;
  SendData((byte*)keypress, sizeof(keypress));
  delay(10);
}
// 将 Buffer 指向的内容,size 长度,计算 checksum 之后发送到Serial2
void SendData(byte *Buffer, byte size) {
  byte sum = 0;
  for (int i = 0; i < size - 1; i++) {
    Serial2.write(*Buffer);
    sum = sum + *Buffer;
    Buffer++;
  }
  *Buffer = sum;
  Serial2.write(sum);
}
// 将ASCII 字符转化为 HID Scancode值
byte Asc2Scancode(byte Asc, boolean *shift) {
  if ((Asc >= 'a') && (Asc <= 'z')) {
    *shift = false;
    return (Asc - 'a' + 0x04);
  }
  if ((Asc >= 'A') && (Asc <= 'Z')) {
    *shift = true;
    return (Asc - 'A' + 0x04);
  }
  if ((Asc >= '1') && (Asc <= '0')) {
    *shift = false;
    return (Asc - '0' + 0x1E);
  }
  if (Asc == '>') {
    *shift = true;
    return (0x37);
  }
  if (Asc == '.') {
    *shift = false;
    return (0x37);
  }
  if (Asc == '_') {
    *shift = true;
    return (0x2D);
  }    
  if (Asc == '-') {
    *shift = false;
    return (0x2D);
  }    
  return 0;
}
// 如果未绑定的组件被触发,则会执行其中内容
// 这里的游戏摇杆和输入框都会在这里处理
void dataRead(const String & data)
{
  BLINKER_LOG("Blinker readString: ", data);
  // 判断是否为游戏摇杆
  if (data.indexOf("joy") != -1) {
    BLINKER_LOG("Joy Move");
    String StrX, StrY;
    // 将摇杆坐标从输入中分离出来
    StrX = data.substring(data.indexOf("[") + 1, data.indexOf(","));
    StrY = data.substring(data.indexOf(",") + 1, data.indexOf("]"));
    BLINKER_LOG("", StrX); BLINKER_LOG("", StrY);
    // 摇杆数据按照鼠标发送出去
    mousemove[7] = map(StrX.toInt(), 0, 255, -127, 127);
    mousemove[8] = map(StrY.toInt(), 0, 255, -127, 127);
    SendData((byte*)mousemove, sizeof(mousemove));
    delay(10);
    mousemove[7] = 0;
    mousemove[8] = 0;
  } else {
    boolean shift;
    byte scanCode;
    for (int i = 0; i < data.length(); i++) {
      BLINKER_LOG("Key In", data.charAt(1));
      // 将收到的 ASCII 转为 ScanCode
      scanCode = Asc2Scancode(data.charAt(i), &shift);
      // 一些按键当有 Shift 按下时会发生转义
      if (scanCode != 0) {
        if (shift == true) {
          keypress[5] = 0x02;
        }
        BLINKER_LOG("Scancode", scanCode);
        // 填写要发送的 ScanCode
        keypress[7] = scanCode;
        SendData((byte*)keypress, sizeof(keypress));
        delay(10);
        keypress[5] = 0x00; keypress[7] = 0;
        SendData((byte*)keypress, sizeof(keypress));
        delay(10);
      }
    }
  }
}

void setup() {
  // 初始化调试串口
  Serial.begin(115200);
  // 初始 CH9329 串口
  Serial2.begin(9600);
#if defined(BLINKER_PRINT)
  BLINKER_DEBUG.stream(BLINKER_PRINT);
#endif

  // 初始化blinker
  Blinker.begin();
  Blinker.attachData(dataRead);
  Button1.attach(button1_callback);
  Button2.attach(button2_callback);
  Button3.attach(button3_callback);
  Button4.attach(button4_callback);
  Button5.attach(button5_callback);
}

void loop() {
  Blinker.run();
}

工作的视频

https://mc.dfrobot.com.cn/thread-312785-1-1.html#pid511208

Intel平台调试的几个概念

在这个页面 https://www.intel.com/content/www/us/en/developer/articles/technical/software-security-guidance/secure-coding/intel-debug-technology.html有几个关于 Intel 平台调试基本概念。

首先,如同使用工具进行测量一定会有误差一样,产品天生会有Bug,一些用户要求的产品特性在另外一些用户严重就是Bug。比如,当Setup 中设置 USB Controller 为 Disable 之后,有些用户会发现仍然能够通过USB键盘进入 BIOS Setup界面,而有的用户则会抱怨修改之后USB键盘完全失效,甚至无法进去BIOS Setup 修改选项。芯片产品更有芯片级调试的需求。但是调试不可避免的碰到用户的数据,比如:反编译追踪,另外这种技术还可能会被用于破解产品,比如,经过研究让客户设计只能运行 Windows的平台能够运行 Linux这种。因此,只能尽量在二者之间寻找平衡点。以我的经验而言,市面上大多数XX产品留有后门的新闻中提到的所谓的“后门”通常都只是预留的调试接口。

对于这种平衡,Intel 采用的策略主要是:区分开发者/调试者和最终用户的策略。比如,开发者的权限更高,能够读写一些最终用户无法看到的寄存器这种。

下面是产品声明周期的示意图,可以看到包含4个阶段:

  1. 芯片的生产制造à2.交给厂商制造电路(比如:主板)à3.厂商制造机器(比如: 笔记本、平板等等)à4.返修。其中的1 2 过程是明显需要有调试能力的,作为BIOS工程师通常工作在这两个阶段。在阶段3之后就要交付给客户了。

为了解决调试和安全之间的矛盾,提出了“Protection Classes”的概念。它是用来控制当前能进行的系统级别调试能力的。它分为三个级别:

  • Public (之前也被称作“Green”或者“Locked”)。这个级别是普通用户能够接触到的级别,安全等级最高,调试能力最低
  • “OxM(之前也被称作“Orange”或者“OEM UnLocked”)。这个级别在 Public 级别上增加了更多的调试能力。这个级别假定的用户是 OxM 厂商。
  • “Intel”(之前也被称为“Read”或者 “Intel Unlocked”)。比前一个 OxM具有更高的调试能力。因为这个级别需要Intel 授权,假定的用户是 Intel。

个人感觉,诸如 BIOS  Debug Log 或者 EC log 是 OxM 级别的调试手段,特别是EC 的数据也只有 OxM 能够获取(需要特别版本的 EC Firmware),同时也只有 OxM才能解读。

为了更好的平衡调试和用户隐私的关系,Intel 引入了Hardware-based Policy Protection 用于管理调试能力。在特殊情况下,可以通过左侧的 Hardware-based Authentication Logic 和 Security Processor 打开目标机的调试能力,对应的右侧的Block X 是SoC 内部的IP,每一个IP 都有预留的用于调试的功能(Debug Capability)。

在上电过程中,会有一个窗口期,如果在这个事件段内有Intel授权,那么可以打开调试功能。(There is a limited time during the boot for which this feature can be used by an Intel entity (i.e., an entity authenticated by a per-part Intel key hash stored in the product).  The entity must perform the authentication (and unlocking) through this hardware-based mechanism before any secure assets are distributed from its rest location (note: “rest location” refers to where an asset is stored)

但是注意,前面提到默认情况下是一个“窗口期”,如果过了这个时间点,那就不行(除非再次上电)。如果想让再任何时候都能够进行调试,那么需要打开 Delayed Authentication 功能,这个可以在 FIT 中设置,也可以在BIOS Setup界面设置。二者是等效的,BIOS 的设置也是告知 CSME 进行调整。所以,Delayed Authentication的作用是:让芯片处于正常模式,当有调试需要的时候再打开调试功能进行 Dbc或者CCA 的连接。

EDK2 202205 来了

目前最新的 EDK2 是 edk2-stable202205,可以在下面的链接下载到:

https://github.com/tianocore/edk2/releases/tag/edk2-stable202205

这次更新了如下内容:

和之前一样,补完下面三个模块的代码(下面的两个brotli是同一套):

  • CryptoPkg/Library/OpensslLib/openssl
  • MdeModulePkg/Universal/RegularExpressionDxe/oniguruma
  • MdeModulePkg/Library/BrotliCustomDecompressLib/brotli
  • BaseTools/Source/C/BrotliCompress/brotli

之后,可以正常编译 EmuPkg和OVMF代码。

EDK2 202205 EmuPKG 编译结果
EDK2 202205 EmuPKG 编译结果

下面是补完的代码,146MB:

链接: https://pan.baidu.com/s/1jSCa-3S9hWpVUQadDtgfRA?pwd=labz 提取码: labz

接下来是一个VirtualBox的镜像,其中是 Win10 + VS2019 + 上述的 EDK2 代码,如果你是初学者或者在配置 EDK2 过程中碰到奇怪的问题,不妨先使用这个版本:

链接: https://pan.baidu.com/s/1CK1F06xhE11VW8P7XNosSg?pwd=labz 提取码: labz

Teensy 3.6 触摸屏功能

Teensy 3.6 支持触摸屏,10指触摸,具体的库在\hardware\teensy\avr\cores\teensy3\usb_touch.c 文件中,下面是一个示例代码,使用了2个手指绘制直线:

#include <Bounce.h>

int yoffset = 4000;

void setup() {
  pinMode(A1, INPUT_PULLUP);
  TouchscreenUSB.begin();
}

void drawline(int x, int y) {
 for (int i=0; i < 6000; i += 100) {
   TouchscreenUSB.press(0, x + i, y + i/13);
   TouchscreenUSB.press(1, x + i+400, y + i/13+400);
   delay(10);
 }
 TouchscreenUSB.release(0);
 TouchscreenUSB.release(1); 
}

void loop() {
  if (digitalRead(A1)==LOW) {
    Serial.println("press");
    drawline(16000, yoffset);
    yoffset += 1200;
    if (yoffset > 24000) yoffset = 4000;
  }
}

特别的,需要在菜单中打开 Touch Screen

另外,如果你使用Windows 10 下面的画板进行测试,需要选中 Brushes,只有这个才支持多点触摸绘图:

Step to UEFI (265)QEMU ACPI Table 的来源

之前介绍过在 Shell 下面查看 ACPI Table 的工具,例如【参考1】提到的:ACPIView。

接下来的问题就是:上面的这个 DSDT 是从哪里来的?

首先,在代码中找了一圈,竟然一无所获;接下来在Debug Log中查找,发现如下信息,其中的一个 Table 长度是 0x1772(6002)非常接近我们在 Shell 下看到的 6009。

ProcessCmdAllocate: File="etc/acpi/tables" Alignment=0x40 Zone=1 Size=0x20000 Address=0x7BDE000
ProcessCmdAddChecksum: File="etc/acpi/tables" ResultOffset=0x49 Start=0x40 Length=0x1772
ProcessCmdAddPointer: PointerFile="etc/acpi/tables" PointeeFile="etc/acpi/tables" PointerOffset=0x17D6 PointerSize=4
ProcessCmdAddPointer: PointerFile="etc/acpi/tables" PointeeFile="etc/acpi/tables" PointerOffset=0x17DA PointerSize=4
ProcessCmdAddChecksum: File="etc/acpi/tables" ResultOffset=0x17BB Start=0x17B2 Length=0x74
ProcessCmdAddChecksum: File="etc/acpi/tables" ResultOffset=0x182F Start=0x1826 Length=0x78
……………….
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDE000 (remaining: 0x20000): found "FACS" size 0x40
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDE040 (remaining: 0x1FFC0): found "DSDT" size 0x1772
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF7B2 (remaining: 0x1E84E): found "FACP" size 0x74
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF826 (remaining: 0x1E7DA): found "APIC" size 0x78
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF89E (remaining: 0x1E762): found "HPET" size 0x38
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF8D6 (remaining: 0x1E72A): found "WAET" size 0x28

这一段 Log 对应的代码在\OvmfPkg\AcpiPlatformDxe\QemuFwCfgAcpi.c 中。

为了验证猜想,在对应代码中加入调试信息,输出读取到QEMU 的 ACPI DSDT,具体在OvmfPkg\AcpiPlatformDxe\QemuFwCfgAcpi.c,修改如下:

Blob2Remaining -= (UINTN) PointerValue;
DEBUG ((DEBUG_INFO, "%a: checking for ACPI header in \"%a\" at 0x%Lx "
  "(remaining: 0x%Lx): ", __FUNCTION__, AddPointer->PointeeFile,
  PointerValue, (UINT64)Blob2Remaining));
 
TableSize = 0;
 
//
// To make our job simple, the FACS has a custom header. Sigh.
//
if (sizeof *Facs &lt;= Blob2Remaining) {
  Facs = (EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE *)(UINTN)PointerValue;
    //LABZDebug_Start
    if ((Facs->Signature==EFI_ACPI_1_0_DIFFERENTIATED_SYSTEM_DESCRIPTION_TABLE_SIGNATURE)) {
                DEBUG ((DEBUG_INFO,"DSDt found\n"));
                p = (CHAR8*)(Facs);
                //p=p+sizeof(EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE);
                for (i=0;i&lt;32;i++) {
                      DEBUG ((DEBUG_INFO,"%x ",p[i]&amp;0xFF));
                }
        }
    // LABZDebug_End
  if (Facs->Length >= sizeof *Facs &amp;&amp;
      Facs->Length &lt;= Blob2Remaining &amp;&amp;
      Facs->Signature ==
              EFI_ACPI_1_0_FIRMWARE_ACPI_CONTROL_STRUCTURE_SIGNATURE) {
    DEBUG ((DEBUG_INFO, "found \"%-4.4a\" size 0x%x\n",
      (CONST CHAR8 *)&amp;Facs->Signature, Facs->Length));
    TableSize = Facs->Length;
 
  }
}

输出结果如下:

Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDE000 (remaining: 0x20000): found "FACS" size 0x40
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDE040 (remaining: 0x1FFC0): DSDt found
44 53 44 54 72 17 0 0 1 9E 42 4F 43 48 53 20 42 58 50 43 20 20 20 20 1 0 0 0 42 58 50 43
Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF7B2 (remaining: 0x1E84E): Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF826 (remaining: 0x1E7DA): Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF89E (remaining: 0x1E762): Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF8D6 (remaining: 0x1E72A): Process2ndPassCmdAddPointer: checking for ACPI header in "etc/acpi/tables" at 0x7BDF8FE (remaining: 0x1E702): InstallQemuFwCfgTables: installed 6 tables
PcRtc: Write 0x20 to CMOS location 0x32

可以看到这个结果和ACPIViewApp Dump 出来的 DSDT 结果是相同的:

这说明QEMU 中的 ACPI Table 来自 QemuFwCfgAcpi.c 取得的 ACPI Table。

参考:

1. https://www.lab-z.com/acpiview/

内存的奇怪问题

最近遇到了一个奇怪的问题,经过化简得代码表示如下:

#include "stdafx.h"
#include <malloc.h>

void foo2() {
	int *Handle;
	Handle = (int *)alloca(100);
	memset(Handle, 0x11, 100);
	return;
}
void foo1(int **Handle){
	*Handle = (int *)alloca(100);
	memset(*Handle,0xAA,100);
	return;
}

int main()
{
	int *Value=NULL;
	foo1(&Value);
	foo2();
	getchar();
    return 0;
}

简单的说,在 foo1() 中分配100bytes的内存空间,0然后在foo2() 中在分配100Bytes,但是实践发现,前面分配的内存空间被“冲掉”了。更具体的说:

1.运行 foo1(), 之后查看到 value 的内存地址已经赋值为 0xaa

2.接下来执行 foo2(),但是运行之后,Value 对应的内存空间被覆盖为0x11。

有兴趣的朋友可以自己先琢磨五分钟看看能否找到问题。

最终,这个问题是分配内存的 alloca()导致的:alloca分配的是栈区(stack)内存,程序自动释放;(注意,栈空间有限仅几kb左右,堆空间远大于栈空间)。当 foo1 执行完成,这个区域已经被释放;当执行 foo2 的时候,程序会再次使用这个内存【参考1】。

解决方法:改成 malloc,它是在堆上进行分配内存的。

参考:

  1. https://zhuanlan.zhihu.com/p/449165315
  2. https://cloud.tencent.com/developer/article/1729074

Step to UEFI (264)代码读取一个 FFS

最近有一个读取 FFS 的需求,具体来说就是在 DXE 阶段需要读取指定的 FFS 文件的内容。针对这个需求,使用QEMU 进行了一番研究。

OVMF 中继承了 Shell,读取这个的动作和我们需求非常类似,于是在 QEMU 的Log中搜索可以看到如下字样:

[Bds]Booting EFI Internal Shell
[Bds] Expand Fv(7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1)/FvFile(7C04A583-9E3E-4F1C-AD65-E05268D0B4D1) -> Fv(7CB8BDC9-F8EB-4F34-AAEA-3EE4AF6516A1)/FvFile(7C04A583-9E3E-4F1C-AD65-E05268D0B4D1)
InstallProtocolInterface: 5B1B31A1-9562-11D2-8E3F-00A0C969723B 6C14040
Loading driver at 0x000068AE000 EntryPoint=0x000068AE4E8 Shell.efi
InstallProtocolInterface: BC62157E-3E33-4FEC-9920-2D3B36D750DF 70F9418

对应在代码中位于\mdemodulepkg\library\uefibootmanagerlib\BmLoadOption.c

DEBUG ((DEBUG_INFO, "[Bds] Expand "));
BmPrintDp (FilePath);
DEBUG ((DEBUG_INFO, " -> "));
BmPrintDp (CurFullPath);
DEBUG ((DEBUG_INFO, "\n"));

经过追踪可以看到具体工作的是位于 \mdepkg\library\dxeserviceslib\DxeServicesLib.c的如下函数:

/**
  Get the image file buffer data and buffer size by its device path.
 
  Access the file either from a firmware volume, from a file system interface,
  or from the load file interface.
 
  Allocate memory to store the found image. The caller is responsible to free memory.
 
  If FilePath is NULL, then NULL is returned.
  If FileSize is NULL, then NULL is returned.
  If AuthenticationStatus is NULL, then NULL is returned.
 
  @param[in]       BootPolicy           Policy for Open Image File.If TRUE, indicates
                                        that the request originates from the boot
                                        manager, and that the boot manager is
                                        attempting to load FilePath as a boot
                                        selection. If FALSE, then FilePath must
                                        match an exact file to be loaded.
  @param[in]       FilePath             The pointer to the device path of the file
                                        that is abstracted to the file buffer.
  @param[out]      FileSize             The pointer to the size of the abstracted
                                        file buffer.
  @param[out]      AuthenticationStatus Pointer to the authentication status.
 
  @retval NULL   FilePath is NULL, or FileSize is NULL, or AuthenticationStatus is NULL, or the file can't be found.
  @retval other  The abstracted file buffer. The caller is responsible to free memory.
**/
VOID *
EFIAPI
GetFileBufferByFilePath (
  IN BOOLEAN                           BootPolicy,
  IN CONST EFI_DEVICE_PATH_PROTOCOL    *FilePath,
  OUT      UINTN                       *FileSize,
  OUT UINT32                           *AuthenticationStatus
  )

进一步研究,上述函数通过 EFI_FIRMWARE_VOLUME2_PROTOCOL 来完成读取。这个 Protocol 在 PI Spec (并不是 UEFI Spec)中有描述:

进一步追踪,可以看到是通过FwVol->ReadSection() 将Shell读取出来的:

SectionType = EFI_SECTION_PE32;
ImageBuffer = NULL;
Status = FwVol->ReadSection (
                  FwVol,
                  FvNameGuid,
                  SectionType,
                  0,
                  (VOID **)&amp;ImageBuffer,
                  &amp;ImageBufferSize,
                  AuthenticationStatus
                  );

ReadSection() 原型定义如下:

/**
  Locates the requested section within a file and returns it in a buffer.
 
  ReadSection() is used to retrieve a specific section from a file
  within a firmware volume. The section returned is determined
  using a depth-first, left-to-right search algorithm through all
  sections found in the specified file. The output buffer is specified by a double indirection
  of the Buffer parameter. The input value of Buffer is used to
  determine if the output buffer is caller allocated or is
  dynamically allocated by ReadSection(). If the input value of
  Buffer!=NULL, it indicates that the output buffer is caller
  allocated. In this case, the input value of *BufferSize
  indicates the size of the caller-allocated output buffer. If
  the output buffer is not large enough to contain the entire
  requested output, it is filled up to the point that the output
  buffer is exhausted and EFI_WARN_BUFFER_TOO_SMALL is returned,
  and then BufferSize is returned with the size that is required
  to successfully complete the read. All other
  output parameters are returned with valid values. If the input
  value of *Buffer==NULL, it indicates the output buffer is to
  be allocated by ReadSection(). In this case, ReadSection()
  will allocate an appropriately sized buffer from boot services
  pool memory, which will be returned in *Buffer. The size of
  the new buffer is returned in *BufferSize and all other output
  parameters are returned with valid values. ReadSection() is
  callable only from TPL_NOTIFY and below. Behavior of
  ReadSection() at any EFI_TPL above TPL_NOTIFY is
  undefined.
 
  @param  This                Indicates the EFI_FIRMWARE_VOLUME2_PROTOCOL instance.
 
  @param NameGuid             Pointer to an EFI_GUID, which indicates the
                              file name from which the requested section
                              will be read.
 
  @param SectionType          Indicates the section type to return.
                              SectionType in conjunction with
                              SectionInstance indicates which section to
                              return.
 
  @param SectionInstance      Indicates which instance of sections
                              with a type of SectionType to return.
                              SectionType in conjunction with
                              SectionInstance indicates which
                              section to return. SectionInstance is
                              zero based.
 
  @param Buffer               Pointer to a pointer to a buffer in which the
                              section contents are returned, not including
                              the section header.
 
  @param BufferSize           Pointer to a caller-allocated UINTN. It
                              indicates the size of the memory
                              represented by Buffer.
 
  @param AuthenticationStatus Pointer to a caller-allocated
                              UINT32 in which the authentication
                              status is returned.
 
 
  @retval EFI_SUCCESS   The call completed successfully.
 
  @retval EFI_WARN_BUFFER_TOO_SMALL   The caller-allocated
                                      buffer is too small to
                                      contain the requested
                                      output. The buffer is
                                      filled and the output is
                                      truncated.
 
  @retval EFI_OUT_OF_RESOURCES  An allocation failure occurred.
 
  @retval EFI_NOT_FOUND   The requested file was not found in
                          the firmware volume. EFI_NOT_FOUND The
                          requested section was not found in the
                          specified file.
 
  @retval EFI_DEVICE_ERROR  A hardware error occurred when
                            attempting to access the firmware
                            volume.
 
  @retval EFI_ACCESS_DENIED The firmware volume is configured to
                            disallow reads. EFI_PROTOCOL_ERROR
                            The requested section was not found,
                            but the file could not be fully
                            parsed because a required
                            GUIDED_SECTION_EXTRACTION_PROTOCOL
                            was not found. It is possible the
                            requested section exists within the
                            file and could be successfully
                            extracted once the required
                            GUIDED_SECTION_EXTRACTION_PROTOCOL
                            is published.
 
**/
typedef
EFI_STATUS
(EFIAPI * EFI_FV_READ_SECTION)(
  IN CONST  EFI_FIRMWARE_VOLUME2_PROTOCOL *This,
  IN CONST  EFI_GUID                      *NameGuid,
  IN        EFI_SECTION_TYPE              SectionType,
  IN        UINTN                         SectionInstance,
  IN OUT    VOID                          **Buffer,
  IN OUT    UINTN                         *BufferSize,
  OUT       UINT32                        *AuthenticationStatus
);

在 OVMF 中实际动作是 \mdemodulepkg\core\dxe\fwvol\FwVolRead.c 中的FvReadFileSection()函数完成的(通过输出 Log 的方法可以确认):

/**
  Locates a section in a given FFS File and
  copies it to the supplied buffer (not including section header).
 
  @param  This                       Indicates the calling context.
  @param  NameGuid                   Pointer to an EFI_GUID, which is the
                                     filename.
  @param  SectionType                Indicates the section type to return.
  @param  SectionInstance            Indicates which instance of sections with a
                                     type of SectionType to return.
  @param  Buffer                     Buffer is a pointer to pointer to a buffer
                                     in which the file or section contents or are
                                     returned.
  @param  BufferSize                 BufferSize is a pointer to caller allocated
                                     UINTN.
  @param  AuthenticationStatus       AuthenticationStatus is a pointer to a
                                     caller allocated UINT32 in which the
                                     authentication status is returned.
 
  @retval EFI_SUCCESS                Successfully read the file section into
                                     buffer.
  @retval EFI_WARN_BUFFER_TOO_SMALL  Buffer too small.
  @retval EFI_NOT_FOUND              Section not found.
  @retval EFI_DEVICE_ERROR           Device error.
  @retval EFI_ACCESS_DENIED          Could not read.
  @retval EFI_INVALID_PARAMETER      Invalid parameter.
 
**/
EFI_STATUS
EFIAPI
FvReadFileSection (
  IN CONST  EFI_FIRMWARE_VOLUME2_PROTOCOL  *This,
  IN CONST  EFI_GUID                       *NameGuid,
  IN        EFI_SECTION_TYPE               SectionType,
  IN        UINTN                          SectionInstance,
  IN OUT    VOID                           **Buffer,
  IN OUT    UINTN                          *BufferSize,
  OUT       UI

运行结果如下:

oading driver at 0x00007AC4000 EntryPoint=0x00007AC4494 PcRtc.efi
InstallProtocolInterface: BC62157E-3E33-4FEC-9920-2D3B36D750DF 7097A98
ProtectUefiImageCommon - 0x7097740
  - 0x0000000007AC4000 - 0x0000000000005300
  Image - c:\buildbs\stable202108\Build\OvmfX64\DEBUG_VS2015x86\X64\PcAtChipsetPkg\PcatRealTimeClockRuntimeDxe\PcatRealTimeClockRuntimeDxe\DEBUG\PcRtc.pdb
!!!!!!!!  ProtectUefiImageCommon - Section Alignment(0x20) is incorrect  !!!!!!!!
!!!!!!!!  Image - c:\buildbs\stable202108\Build\OvmfX64\DEBUG_VS2015x86\X64\PcAtChipsetPkg\PcatRealTimeClockRuntimeDxe\PcatRealTimeClockRuntimeDxe\DEBUG\PcRtc.pdb  !!!!!!!!
[EFI_FIRMWARE_VOLUME2_PROTOCOL Success 944416]
4D 5A 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
A5 A0 A5 C0 A5 D8 A5 F0 A5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 
InstallProtocolInterface: 27CFAC87-46CC-11D4-9A38-0090273FC14D 0

使用工具可以看到 Shell.efi 的大小是 94416Bytes,读取到Buffer 中的内容也是 Shell 的内容。

总结:BIOS 工程师可以通过 EFI_FIRMWARE_VOLUME2_PROTOCOL 来获取指定 FFS 的内容。

一个让你轻松配置ESP32 WIFI的库

ESP32 带有 WIFI 功能,而众所周知要想让一个设备连接WIFI AP 需要告知设备对应 AP 的名称和密码,简单实验的话,可以直接在代码中写死这两个参数,但这种情况下烧写之后设备只能在固定的环境下使用。https://github.com/tzapu/wifimanager 这个项目可以解决上述问题。先说一下这个东西如何使用:

  1. 编译下载Arduino\libraries\WiFiManager-master\examples\OnDemand下面的代码
  2. 上电运行之后短接 Pin0
  3. 用手机查找OnDemandAP 这个 AP
  4. 连接之后自动打开下面的界面

5.选择 Configure WIFI 会显示当前能搜索到的WIFI AP名称,选择你要的

6.输入对应的密码设备即可连接

我在 DFRobot的 FireBeetle 上实验(需要注意他自带的WIFI库太老,运行期AP 无法启动,需要用ESP32 Arduino库中的 FireBeetle),工作正常。

Step to UEFI (263)实验:直接修改QEMU的启动顺序

当我们使用如下 Command 启动 QEMU 的时候,能够将 d:\tmp 目录映射为 fs0:

.\qemu-system-x86_64.exe -bios ovmf.fd  -hda fat:rw:d:\tmp\

之后,可以在这个目录中看到一个名为 NvVars 的文件。这次实验的目标是直接修改 NvVars 文件来实现调整启动顺序。例如:启动之后在 Setup 中可以看到如下4个启动设备:

1.进入Shell 后使读取变量的命令,将变量保存在 Result.txt 文件中:

Dmpstore >> result.txt

2.在 Debug Log 中可以看到如下字样,就是说 OVMF 在启动过程中会读取NvVars这个文件作为变量:

InstallProtocolInterface: 964E5B22-6459-11D2-8E39-00A0C969723B 6B6F030
Installed Fat filesystem on 6C14698
FsAccess.c: LoadNvVarsFromFs
FSOpen: Open 'NvVars' Success
FsAccess.c: Read 10590 bytes from NV Variables file

3.进一步分析,读取动作来自 ovmfpkg\library\nvvarsfilelib\FsAccess.c 文件中的LoadNvVarsFromFs() 函数

/**
  Loads the non-volatile variables from the NvVars file on the
  given file system.
 
  @param[in]  FsHandle - Handle for a gEfiSimpleFileSystemProtocolGuid instance
 
  @return     EFI_STATUS based on the success or failure of load operation
 
**/
EFI_STATUS
LoadNvVarsFromFs (
  EFI_HANDLE                            FsHandle
  )

4.具体读取动作在ReadNvVarsFile() 函数中:

/**
  Reads the contents of the NvVars file on the file system
 
  @param[in]  FsHandle - Handle for a gEfiSimpleFileSystemProtocolGuid instance
 
  @return     EFI_STATUS based on the success or failure of the file read
 
**/
EFI_STATUS
ReadNvVarsFile (
  IN  EFI_HANDLE            FsHandle
  )

读取内容

FileContents = FileHandleReadToNewBuffer (File, FileSize);
if (FileContents == NULL) {
  FileHandleClose (File);
  return EFI_UNSUPPORTED;
}

5.读取之后使用 IterateVariablesInBuffer() 函数进行解析

/**
  Iterates through the variables in the buffer, and calls a callback
  function for each variable found.
 
  @param[in]  CallbackFunction - Function called for each variable instance
  @param[in]  Context - Passed to each call of CallbackFunction
  @param[in]  Buffer - Buffer containing serialized variables
  @param[in]  MaxSize - Size of Buffer in bytes
 
  @return     EFI_STATUS based on the success or failure of the operation
 
**/
STATIC
EFI_STATUS
IterateVariablesInBuffer (
  IN VARIABLE_SERIALIZATION_ITERATION_CALLBACK  CallbackFunction,
  IN VOID                                       *CallbackContext,
  IN VOID                                       *Buffer,
  IN UINTN                                      MaxSize
  )

上面是一些基本的研究,下面尝试直接修改。在Dump 的变量文件Result.txt 中,可以看到 BootOrder 变量:

00000080: 00 00 00 00 00 00 00 00-00 00 00 00 00 00 00 00  *................*
  00000090: 00 00 00 00 7F FF 04 00-4E AC 08 81 11 9F 59 4D  *........N.....YM*
  000000A0: 85 0E E2 1A 52 2C 59 B2-                         *....R,Y.*
Variable NV+RT+BS 'EFIGlobalVariable:BootOrder' DataSize = 0x0A
  00000000: 00 00 01 00 02 00 03 00-04 00                    *..........*
Variable NV+RT+BS 'EFIGlobalVariable:Key0002' DataSize = 0x0E
  00000000: 00 00 00 40 3C 4A 2D 14-05 00 11 00 00 00        *...@&lt;J-.......*

对应在 NvVars 文件中位于下面几行:

这里,将 00 00 01 00 02 00 03 00-04 00 修改为 00 00 04 00 02 00 03 00-01 00,下次再启动 QEMU 会会先启动到网卡上了。