记录一个`ffmpeg`的`swscale`库crash的例子

记录一个ffmpegswscale库crash的例子

本质上, 就是simd越界导致, 具体场景如下:

外部api分配了rgb24内存指针ptr, 然后转换为yuv420p, 如果ptrend不可访问, 则会crash

1. simd越界例子

cpp 复制代码
#include <cstdint>
#include <immintrin.h>
#include <iostream>
#include <memory>

#ifdef _WIN32
#include <windows.h>
#elif __linux__
#include <sys/mman.h>
#include <unistd.h>
#endif

#ifdef _WIN32
void win_crash() {
  constexpr size_t N = 1024;
  constexpr size_t PAGE = 4096;
  std::shared_ptr<uint8_t> base(
      static_cast<uint8_t *>(VirtualAlloc(
          nullptr, PAGE * 2, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)),
      [](uint8_t *p) { VirtualFree(p, 0, MEM_RELEASE); });
  DWORD old;
  VirtualProtect(base.get() + PAGE, PAGE, PAGE_NOACCESS, &old);
  uint8_t *data = base.get() + PAGE - N;
  for (size_t i = 0; i < N; ++i)
    data[i] = static_cast<uint8_t>(i);

  for (size_t i = 0; i < N; i += 8) {
    __m256i v =
        _mm256_loadu_si256(reinterpret_cast<const __m256i *>(data + 32 + i));
    uint8_t tmp = static_cast<uint8_t>(_mm256_extract_epi8(v, 0));
    std::cout << static_cast<int64_t>(tmp) << "\n";
  }
}
#endif

#ifdef __linux__
// target_compile_options(my_target_name PRIVATE -mavx2)
void linux_crash() {
  constexpr size_t N = 1024;
  constexpr size_t PAGE = 4096;
  void *p = mmap(nullptr, PAGE * 2, PROT_READ | PROT_WRITE,
                 MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
  if (p == MAP_FAILED) {
    perror("mmap");
    return;
  }
  std::shared_ptr<uint8_t> base(static_cast<uint8_t *>(p),
                                [](uint8_t *p) { munmap(p, PAGE * 2); });
  if (mprotect(base.get() + PAGE, PAGE, PROT_NONE) != 0) {
    perror("mprotect");
    return;
  }
  uint8_t *data = base.get() + PAGE - N;
  for (size_t i = 0; i < N; ++i)
    data[i] = static_cast<uint8_t>(i);
  for (size_t i = 0; i < N; i += 8) {
    __m256i v = _mm256_loadu_si256(reinterpret_cast<const __m256i *>(data + i));
    uint8_t tmp = static_cast<uint8_t>(_mm256_extract_epi8(v, 0));
    std::cout << static_cast<int64_t>(tmp) << "\n";
  }
}
#endif

int main() {
  win_crash();
  // linux_crash();
  return 0;
}

ffmpeg堆栈错误信息

最终崩溃在函数指针lumToYV12中, 具体汇编代码见libswscale/x86/swscale.clibswscale/input.asm

reference

相关推荐
兵叔物联17 小时前
基于FFmpeg的短视频自动剪辑工具
ffmpeg·音视频
霸道流氓气质3 天前
视频预览链路三件套:ZLMediaKit · MediaMTX · FFmpeg 完全指南
ffmpeg·音视频
xgc_java3 天前
在Java里把ONNX/OpenCV/FFmpeg跑稳:28篇bytedeco实战小册完整指南
java·opencv·ffmpeg
鲲穹AI全能助理9 天前
实用音频合成工具分享:灵境配音 使用场景与功能说明
ffmpeg·音视频
我是Superman丶9 天前
Windows系统FFmpeg官方下载+完整安装配置保姆级教程(2026最新版)
windows·ffmpeg
luoyayun36110 天前
Qt + FFmpeg 视频工具:视频一键压缩功能实现
qt·ffmpeg·音视频·视频压缩
雪的季节10 天前
ffmpeg源码国内gitee下载
ffmpeg·gitee
Mister Leon13 天前
FFmpeg - Jetson Orin 实战部署
ffmpeg
阿拉斯攀登14 天前
售货柜实战:IPC 拉流 → 抽帧 → YOLO 识别完整流水线
yolo·ffmpeg·音视频·webrtc·视频编解码
阿拉斯攀登14 天前
RTSP 拉流与录制:IPC 摄像头本地录像完整方案
ffmpeg·音视频·webrtc·实时音视频·视频编解码