#!/bin/bash

# QRingBuffer整数溢出测试脚本
# 用于验证QtBase项目中QRingBuffer::free函数的整数溢出bug

set -e  # 遇到错误时退出

echo "=========================================="
echo "QRingBuffer Integer Overflow Test Script"
echo "=========================================="

# 检查是否在QtBase项目目录中
if [ ! -f "CMakeLists.txt" ] || [ ! -d "src/corelib/tools" ]; then
    echo "错误：请在QtBase项目根目录中运行此脚本"
    exit 1
fi

# 创建测试目录
TEST_DIR="qringbuffer_test"
mkdir -p $TEST_DIR
cd $TEST_DIR

echo "创建测试目录: $TEST_DIR"

# 复制测试文件
cp ../test_qringbuffer_overflow.cpp .
cp ../CMakeLists_test.txt CMakeLists.txt

echo "复制测试文件完成"

# 创建构建目录
BUILD_DIR="build"
mkdir -p $BUILD_DIR
cd $BUILD_DIR

echo "开始构建测试程序..."

# 配置CMake
cmake .. \
    -DCMAKE_PREFIX_PATH=/usr/lib/x86_64-linux-gnu/cmake/Qt6 \
    -DCMAKE_BUILD_TYPE=Debug \
    -DQT_QMAKE_EXECUTABLE=qmake6

# 编译
make -j$(nproc)

echo "构建完成！"

# 运行测试
echo ""
echo "=========================================="
echo "开始运行测试..."
echo "=========================================="

# 运行基本测试
./test_qringbuffer_overflow

echo ""
echo "=========================================="
echo "测试完成！"
echo "=========================================="

# 检查是否有错误输出
if [ $? -eq 0 ]; then
    echo "✅ 测试程序运行成功"
else
    echo "❌ 测试程序运行失败"
    exit 1
fi

echo ""
echo "测试结果分析："
echo "- 如果看到 'INTEGER UNDERFLOW DETECTED!' 消息，说明发现了整数溢出bug"
echo "- 如果程序崩溃，说明bug可能导致程序不稳定"
echo "- 如果bufferSize变为负数，确认了整数下溢问题"

cd ../..

echo ""
echo "测试文件位置："
echo "- 测试程序: $TEST_DIR/$BUILD_DIR/test_qringbuffer_overflow"
echo "- 源代码: $TEST_DIR/test_qringbuffer_overflow.cpp"
echo "- 构建文件: $TEST_DIR/$BUILD_DIR/"

echo ""
echo "要重新运行测试，请执行："
echo "cd $TEST_DIR/$BUILD_DIR && ./test_qringbuffer_overflow" 