Repository: game1024/OpenSpeedy Branch: master Commit: 74ada0fc7c25 Files: 82 Total size: 570.2 KB Directory structure: gitextract_jddv06rn/ ├── .github/ │ ├── FUNDING.yml │ ├── ISSUE_TEMPLATE/ │ │ ├── bug.yml │ │ ├── config.yml │ │ └── feature.yml │ └── workflows/ │ ├── ci.yml │ └── package.yml ├── .gitignore ├── .gitmodules ├── CMakeLists.txt ├── CMakePresets.json ├── CMakeUserPresets.json ├── LICENSE ├── OpenSpeedy_en_US.ts ├── OpenSpeedy_zh_CN.ts ├── OpenSpeedy_zh_TW.ts ├── README.md ├── aboutdialog.cpp ├── aboutdialog.h ├── aboutdialog.ui ├── bridge/ │ ├── CMakeLists.txt │ └── main.cpp ├── config.h ├── cpuutils.cpp ├── cpuutils.h ├── docs/ │ ├── README_cn.md │ └── README_ja.md ├── installer/ │ ├── OpenSpeedy.wxs │ ├── config/ │ │ └── config.xml │ └── create_installer.bat ├── main.cpp ├── mainwindow.cpp ├── mainwindow.h ├── mainwindow.ui ├── memutils.cpp ├── memutils.h ├── preferencedialog.cpp ├── preferencedialog.h ├── preferencedialog.ui ├── processmonitor.cpp ├── processmonitor.h ├── qsinglekeysequenceedit.cpp ├── qsinglekeysequenceedit.h ├── resources.qrc ├── script/ │ ├── build32.bat │ ├── build64.bat │ └── initenv.bat ├── speedpatch/ │ ├── CMakeLists.txt │ ├── SpeedPatch_global.h │ ├── speedpatch.cpp │ ├── speedpatch.h │ └── vcpkg.json ├── taskscheduler.cpp ├── taskscheduler.h ├── themeutils.cpp ├── themeutils.h ├── third_party/ │ └── minhook/ │ ├── .editorconfig │ ├── .github/ │ │ └── workflows/ │ │ └── msbuild.yml │ ├── .gitignore │ ├── AUTHORS.txt │ ├── CMakeLists.txt │ ├── LICENSE.txt │ ├── README.md │ ├── build/ │ │ └── MinGW/ │ │ ├── make.bat │ │ └── make.sh │ ├── cmake/ │ │ └── minhook-config.cmake.in │ ├── dll_resources/ │ │ └── MinHook.def │ ├── include/ │ │ └── MinHook.h │ └── src/ │ ├── buffer.c │ ├── buffer.h │ ├── hde/ │ │ ├── hde32.c │ │ ├── hde32.h │ │ ├── hde64.c │ │ ├── hde64.h │ │ ├── pstdint.h │ │ ├── table32.h │ │ └── table64.h │ ├── hook.c │ ├── trampoline.c │ └── trampoline.h ├── windbg.h ├── winutils.cpp └── winutils.h ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/FUNDING.yml ================================================ # These are supported funding model platforms github: [game1024] patreon: ================================================ FILE: .github/ISSUE_TEMPLATE/bug.yml ================================================ name: Bug Report / 错误报告 description: 报告软件中的错误或问题 / Report a bug or issue title: "[Bug]: " labels: ["bug"] body: - type: markdown attributes: value: | ## 重要提示 / Important Notice ⚠️ **本项目仅支持离线使用场景,对于在线类软件(如网络游戏、在线服务、网盘等)的问题不提供支持。** --- 感谢您反馈问题!请填写以下信息以帮助我们更好地定位和解决问题。 - type: input id: software-version attributes: label: 软件版本 / Software Version description: 您使用的 OpenSpeedy 版本是什么? placeholder: 例如:v1.0.0 或 commit hash validations: required: true - type: dropdown id: os-version attributes: label: 操作系统 / Operating System description: 您使用的操作系统版本 options: - Windows 11 (23H2) - Windows 11 (22H2) - Windows 11 (21H2) - Windows 10 (22H2) - Windows 10 (21H2) - Windows 10 (20H2) - Windows 10 (其他版本 / Other) - Windows 8.1 - Windows 8 - Windows 7 - 其他 / Other validations: required: true - type: input id: os-build attributes: label: 系统版本号 / OS Build Number description: 可以在"设置 > 系统 > 关于"中找到 / Can be found in "Settings > System > About" placeholder: 例如:22621.1234 - type: textarea id: description attributes: label: 问题描述 / Bug Description description: 请详细描述您遇到的问题 placeholder: 描述问题的具体表现... validations: required: true - type: textarea id: reproduction attributes: label: 复现步骤 / Steps to Reproduce description: 如何复现这个问题? placeholder: | 1. 打开软件... 2. 点击... 3. 看到错误... validations: required: true - type: textarea id: expected attributes: label: 期望行为 / Expected Behavior description: 您期望发生什么? placeholder: 描述期望的正确行为... validations: required: true - type: textarea id: actual attributes: label: 实际行为 / Actual Behavior description: 实际发生了什么? placeholder: 描述实际发生的情况... validations: required: true - type: textarea id: target-software attributes: label: 目标软件信息 / Target Software Information description: 您正在使用 OpenSpeedy 优化哪个软件?请提供软件名称和版本 placeholder: | 软件名称: 软件版本: 软件类型:离线软件 / 单机软件 - type: textarea id: logs attributes: label: 日志或错误信息 / Logs or Error Messages description: 如有相关日志或错误信息,请粘贴在此 render: shell - type: textarea id: screenshots attributes: label: 截图 / Screenshots description: 如果适用,请添加截图来帮助解释您的问题 - type: textarea id: additional attributes: label: 其他信息 / Additional Context description: 其他可能有助于解决问题的信息 - type: checkboxes id: terms attributes: label: 确认事项 / Confirmation description: 请确认以下事项 options: - label: 我确认这是一个离线软件的问题,不涉及在线服务 / I confirm this is about offline software, not online services required: true - label: 我已经搜索过现有的 issues,没有找到类似问题 / I have searched existing issues and found no duplicates required: true - label: 我使用的是最新版本的软件 / I am using the latest version of the software required: false ================================================ FILE: .github/ISSUE_TEMPLATE/config.yml ================================================ blank_issues_enabled: false contact_links: - name: 💬 讨论区 / Discussions url: https://github.com/game1024/Speedy/discussions about: 如有疑问或需要帮助,请访问讨论区 / For questions or help, please visit Discussions - name: 📖 文档 / Documentation url: https://github.com/game1024/Speedy/blob/master/README.md about: 查看项目文档和使用说明 / View project documentation and usage guide - name: ⚠️ 重要提示 / Important Notice url: https://github.com/game1024/Speedy/blob/master/README.md about: 本项目仅支持离线软件,不支持在线服务类软件 / This project only supports offline software, not online services ================================================ FILE: .github/ISSUE_TEMPLATE/feature.yml ================================================ name: Feature Request / 功能请求 description: 建议新功能或改进 / Suggest a new feature or improvement title: "[Feature]: " labels: ["enhancement"] body: - type: markdown attributes: value: | ## 重要提示 / Important Notice ⚠️ **本项目仅支持离线使用场景,对于在线类软件(如网络游戏、在线服务、网盘等)的功能请求不提供支持。** --- 感谢您的建议!请详细描述您希望添加的功能。 - type: textarea id: problem attributes: label: 问题描述 / Problem Description description: 这个功能要解决什么问题? placeholder: 我在使用中遇到了...的问题 validations: required: true - type: textarea id: solution attributes: label: 建议的解决方案 / Proposed Solution description: 您希望如何实现这个功能? placeholder: 我建议添加一个...功能,可以... validations: required: true - type: textarea id: alternatives attributes: label: 替代方案 / Alternatives Considered description: 您是否考虑过其他解决方案? placeholder: 我也考虑过...,但是... - type: textarea id: use-case attributes: label: 使用场景 / Use Case description: 这个功能在什么场景下会被使用? placeholder: 当我...的时候,我需要... validations: required: true - type: textarea id: additional attributes: label: 其他信息 / Additional Context description: 其他可能有助于理解该功能请求的信息 placeholder: 相关链接、参考资料等 - type: checkboxes id: terms attributes: label: 确认事项 / Confirmation description: 请确认以下事项 options: - label: 这个功能适用于离线软件场景 / This feature is for offline software scenarios required: true - label: 我已经搜索过现有的 issues,没有找到类似的功能请求 / I have searched existing issues and found no similar requests required: true ================================================ FILE: .github/workflows/ci.yml ================================================ name: Build OpenSpeedy on: pull_request: branches: [ master ] workflow_dispatch: jobs: build: runs-on: self-hosted outputs: artifact-id: ${{ steps.upload-unsigned-artifacts.outputs.artifact-id }} steps: - name: Checkout uses: actions/checkout@v4 - name: Build 32-bit shell: cmd run: | echo Building 32-bit... call script\initenv.bat call script\build32.bat - name: Build 64-bit shell: cmd run: | echo Building 64-bit... call script\initenv.bat call script\build64.bat - name: Collect artifacts to flat directory shell: cmd run: | echo Collecting artifacts... if not exist "artifacts" mkdir "artifacts" copy "build\CMAKE_x64_static-Release\OpenSpeedy.exe" "artifacts\" copy "build\CMAKE_x64_static-Release\speedpatch64.dll" "artifacts\" copy "build\CMAKE_x64_static-Release\bridge64.exe" "artifacts\" copy "build\CMAKE_x86_static-Release\speedpatch32.dll" "artifacts\" copy "build\CMAKE_x86_static-Release\bridge32.exe" "artifacts\" echo Artifacts directory contents: dir "artifacts" - name: Upload unsigned artifacts id: upload-unsigned-artifacts uses: actions/upload-artifact@v4 if: success() with: name: OpenSpeedy-unsigned-artifacts path: artifacts/ if-no-files-found: warn ================================================ FILE: .github/workflows/package.yml ================================================ name: Package on: workflow_dispatch: inputs: build_id: description: '构建工作流ID' required: true type: string version: description: '版本号' required: true default: '1.0.0' type: string artifact_name: description: '签名的制品名称' required: true default: 'OpenSpeedy-unsigned-artifacts' type: string jobs: package: runs-on: windows-latest # GitHub-hosted runner steps: - name: Checkout uses: actions/checkout@v4 - name: Download build artifact uses: actions/download-artifact@v4 with: name: ${{ github.event.inputs.artifact_name }} run-id: ${{ github.event.inputs.build_id }} path: artifacts/ github-token: ${{ secrets.GITHUB_TOKEN }} - id: upload-unsigned-artifacts name: Re-upload as new artifact uses: actions/upload-artifact@v4 with: name: OpenSpeedy-unsigned-artifacts path: artifacts/ retention-days: 30 - name: SignPath signing uses: signpath/github-action-submit-signing-request@v1.1 with: api-token: ${{ secrets.SIGNPATH_API_TOKEN }} organization-id: '58b9835d-38ea-4898-a564-76610c01cecd' project-slug: OpenSpeedy signing-policy-slug: release-signing github-artifact-id: ${{ steps.upload-unsigned-artifacts.outputs.artifact-id }} artifact-configuration-slug: initial wait-for-completion: true output-artifact-directory: signed-artifacts/ parameters: | version: ${{ toJSON(github.event.inputs.version) }} - name: Upload signed artifacts uses: actions/upload-artifact@v4 with: name: OpenSpeedy-${{ github.event.inputs.version }} path: signed-artifacts/ retention-days: 30 - name: Install WiX Toolset v3 run: | choco install wixtoolset -y $env:PATH += ";C:\Program Files (x86)\WiX Toolset v3.11\bin" echo "C:\Program Files (x86)\WiX Toolset v3.11\bin" | Out-File -FilePath $env:GITHUB_PATH -Encoding utf8 -Append - name: Prepare installer files run: | New-Item -ItemType Directory -Force -Path installer/files Copy-Item -Path "signed-artifacts/*" -Destination "installer/files/" -Recurse -Force - name: Build MSI installer run: | cd installer candle.exe OpenSpeedy.wxs -dVersion="${{ github.event.inputs.version }}" -ext WixUIExtension light.exe OpenSpeedy.wixobj -out ../OpenSpeedy-installer-${{ github.event.inputs.version }}.msi -ext WixUIExtension - id: upload-unsigned-installer name: Upload installer uses: actions/upload-artifact@v4 with: name: OpenSpeedy-unsigned-installer-${{ github.event.inputs.version }} path: OpenSpeedy-installer-${{ github.event.inputs.version }}.msi - name: SignPath signing uses: signpath/github-action-submit-signing-request@v1.1 with: api-token: ${{ secrets.SIGNPATH_API_TOKEN }} organization-id: '58b9835d-38ea-4898-a564-76610c01cecd' project-slug: OpenSpeedy signing-policy-slug: release-signing github-artifact-id: ${{ steps.upload-unsigned-installer.outputs.artifact-id }} artifact-configuration-slug: installer wait-for-completion: true output-artifact-directory: signed-installer/ parameters: | version: ${{ toJSON(github.event.inputs.version) }} - name: Upload signed installer uses: actions/upload-artifact@v4 with: name: OpenSpeedy-installer-${{ github.event.inputs.version }} path: signed-installer/ retention-days: 30 ================================================ FILE: .gitignore ================================================ # This file is used to ignore files which are generated # ---------------------------------------------------------------------------- *.msi *.wixobj *.wixpdb *~ *.autosave *.a *.core *.moc *.o *.obj *.orig *.rej *.so *.so.* *_pch.h.cpp *_resource.rc *.qm .#* *.*# core !core/ tags .DS_Store .directory *.debug Makefile* *.prl *.app moc_*.cpp ui_*.h qrc_*.cpp Thumbs.db *.res *.rc /.qmake.cache /.qmake.stash # qtcreator generated files *.pro.user* *.qbs.user* CMakeLists.txt.user* # xemacs temporary files *.flc # Vim temporary files .*.swp # Visual Studio generated files *.ib_pdb_index *.idb *.ilk *.pdb *.sln *.suo *.vcproj *vcproj.*.*.user *.ncb *.sdf *.opensdf *.vcxproj *vcxproj.* # MinGW generated files *.Debug *.Release # Python byte code *.pyc # Binaries # -------- *.dll *.exe # Directories with generated files .moc/ .obj/ .pch/ .rcc/ .uic/ /build*/ .vs/ out/ ================================================ FILE: .gitmodules ================================================ ================================================ FILE: CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.16) project(OpenSpeedy VERSION 1.7.7 LANGUAGES CXX) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) # 启用Qt静态链接 set(CMAKE_MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Widgets LinguistTools) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Widgets Network WinExtras LinguistTools) set(TS_FILES OpenSpeedy_zh_CN.ts OpenSpeedy_en_US.ts OpenSpeedy_zh_TW.ts ) set(PROJECT_SOURCES main.cpp mainwindow.cpp mainwindow.h mainwindow.ui themeutils.h themeutils.cpp ${TS_FILES} ) if(${QT_VERSION_MAJOR} GREATER_EQUAL 6) qt_add_executable(OpenSpeedy MANUAL_FINALIZATION ${PROJECT_SOURCES} winutils.h winutils.cpp processmonitor.h processmonitor.cpp resources.qrc images/icon.ico images/logo.png icons.rc ) # Define target properties for Android with Qt 6 as: # set_property(TARGET OpenSpeedy APPEND PROPERTY QT_ANDROID_PACKAGE_SOURCE_DIR # ${CMAKE_CURRENT_SOURCE_DIR}/android) # For more information, see https://doc.qt.io/qt-6/qt-add-executable.html#target-creation qt_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) else() qt5_create_translation(QM_FILES ${CMAKE_SOURCE_DIR} ${TS_FILES}) add_definitions("-DUNICODE -DNOMINMAX") add_executable(OpenSpeedy ${PROJECT_SOURCES} processmonitor.h processmonitor.cpp resources.qrc images/icon.ico images/logo.png icons.rc config.h windbg.h aboutdialog.ui aboutdialog.h aboutdialog.cpp aboutdialog.ui preferencedialog.h preferencedialog.cpp preferencedialog.ui qsinglekeysequenceedit.h qsinglekeysequenceedit.cpp ${QM_FILES} ) add_library(winutils winutils.h winutils.cpp cpuutils.h cpuutils.cpp memutils.h memutils.cpp taskscheduler.h taskscheduler.cpp ) target_include_directories(winutils PUBLIC ${CMAKE_CURRENT_SOURCE_DIR} ) target_link_libraries(winutils PUBLIC Qt${QT_VERSION_MAJOR}::Core pdh ole32 oleaut32 taskschd) endif() target_link_libraries(OpenSpeedy PRIVATE Qt${QT_VERSION_MAJOR}::Widgets Qt${QT_VERSION_MAJOR}::Network Qt${QT_VERSION_MAJOR}::WinExtras winutils ) # Qt for iOS sets MACOSX_BUNDLE_GUI_IDENTIFIER automatically since Qt 6.1. # If you are developing for iOS or macOS you should consider setting an # explicit, fixed bundle identifier manually though. if(${QT_VERSION} VERSION_LESS 6.1.0) set(BUNDLE_ID_OPTION MACOSX_BUNDLE_GUI_IDENTIFIER com.example.OpenSpeedy) endif() set_target_properties(OpenSpeedy PROPERTIES ${BUNDLE_ID_OPTION} MACOSX_BUNDLE_BUNDLE_VERSION ${PROJECT_VERSION} MACOSX_BUNDLE_SHORT_VERSION_STRING ${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR} MACOSX_BUNDLE TRUE WIN32_EXECUTABLE TRUE #LINK_FLAGS "/MANIFESTUAC:\"level='requireAdministrator' uiAccess='false'\" /SUBSYSTEM:WINDOWS" ) include(GNUInstallDirs) install(TARGETS OpenSpeedy BUNDLE DESTINATION . LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) if(QT_VERSION_MAJOR EQUAL 6) qt_finalize_executable(OpenSpeedy) endif() add_subdirectory(third_party/minhook) add_subdirectory(speedpatch) add_subdirectory(bridge) ================================================ FILE: CMakePresets.json ================================================ { "version": 3, "configurePresets": [ { "hidden": true, "name": "Qt", "cacheVariables": { "CMAKE_PREFIX_PATH": "$env{QTDIR}" }, "vendor": { "qt-project.org/Qt": { "checksum": "wVa86FgEkvdCTVp1/nxvrkaemJc=" } } } ], "vendor": { "qt-project.org/Presets": { "checksum": "67SmY24ZeVbebyKD0fGfIzb/bGI=" } } } ================================================ FILE: CMakeUserPresets.json ================================================ { "version": 3, "configurePresets": [ { "name": "Qt-Debug", "inherits": "Qt-Default", "binaryDir": "${sourceDir}/out/build/debug", "cacheVariables": { "CMAKE_BUILD_TYPE": "Debug", "CMAKE_CXX_FLAGS": "-DQT_QML_DEBUG" }, "environment": { "QML_DEBUG_ARGS": "-qmljsdebugger=file:{68d8eccf-89d3-401a-a51b-854d41e11c66},block" } }, { "name": "Qt-Release", "inherits": "Qt-Default", "binaryDir": "${sourceDir}/out/build/release", "cacheVariables": { "CMAKE_BUILD_TYPE": "Release" } }, { "hidden": true, "name": "Qt-Default", "inherits": "6.9.0_msvc2022_64", "vendor": { "qt-project.org/Default": { "checksum": "p2g8qSfRuZwrHdoqsydD/azGQjs=" } } }, { "hidden": true, "name": "6.9.0_msvc2022_64", "inherits": "Qt", "environment": { "QTDIR": "D:/Qt/6.9.0/msvc2022_64" }, "architecture": { "strategy": "external", "value": "x64" }, "generator": "Ninja", "vendor": { "qt-project.org/Version": { "checksum": "sBywmcWZZXChcZz0AVGlSBNHGws=" } } } ], "vendor": { "qt-project.org/Presets": { "checksum": "IQB0bB4OeX7kqF6cObd8brpl2ck=" } } } ================================================ FILE: LICENSE ================================================ GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not price. Our General Public Licenses are designed to make sure that you have the freedom to distribute copies of free software (and charge for them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If conditions are imposed on you (whether by court order, agreement or otherwise) that contradict the conditions of this License, they do not excuse you from the conditions of this License. If you cannot convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU General Public License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. Each version is given a distinguishing version number. If the Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state the exclusion of warranty; and each file should have at least the "copyright" line and a pointer to where the full notice is found. Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . ================================================ FILE: OpenSpeedy_en_US.ts ================================================ AboutDialog 关于 About OpenSpeedy 😄 General Public License v3 🎁 捐赠: Sponsor: <html><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></body></html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> p, li { white-space: pre-wrap; } hr { height: 1px; border-width: 0; } li.unchecked::marker { content: "\2610"; } li.checked::marker { content: "\2612"; } </style></head><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></p></body></html> <html><head/><body><p><a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> v0.0.0 作者: Author: <html><head/><body><p><a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">game1024/OpenSpeedy</span></a></p></body></html> 主页: Github: 版本: Version: 协议: License: <html><head/><body><p>作者:<a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> <html><head/><body><p>Author:<a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> 🚀 <html><head/><body><p>主页:<a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">https://github.com/game1024/OpenSpeedy</span></a></p></body></html> <html><head/><body><p>HomePage:<a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">https://github.com/game1024/OpenSpeedy</span></a></p></body></html> 🌳 版本:v0.0.0 Version:v0.0.0 📜 协议:General Public License v3 License:General Public License v3 确认 OK MainWindow OpenSpeedy Speedy ⚡变速速率 ⚡Acceleration 🖥️ 操作系统 🖥️ Operate System windows 11 24H2 🔥 CPU 10.0% 📊 内存 📊 Memory ( 7.2G / 32.0G ) 12.3% ♥️ 32bit 注入器 ♥️ 32bit Injector 正常 Normal ♥️ 64bit 注入器 ♥️ 64bit Injector ▲ 原速 ▲ Origin 💻进程 💻Processes 架构 Arch 浅色 Light 深色 Dark 体系结构 Arch x1.0倍 x1.0 times ✖️1.0倍 ✖️1.0 times Ctrl + Alt + ⬆️ 增加速度 Ctrl + Alt + ⬆️ Speed Up Ctrl + Alt + ⬇️ 减少速度 Ctrl + Alt + ⬇️ Speed Down Ctrl + Alt + 0 重置速度 Ctrl + Alt + 0 Reset Speed 开机自启 Launch at startup 💻系统进程 💻System Process 🔍输入进程名搜索... 🔍Search with process name 进程名称 Process Name PID 内存使用 Memory 平台架构 Arch 优先级 Priority 是否加速 isAccelerated 搜索到1200个进程, 已过滤展示20个 Found 1200 processes, filtered to show 20 📖关于 📖About ⌨️快捷键 ⌨️Keyboard 🌐语言 🌐Language 🎨主题 🎨Theme 中文(简体) 中文(繁體) English 变速速率 ⚡Acceleration 原速 Origin 系统进程 System Process 输入进程名搜索... Search with process name 线程数 Thread Num 🪟 操作系统 🪟 Operate System %1倍 %1 times ✖️%1倍 ✖️%1 times 显示 Show 隐藏 Hide 退出 Exit 提示 Tips 直到重启应用后,界面的语言才会生效 The UI language will only take effect after restarting the application. PreferenceDialog 快捷键 Keyboard 档位3 Shift3 速度 Speed Ctrl+Alt+1 减少速度 Speed Down 按键 Key Ctrl+Alt+5 档位5 Shift5 Ctrl+Alt+3 档位1 Shift1 Ctrl+Alt+0 重置速度 Speed Reset Ctrl+Alt+Up Ctrl+Alt+4 档位2 Shift2 Ctrl+Alt+2 Ctrl+Alt+Down 增加速度 Speed Up 档位4 Shift4 步幅 Step 确认 OK 取消 Cancel %1 增加速度 %1 Speed Up %1 减少速度 %1 Speed Down %1 重置速度 %1 Speed Reset ProcessMonitor 搜索到%1个进程, 已过滤展示%2个 Found %1 processes, filtered to show %2 加速中 Accelerating High Medium Low 实时 RT 未知 Unknown 启动失败 32位桥接子进程启动失败,请确保Speedy.exe和bridge32.exe在同一目录下 Failed to start 32-bit bridge subprocess. Please ensure Speedy.exe and bridge32.exe are in the same directory. 64位桥接子进程启动失败,请确保Speedy.exe和bridge64.exe在同一目录下 Failed to start 64-bit bridge subprocess. Please ensure Speedy.exe and bridge64.exe are in the same directory. 正常 Normal 异常退出 Error Exit ================================================ FILE: OpenSpeedy_zh_CN.ts ================================================ AboutDialog 关于 OpenSpeedy 😄 General Public License v3 🎁 捐赠: <html><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></body></html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> p, li { white-space: pre-wrap; } hr { height: 1px; border-width: 0; } li.unchecked::marker { content: "\2610"; } li.checked::marker { content: "\2612"; } </style></head><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></p></body></html> <html><head/><body><p><a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> v0.0.0 作者: <html><head/><body><p><a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">game1024/OpenSpeedy</span></a></p></body></html> 主页: 版本: 协议: 🚀 🌳 📜 确认 MainWindow OpenSpeedy ⚡变速速率 🖥️ 操作系统 windows 11 24H2 🔥 CPU 10.0% 📊 内存 ( 7.2G / 32.0G ) 12.3% ♥️ 32bit 注入器 正常 ♥️ 64bit 注入器 ▲ 原速 💻进程 架构 ✖️1.0倍 Ctrl + Alt + ⬆️ 增加速度 Ctrl + Alt + ⬇️ 减少速度 Ctrl + Alt + 0 重置速度 开机自启 Speedy 🔍输入进程名搜索... 进程名称 PID 内存使用 优先级 是否加速 搜索到1200个进程, 已过滤展示20个 📖关于 ⌨️快捷键 🌐语言 🎨主题 中文(简体) 中文(繁體) 浅色 深色 English %1倍 ✖️%1倍 显示 隐藏 退出 提示 直到重启应用后,界面的语言才会生效 PreferenceDialog 快捷键 档位3 速度 Ctrl+Alt+1 减少速度 按键 Ctrl+Alt+5 档位5 Ctrl+Alt+3 档位1 Ctrl+Alt+0 重置速度 Ctrl+Alt+Up Ctrl+Alt+4 档位2 Ctrl+Alt+2 Ctrl+Alt+Down 增加速度 档位4 步幅 确认 取消 %1 增加速度 %1 减少速度 %1 重置速度 ProcessMonitor 搜索到%1个进程, 已过滤展示%2个 加速中 实时 未知 启动失败 32位桥接子进程启动失败,请确保Speedy.exe和bridge32.exe在同一目录下 64位桥接子进程启动失败,请确保Speedy.exe和bridge64.exe在同一目录下 正常 异常退出 ================================================ FILE: OpenSpeedy_zh_TW.ts ================================================ AboutDialog 关于 關於 OpenSpeedy 版本: 版本: 🎁 捐赠: 捐贈 <html><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></body></html> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd"> <html><head><meta name="qrichtext" content="1" /><meta charset="utf-8" /><style type="text/css"> p, li { white-space: pre-wrap; } hr { height: 1px; border-width: 0; } li.unchecked::marker { content: "\2610"; } li.checked::marker { content: "\2612"; } </style></head><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <p style=" margin-top:12px; margin-bottom:12px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></p></body></html> 😄 作者: 作者: 📜 General Public License v3 🚀 <html><head/><body><p><a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> 🌳 <html><head/><body><p><a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">game1024/OpenSpeedy</span></a></p></body></html> v0.0.0 协议: 協議: 主页: 主頁: 确认 確認 MainWindow OpenSpeedy ⚡变速速率 ⚡變速倍率 开机自启 開機自啟 ✖️1.0倍 ✖️1.0倍 🖥️ 操作系统 🖥️ 作業系統 Speedy windows 11 24H2 🔥 CPU 10.0% 📊 内存 📊 記憶體 ( 7.2G / 32.0G ) 12.3% ♥️ 32bit 注入器 ♥️ 32bit 注入器 正常 正常 ♥️ 64bit 注入器 ♥️ 64bit 注入器 ▲ 原速 ▲ 原速 Ctrl + Alt + ⬆️ 增加速度 Ctrl + Alt + ⬆️ 增加速度 Ctrl + Alt + ⬇️ 减少速度 Ctrl + Alt + ⬇️ 減少速度 Ctrl + Alt + 0 重置速度 Ctrl + Alt + 0 重設速度 💻进程 💻行程 浅色 深色 💻系统进程 💻系統行程 🔍输入进程名搜索... 🔍輸入行程名搜尋... 进程名称 行程名稱 PID 内存使用 記憶體使用 架构 架構 平台架构 平臺架構 优先级 優先順序 是否加速 是否加速 搜索到1200个进程, 已过滤展示20个 搜索到1200个行程, 已過濾顯示20個 📖关于 📖關於 ⌨️快捷键 ⌨️快速鍵 🌐语言 🌐語言 🎨主题 中文(简体) English 中文(繁體) 变速速率 變速速率 原速 原速 x1.0倍 x1.0倍 系统进程 系統行程 输入进程名搜索... 輸入行程名搜索 线程数 線程數 🪟 操作系统 🪟 作業系統 %1倍 %1倍 ✖️%1倍 ✖️%1倍 显示 顯示 隐藏 隱藏 退出 退出 提示 提示 直到重启应用后,界面的语言才会生效 直到重啟應用後,界面的語言才會生效 是否注入 是否注入 体系结构 架构 PreferenceDialog 快捷键 快速鍵 档位3 檔位3 速度 速度 Ctrl+Alt+1 减少速度 減少速度 按键 按鍵 Ctrl+Alt+5 档位5 檔位5 Ctrl+Alt+3 档位1 檔位1 Ctrl+Alt+0 重置速度 重設速度 Ctrl+Alt+Up Ctrl+Alt+4 档位2 檔位2 Ctrl+Alt+2 Ctrl+Alt+Down 增加速度 增加速度 档位4 檔位4 步幅 步進 确认 確認 取消 取消 %1 增加速度 %1 增加速度 %1 减少速度 %1 減少速度 %1 重置速度 %1 重設速度 ProcessMonitor 搜索到%1个进程, 已过滤展示%2个 搜尋到%1個行程,已篩選顯示%2個 加速中 加速中 標準 在標準以下 实时 即時 未知 未知 启动失败 32位桥接子进程启动失败,请确保Speedy.exe和bridge32.exe在同一目录下 32位橋接子進程啟動失敗,請確保Speedy.exe和bridge32.exe在同一目錄下 64位桥接子进程启动失败,请确保Speedy.exe和bridge64.exe在同一目录下 64位橋接子進程啟動失敗,請確保Speedy.exe和bridge64.exe在同一目錄下 正常 正常 异常退出 異常退出 ================================================ FILE: README.md ================================================

OpenSpeedy

OpenSpeedy is an open-source and free game speed tool that helps you break frame rate limitations and provides a smoother, silkier gaming acceleration experience.

Offcial Website


GitHub Stars GitHub Forks Github Issues
Downloads Version Github Action Platform
Commit Activity
Featured|HelloGitHub

简体中文 · 日本語 · English

# 🚀 Features - Completely free and open-source - Easy-to-use interface - Customizable speed multiplier - Good compatibility with various game engines - Low system resource consumption - Supports accelerating both x86 and x64 processes - Non-invasive to the kernel: Ring3 level Hook, does not compromise the system kernel # 💾 Installation 📦 **Method1: Winget** ``` powershell # install winget install openspeedy # open a new terminal, you can run openspeedy by following command speedy ``` 📥 **Method2: Manual Download** Visit the [Installation Page](https://github.com/game1024/OpenSpeedy/releases) to download the latest version # 💻 System Requirements - OS: Windows 10 or later - Platform: x86 (32-bit) and x64 (64-bit) # 📝 Usage Instructions 1. Start OpenSpeedy 2. Launch the target game you want to speed up 3. Select the game process, and adjust the speed multiplier in the OpenSpeedy interface 4. The effect takes effect immediately. Compare the results below # 🔧 Technical Principle OpenSpeedy achieves game speed adjustment by hooking the following Windows system time functions: | Function Name | Library | Description | |---------------|---------|-------------| | Sleep | user32.dll | Thread sleep | | SetTimer | user32.dll | Create message-based timer | | timeGetTime | winmm.dll | Get milliseconds elapsed since system startup | | GetTickCount | kernel32.dll | Get milliseconds elapsed since system startup | | GetTickCount64 | kernel32.dll | Get milliseconds elapsed since system startup (64-bit) | | QueryPerformanceCounter | kernel32.dll | High precision performance counter | | GetSystemTimeAsFileTime | kernel32.dll | Get system time | | GetSystemTimePreciseAsFileTime | kernel32.dll | Get high precision system time | # ⚠️ Notes - This tool is for learning and research purposes only - Some online games may have anti-cheat systems. Using this tool may result in your account being banned - Excessive speeding up may cause the game physics engine to malfunction or crash - Not recommended for use in competitive online games - Open source product does not include digital signature and may be falsely flagged by antivirus software # 🔄 Feedback If you encounter any issues during use, feel free to provide feedback via: - [FAQ](https://github.com/game1024/OpenSpeedy/wiki#faq) - You can first check the wiki to locate the issue. - [GitHub Issues](https://github.com/game1024/OpenSpeedy/issues) - Submit issue reports # 🎁 Buy me a coffee If you find the OpenSpeedy project helpful, you can buy me a coffee~ ☕️ |Name|Description| |--|--| |365VPN|uses dedicated lines to connect worldwide, offering speeds of up to 10Gbps. Download now to start surfing for free🏄: https://ref.365tz87989.com/?r=RWQVZD| |Github Sponsor|https://github.com/sponsors/game1024| # Sponsors
SignPath logo This program uses free code signing provided by SignPath.io and a certificate by the SignPath Foundation
# 📜 License OpenSpeedy is licensed under the GNU v3 License. # 🙏 Acknowledgements OpenSpeedy uses source code from the following projects. Thanks to the open-source community! If OpenSpeedy helps you, please give us a Star! - [minhook](https://github.com/TsudaKageyu/minhook): For API Hooking - [Qt](https://www.qt.io/): GUI Disclaimer: OpenSpeedy is intended for educational and research purposes only. Users assume all risks and responsibilities for using this software. The author is not responsible for any loss or legal liability resulting from the use of this software. Contribution Leaderboard

Star History Chart

================================================ FILE: aboutdialog.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "aboutdialog.h" #include "ui_aboutdialog.h" #include #include AboutDialog::AboutDialog(QWidget* parent) : QDialog(parent) , ui(new Ui::AboutDialog) { ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("确认")); ui->versionContent->setText(QString("%1").arg(OPENSPEEDY_VERSION)); connect(QGuiApplication::primaryScreen(), &QScreen::logicalDotsPerInchChanged, this, &AboutDialog::recreate); setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); } AboutDialog::~AboutDialog() { delete ui; } void AboutDialog::recreate() { layout()->invalidate(); layout()->activate(); adjustSize(); } ================================================ FILE: aboutdialog.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef ABOUTDIALOG_H #define ABOUTDIALOG_H #include "config.h" #include namespace Ui { class AboutDialog; } class AboutDialog : public QDialog { Q_OBJECT public: explicit AboutDialog(QWidget* parent = nullptr); ~AboutDialog(); private slots: void recreate(); private: Ui::AboutDialog* ui; }; #endif // ABOUTDIALOG_H ================================================ FILE: aboutdialog.ui ================================================ AboutDialog Qt::ApplicationModal 0 0 440 215 0 0 0 0 16777215 16777215 关于 false false 7 QLayout::SetFixedSize 微软雅黑 12 OpenSpeedy Qt::AlignCenter QLayout::SetMaximumSize 4 0 0 Segoe UI Emoji 12 😄 0 0 微软雅黑 版本: false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 0 0 Segoe UI Emoji 12 🚀 0 0 Segoe UI Emoji 12 🌳 微软雅黑 v0.0.0 微软雅黑 <html><head/><body><p><a href="https://github.com/game1024"><span style=" text-decoration: none; color:#003e92;">game1024</span></a></p></body></html> true 0 0 微软雅黑 协议: false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 0 0 Segoe UI Emoji 12 📜 微软雅黑 General Public License v3 微软雅黑 <html><head/><body><p><a href="https://github.com/game1024/OpenSpeedy"><span style=" text-decoration: none; color:#003e92;">game1024/OpenSpeedy</span></a></p></body></html> true 0 0 微软雅黑 作者: false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true 0 0 微软雅黑 主页: false Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter true Segoe UI Emoji 12 🎁 微软雅黑 捐赠: Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 微软雅黑 <html><body style=" font-family:'微软雅黑'; font-size:9pt; font-weight:400; font-style:normal;"> <a href="https://afdian.com/a/game1024"><span style="text-decoration: none; color:#003e92">afdian/a/game1024</span></a></body></html> true QDialogButtonBox::Ok buttonBox accepted() AboutDialog accept() 219 154 219 89 ================================================ FILE: bridge/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.16) project(Bridge LANGUAGES CXX) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ..) find_package(QT NAMES Qt6 Qt5 REQUIRED COMPONENTS Core) find_package(Qt${QT_VERSION_MAJOR} REQUIRED COMPONENTS Core) # 判断是32位还是64位 if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(TARGET_NAME "bridge64") set(SPEEDPATCH_LIBRARY "speedpatch64") elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) set(TARGET_NAME "bridge32") set(SPEEDPATCH_LIBRARY "speedpatch32") else() set(TARGET_NAME "bridge64") set(SPEEDPATCH_LIBRARY "speedpatch") endif() add_executable(${TARGET_NAME} main.cpp ) target_link_libraries(${TARGET_NAME} Qt${QT_VERSION_MAJOR}::Core ${SPEEDPATCH_LIBRARY} winutils) include(GNUInstallDirs) install(TARGETS ${TARGET_NAME} LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR} ) ================================================ FILE: bridge/main.cpp ================================================ #include "../config.h" #include "../speedpatch/speedpatch.h" #include "../windbg.h" #include "../winutils.h" #include #include #include #include #include #ifndef _WIN64 #define SPEEDPATCH_DLL SPEEDPATCH32_DLL #else #define SPEEDPATCH_DLL SPEEDPATCH64_DLL #endif void handleInject(int processId, QString dllPath) { qDebug() << "执行 inject,进程ID:" << processId; winutils::injectDll(processId, dllPath); SetProcessStatus(processId, true); } void handleUnhook(int processId, QString dllPath) { qDebug() << "执行 unhook,进程ID:" << processId; SetProcessStatus(processId, false); } void handleChange(double factor) { qDebug() << "执行 change,参数:" << factor; ChangeSpeed(factor); } int main(int argc, char* argv[]) { SetUnhandledExceptionFilter(createMiniDump); QCoreApplication a(argc, argv); if (winutils::enableAllPrivilege()) { qDebug() << "权限提升成功"; } QString dllPath = QDir::toNativeSeparators( QCoreApplication::applicationDirPath() + "/" + SPEEDPATCH_DLL); QTextStream in(stdin); QTextStream out(stdout); QRegularExpression injectRegex("^\\s*inject\\s+(\\d+)\\s*$", QRegularExpression::CaseInsensitiveOption); QRegularExpression unhookRegex("^\\s*unhook\\s+(\\d+)\\s*$", QRegularExpression::CaseInsensitiveOption); QRegularExpression changeRegex("^\\s*change\\s+([+-]?\\d*\\.?\\d+)\\s*$", QRegularExpression::CaseInsensitiveOption); QRegularExpression exitRegex("^\\s*exit\\s*$", QRegularExpression::CaseInsensitiveOption); while (true) { QString line = in.readLine(); if (line.isNull()) { // 管道关闭或输入结束 break; } line = line.trimmed(); if (line.isEmpty()) continue; QRegularExpressionMatch match; if ((match = injectRegex.match(line)).hasMatch()) { int pid = match.captured(1).toInt(); handleInject(pid, dllPath); } else if ((match = unhookRegex.match(line)).hasMatch()) { int pid = match.captured(1).toInt(); handleUnhook(pid, dllPath); } else if ((match = changeRegex.match(line)).hasMatch()) { double factor = match.captured(1).toDouble(); handleChange(factor); } else if (exitRegex.match(line).hasMatch()) { qDebug() << "收到exit命令,程序即将退出。"; break; } else { qDebug() << "无效命令:" << line; } } return 0; } ================================================ FILE: config.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef CONFIG_H #define CONFIG_H #define OPENSPEEDY_VERSION "v1.7.9" #define BRIDGE32_EXE "bridge32.exe" #define BRIDGE64_EXE "bridge64.exe" #define SPEEDPATCH32_DLL "speedpatch32.dll" #define SPEEDPATCH64_DLL "speedpatch64.dll" #define CONFIG_LANGUAGE "General/Language" #define CONFIG_THEME "General/Theme" // 热键ID enum HotkeyIds { HOTKEY_INCREASE_SPEED = 1001, HOTKEY_DECREASE_SPEED = 1002, HOTKEY_RESET_SPEED = 1003, HOTKEY_SHIFT1 = 1011, HOTKEY_SHIFT2 = 1012, HOTKEY_SHIFT3 = 1013, HOTKEY_SHIFT4 = 1014, HOTKEY_SHIFT5 = 1015 }; #endif // CONFIG_H ================================================ FILE: cpuutils.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "cpuutils.h" CpuUtils::CpuUtils() { } bool CpuUtils::init() { // 创建查询 if (PdhOpenQuery(NULL, NULL, &hQuery) != ERROR_SUCCESS) return false; if (PdhAddEnglishCounter(hQuery, L"\\Processor(_Total)\\% Processor Time", NULL, &hCounter) != ERROR_SUCCESS) { PdhCloseQuery(hQuery); return false; } // 第一次采样 PdhCollectQueryData(hQuery); initialized = true; return true; } double CpuUtils::getUsage() { if (!initialized) return -1; // 收集数据 if (PdhCollectQueryData(hQuery) != ERROR_SUCCESS) return -1; PDH_FMT_COUNTERVALUE value; if (PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, NULL, &value) != ERROR_SUCCESS) return -1; return value.doubleValue; } QString CpuUtils::getModel() { int cpuInfo[4]; char cpuBrand[48 + 1] = {0}; // 获取CPU品牌字符串(需要调用3次CPUID) __cpuid(cpuInfo, 0x80000002); memcpy(cpuBrand, cpuInfo, sizeof(cpuInfo)); __cpuid(cpuInfo, 0x80000003); memcpy(cpuBrand + 16, cpuInfo, sizeof(cpuInfo)); __cpuid(cpuInfo, 0x80000004); memcpy(cpuBrand + 32, cpuInfo, sizeof(cpuInfo)); QString result(cpuBrand); return result.trimmed(); } CpuUtils::~CpuUtils() { if (hCounter) PdhRemoveCounter(hCounter); if (hQuery) PdhCloseQuery(hQuery); } ================================================ FILE: cpuutils.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef CPUUTILS_H #define CPUUTILS_H #include #include #include class CpuUtils { private: PDH_HQUERY hQuery = NULL; PDH_HCOUNTER hCounter = NULL; bool initialized = false; public: CpuUtils(); ~CpuUtils(); bool init(); double getUsage(); QString getModel(); }; #endif // CPUUTILS_H ================================================ FILE: docs/README_cn.md ================================================

OpenSpeedy

OpenSpeedy 是一款开源免费的游戏变速工具,让你的游戏突破帧率限制,提供更流畅丝滑的游戏加速体验。

官方网站


GitHub Stars GitHub Forks Github Issues
Downloads Version Github Action Platform
提交活跃度
Featured|HelloGitHub

简体中文 · 日本語 · English

# 🚀 特性 - 完全免费且开源 - 简单易用的界面 - 可自定义变速倍率 - 对多种游戏引擎兼容性良好 - 低系统资源占用 - 同时可以加速x86和x64平台进程 - 无内核侵入性,Ring3层Hook,不破坏系统内核 # 💾 安装 📦 **方式1: Winget** ``` powershell # 安装命令如下 winget install openspeedy # 打开一个新的终端,运行openspeedy speedy ``` 📥 **方式2: 手动下载** 访问 [安装页面](https://github.com/game1024/OpenSpeedy/releases) 下载最新版本 📥 **方式3:微软商店下载(仅限中国地区)** # 💻 操作系统要求 - OS: Windows10 以上 - 平台:x86(32位) 和 x64 (64位) # 📝 使用说明 1. 启动 OpenSpeedy 2. 运行需要变速的目标游戏 3. 勾选游戏进程,在 OpenSpeedy 界面中调整速度倍率 4. 即刻生效,对比效果如下 # 🔧 技术原理 如果想要了解如何编译项目,可以参考[开发者文档](https://github.com/game1024/OpenSpeedy/wiki/%E5%BC%80%E5%8F%91%E8%80%85%E6%96%87%E6%A1%A3) OpenSpeedy 通过 Hook 以下 Windows 系统时间函数来实现游戏速度调整: |函数名 | 所属库 | 功能 | |--------|----------|------------------| |Sleep|user32.dll|线程休眠| |SetTimer|user32.dll|创建基于消息的计时器| |timeGetTime | winmm.dll | 获取系统启动后经过的毫秒数 | |GetTickCount | kernel32.dll | 获取系统启动后经过的毫秒数 | |GetTickCount64 | kernel32.dll | 获取系统启动后经过的毫秒数(64位) | |QueryPerformanceCounter | kernel32.dll | 高精度性能计数器 | |GetSystemTimeAsFileTime | kernel32.dll | 获取系统时间 | |GetSystemTimePreciseAsFileTime | kernel32.dll | 获取高精度系统时间 | # ⚠️ 注意事项 - 本工具仅供学习和研究使用 - 部分在线游戏可能有反作弊系统,使用本工具可能导致账号被封禁 - 过度加速可能导致游戏物理引擎异常或崩溃 - 不建议在竞技类在线游戏中使用 - 开源产品不带数字签名,可能被杀毒软件误报 # 🔄 反馈 如果在使用过程中遇到任何问题,欢迎通过以下方式反馈: - [FAQ](https://github.com/game1024/OpenSpeedy/wiki#faq) - 先查看wiki定位常见问题 - [GitHub Issues](https://github.com/game1024/OpenSpeedy/issues) - 提交问题报告, 网盘类问题请勿提issue, 我不支持, 谢谢合作~🙏 # 🎁 请我喝杯咖啡 如果觉得OpenSpeedy项目对你有帮助,可以请我喝杯咖啡~☕️ |名称|介绍|备注| |-|-|-| |365VPN|我用过最稳定的,不限流的全系统VPN|[体验地址](https://ref.365tz87989.com/?r=RWQVZD)| # 📜 开源协议 OpenSpeedy 遵循 GNU v3 许可证。 # 🙏 鸣谢 OpenSpeedy使用到以下项目的源码,感谢开源社区的力量,如果OpenSpeedy对你有帮助,欢迎Star! - [minhook](https://github.com/TsudaKageyu/minhook): 用于API Hook - [Qt](https://www.qt.io/): GUI 免责声明: OpenSpeedy 仅用于教育和研究目的。用户应自行承担使用本软件的所有风险和责任。作者不对因使用本软件导致的任何损失或法律责任负责。 Contribution Leaderboard

Star History Chart

================================================ FILE: docs/README_ja.md ================================================

OpenSpeedy

OpenSpeedyは、フレームレート制限を突破し、よりスムーズで快適なゲーム加速体験を提供する、オープンソースかつ無料のゲーム速度調整ツールです。


GitHub Stars GitHub Forks Github Issues
Downloads Version Github Action Platform
コミットアクティビティ

简体中文 · 日本語 · English

# 🚀 特徴 - 完全無料・オープンソース - シンプルで使いやすいインターフェース - 速度倍率をカスタマイズ可能 - 様々なゲームエンジンとの高い互換性 - 低いシステムリソース消費 - x86およびx64プラットフォームのプロセスを同時に加速可能 - カーネル非侵入型、Ring3レベルのHook、システムカーネルを破壊しない # 📥 インストール 1. [インストールページ](https://github.com/game1024/OpenSpeedy/releases)にアクセスし、最新版をダウンロードしてください 2. ダウンロードしたファイルを任意の場所に解凍してください 3. インストール不要、「OpenSpeedy.exe」を直接実行するだけで利用できます # 💻 動作環境 - OS: Windows10以降 - プラットフォーム:x86(32ビット)およびx64(64ビット) # 📝 使い方 1. OpenSpeedyを起動する 2. 速度を変更したいゲームを起動する 3. ゲームプロセスを選択し、OpenSpeedyの画面で速度倍率を調整する 4. すぐに効果が反映されます。下記の比較動画をご覧ください # 🔧 技術原理 OpenSpeedyは、以下のWindowsシステム時間関数をHookすることで、ゲーム速度を調整しています: | 関数名 | 所属ライブラリ | 機能 | |--------|--------|------------------| | Sleep | user32.dll | スレッドのスリープ | | SetTimer | user32.dll | メッセージベースのタイマー作成 | | timeGetTime | winmm.dll | システム起動後の経過ミリ秒数取得 | | GetTickCount | kernel32.dll | システム起動後の経過ミリ秒数取得 | | GetTickCount64 | kernel32.dll | システム起動後の経過ミリ秒数取得 (64ビット) | | QueryPerformanceCounter | kernel32.dll | 高精度パフォーマンスカウンタ | | GetSystemTimeAsFileTime | kernel32.dll | システム時刻の取得 | | GetSystemTimePreciseAsFileTime | kernel32.dll | 高精度なシステム時刻の取得 | # ⚠️ 注意事項 - 本ツールは学習および研究用途のみを目的としています - 一部オンラインゲームにはアンチチートシステムが搭載されています。本ツールの使用によりアカウントがBANされる場合があります - 過度な加速は、ゲームの物理エンジン異常やクラッシュの原因となる場合があります - 対戦型オンラインゲームでの利用は推奨しません - オープンソース製品のためデジタル署名は付与しておらず、ウイルス対策ソフトによる誤検出の可能性があります # 🔄 フィードバック 使用中に問題が発生した場合は、以下の方法でご連絡ください: - [FAQ](https://github.com/game1024/OpenSpeedy/wiki#faq) - まずはWikiを確認して問題の場所を特定できます - [GitHub Issues](https://github.com/game1024/OpenSpeedy/issues) - 不具合報告 # 🎁 スポンサー もしOpenSpeedyプロジェクトが役に立ったと感じたら、コーヒーをご馳走していただけると嬉しいです~ ☕️ 365VPNは専用回線を利用して世界中を接続し、最大10Gbpsの速度を提供します。今すぐダウンロードして無料でサーフィンを始めましょう🏄: https://ref.365tz87989.com/?r=RWQVZD # 📜 ライセンス OpenSpeedyはGNU v3ライセンスに従っています。 # 🙏 クレジット OpenSpeedyは以下のプロジェクトのソースコードを使用しています。オープンソースコミュニティに感謝します。OpenSpeedyが役立った場合はStarをお願いします! - [minhook](https://github.com/TsudaKageyu/minhook): APIフック用 - [Qt](https://www.qt.io/): GUI 免責事項: OpenSpeedyは教育及び研究目的のみでご利用ください。本ソフトウェアの使用に伴うすべてのリスクと責任は利用者にあります。著者は本ソフトウェアの使用によるいかなる損害や法的責任も一切負いません。 Contribution Leaderboard

Star History Chart

================================================ FILE: installer/OpenSpeedy.wxs ================================================ ================================================ FILE: installer/config/config.xml ================================================  Speedy 1.0.0 Speedy Game1024 Speedy @HomeDir@/Speedy Modern true ================================================ FILE: installer/create_installer.bat ================================================ set QTIFWDIR=D:\Qt\Tools\QtInstallerFramework\4.9\bin %QTIFWDIR%\binarycreator.exe -c %~dp0config\config.xml -p packages OpenSpeedy-installer.exe ================================================ FILE: main.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "mainwindow.h" #include "themeutils.h" #include "windbg.h" #include #include #include #include #include #include #include int main(int argc, char* argv[]) { SetUnhandledExceptionFilter(createMiniDump); SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); QApplication a(argc, argv); QSettings settings(QCoreApplication::applicationDirPath() + "/config.ini", QSettings::IniFormat); int theme = settings.value(CONFIG_THEME, ThemeUtils::Light).toInt(); ThemeUtils::applyTheme((ThemeUtils::Theme)theme); winutils::enableAllPrivilege(); // 检查是否已有实例在运行 QString unique = "OpenSpeedy"; QLocalSocket socket; socket.connectToServer(unique); if (socket.waitForConnected(500)) { socket.close(); return -1; } // 使用资源文件中的图标 QIcon appIcon; appIcon.addFile(":/icons/images/icon_16.ico", QSize(16, 16)); appIcon.addFile(":/icons/images/icon_32.ico", QSize(32, 32)); appIcon.addFile(":/icons/images/icon_64.ico", QSize(64, 64)); a.setWindowIcon(appIcon); QTranslator translator; const QString baseName = "OpenSpeedy_" + settings.value(CONFIG_LANGUAGE, QLocale().system().name()).toString(); if (translator.load(":/i18n/translations/" + baseName)) { a.installTranslator(&translator); } // 解析命令行参数 QCommandLineParser parser; parser.setApplicationDescription("OpenSpeedy"); QCommandLineOption minimizeOption( QStringList() << "m" << "minimize-to-tray", "启动时最小化到托盘"); parser.addOption(minimizeOption); parser.process(a); MainWindow w; if (parser.isSet(minimizeOption)) { w.hide(); } else { w.show(); } // 创建并启动本地服务器 QLocalServer server; QLocalServer::removeServer(unique); server.listen(unique); // 当用户尝试再运行一个进程时,将窗口显示到最前台 QObject::connect(&server, &QLocalServer::newConnection, [&] { w.show(); w.raise(); w.showNormal(); w.activateWindow(); }); return a.exec(); } ================================================ FILE: mainwindow.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "./ui_mainwindow.h" #include "mainwindow.h" #include "themeutils.h" #include #include #include #include #include #include #include #include MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); QScreen *screen = QGuiApplication::primaryScreen(); if (screen != nullptr) { qreal dpiScale = screen->devicePixelRatio(); QRect screenGeometry = screen->availableGeometry(); int windowWidth = 1024; int windowHeight = 768; if (dpiScale >= 2) { windowWidth = static_cast(1024 / 1.5); windowHeight = static_cast(768 / 1.5); } windowWidth = qMin(windowWidth, screenGeometry.width()-100); windowHeight = qMin(windowHeight, screenGeometry.height()-100); this->resize(windowWidth, windowHeight); int x = (screenGeometry.width() - this->frameGeometry().width()) / 2 ; int y = (screenGeometry.height() - this->frameGeometry().height()) /2; this->move(x, y); } init(); } MainWindow::~MainWindow() { QApplication::instance()->removeNativeEventFilter(this); m_thread->quit(); m_thread->wait(); delete m_settings; delete m_aboutDlg; delete m_preferenceDlg; delete m_processMonitor; delete m_cpu; delete m_mem; delete ui; } void MainWindow::recreate() { // step1: 获取主屏幕的缩放比例 // step2: 根据缩放比例调整窗口大小 // step3: 确保窗口不会超出屏幕范围 QScreen* primaryScreen = QApplication::primaryScreen(); qreal dpiScale = primaryScreen->devicePixelRatio(); QRect screenGeometry = primaryScreen->availableGeometry(); int windowWidth = 1024; int windowHeight = 768; if (dpiScale >= 2) { windowWidth = static_cast(1024 / 1.5); windowHeight = static_cast(768 / 1.5); } windowWidth = qMin(windowWidth, screenGeometry.width()-100); windowHeight = qMin(windowHeight, screenGeometry.height()-100); this->resize(windowWidth, windowHeight); layout()->invalidate(); layout()->activate(); //adjustSize(); recreateTray(); } void MainWindow::refresh() { // 获取当前主题下的高亮文本颜色 QColor highlightColor = QApplication::palette().color(QPalette::Highlight); // 如果是深色模式,使用亮蓝色;如果是浅色模式,使用深蓝色 QString colorStr = (QApplication::palette().color(QPalette::Window).value() < 128) ? "lightblue" : "blue"; ui->cpuContent->setText(QString("%2%") .arg(colorStr) .arg(m_cpu->getUsage(), 5, 'f', 1, ' ')); double memUsage = m_mem->getUsage(); double memTotal = m_mem->getTotal(); ui->memContent->setText( QString("(%2G / %3G) %4%") .arg(colorStr) .arg(memUsage, 0, 'f', 1) .arg(memTotal, 0, 'f', 1) .arg(memUsage / memTotal * 100, 4, 'f', 1)); } void MainWindow::on_sliderCtrl_valueChanged(int value) { double factor = speedFactor(value); m_processMonitor->changeSpeed(factor); if (factor >= 1.0) { ui->sliderCtrl->setToolTip(QString(tr("%1倍")).arg(factor, 0, 'f', 2)); ui->sliderLabel->setText(QString(tr("✖️%1倍")).arg(factor, 0, 'f', 2)); } else { ui->sliderCtrl->setToolTip(QString(tr("%1倍")).arg(factor, 0, 'f')); ui->sliderLabel->setText(QString(tr("✖️%1倍")).arg(factor, 0, 'f')); } ui->sliderInputSpinBox->setValue(factor); m_settings->setValue(CONFIG_SLIDERVALUE_KEY, value); m_settings->sync(); } void MainWindow::on_sliderInputSpinBox_editingFinished() { double factor = ui->sliderInputSpinBox->value(); ui->sliderInputSpinBox->clearFocus(); ui->sliderCtrl->setValue(sliderValue(factor)); } void MainWindow::on_processNameFilter_textChanged(const QString &text) { m_processMonitor->setFilter(text); } void MainWindow::on_sliderLabel_clicked() { if (ui->sliderCtrl->value() != 0) { m_back = ui->sliderCtrl->value(); ui->sliderCtrl->setValue(0); } else { ui->sliderCtrl->setValue(m_back); } } void MainWindow::iconActivated(QSystemTrayIcon::ActivationReason reason) { { switch (reason) { case QSystemTrayIcon::Trigger: // 单击 if (isVisible()) hide(); else { show(); showNormal(); activateWindow(); } break; case QSystemTrayIcon::DoubleClick: // 双击 show(); showNormal(); activateWindow(); break; default: break; } } } void MainWindow::createTray() { // 创建系统托盘图标 trayIcon = new QSystemTrayIcon(this); trayIcon->setIcon(QIcon(":/icons/images/icon.ico")); trayIcon->setToolTip("OpenSpeedy"); // 创建托盘菜单、创建动作 trayMenu = new QMenu(this); showAction = new QAction(tr("显示"), this); hideAction = new QAction(tr("隐藏"), this); quitAction = new QAction(tr("退出"), this); // 连接信号和槽 connect(showAction, &QAction::triggered, this, [&] { showNormal(); activateWindow(); }); connect(hideAction, &QAction::triggered, this, &MainWindow::hide); connect(quitAction, &QAction::triggered, qApp, &QApplication::quit); // 添加动作到菜单 trayMenu->addAction(showAction); trayMenu->addAction(hideAction); trayMenu->addSeparator(); trayMenu->addAction(quitAction); // 设置托盘图标的菜单 trayIcon->setContextMenu(trayMenu); // 处理托盘图标的点击事件 connect(trayIcon, &QSystemTrayIcon::activated, this, &MainWindow::iconActivated); // 显示托盘图标 trayIcon->show(); } double MainWindow::speedFactor(int sliderValue) { double factor = 1.0; if (sliderValue > 0.0) { factor = 1.0 + (double)sliderValue / 100; } else if (sliderValue < 0.0) { factor = 1.0 + (double)sliderValue / 100000; } else { factor = 1.0; } return factor; } int MainWindow::sliderValue(double speedFactor) { int sliderValue = 0; if (speedFactor > 1.0) { sliderValue = (long long)(speedFactor * 100) - 100; } else if (speedFactor < 1.0) { sliderValue = (long long)(speedFactor * 100000) - 100000; } else { sliderValue = 0; } qDebug() << sliderValue; return sliderValue; } void MainWindow::recreateTray() { qDebug() << "重绘托盘"; delete trayMenu; delete trayIcon; delete showAction; delete hideAction; delete quitAction; createTray(); adjustSize(); } void MainWindow::init() { m_back = 0; m_settings = new QSettings(QCoreApplication::applicationDirPath() + "/config.ini", QSettings::IniFormat); m_aboutDlg = new AboutDialog(this); m_preferenceDlg = new PreferenceDialog((HWND)winId(), m_settings, ui->increaseSpeedLabel, ui->decreaseSpeedLabel, ui->resetSpeedLabel, this); // 安装本地事件过滤器以处理全局快捷键 QApplication::instance()->installNativeEventFilter(this); m_processMonitor = new ProcessMonitor( m_settings, ui->processMonitorWidget, ui->processMonitorLabel, ui->injector32Status, ui->injector64Status, nullptr); m_thread = new QThread(this); connect(m_thread, &QThread::started, m_processMonitor, &ProcessMonitor::start); connect(m_thread, &QThread::finished, m_processMonitor, &QObject::deleteLater); connect(m_thread, &QThread::finished, m_thread, &QThread::deleteLater); connect(QGuiApplication::primaryScreen(), &QScreen::logicalDotsPerInchChanged, this, &MainWindow::recreate); m_thread->start(); m_processMonitor->start(); createTray(); QApplication::setQuitOnLastWindowClosed(false); ui->osContent->setText(winutils::getWindowsVersion()); m_cpu = new CpuUtils(); m_cpu->init(); m_mem = new MemUtils(); m_mem->init(); m_timer = new QTimer(); refresh(); connect(m_timer, &QTimer::timeout, this, &MainWindow::refresh); m_timer->start(1000); /* 读取slider值 */ int value = qBound(ui->sliderCtrl->minimum(), m_settings->value(CONFIG_SLIDERVALUE_KEY, 0).toInt(), ui->sliderCtrl->maximum()); ui->sliderCtrl->setValue(value); if (winutils::isAutoStartEnabled(QApplication::applicationName())) { ui->autoStartCheckBox->setCheckState(Qt::Checked); } else { ui->autoStartCheckBox->setCheckState(Qt::Unchecked); } /* 首选项菜单 */ connect(ui->menuPreference, &QMenu::aboutToShow, [this] { ui->menuPreference->hide(); QTimer::singleShot(50, [this]() { m_preferenceDlg->show(); m_preferenceDlg->activateWindow(); m_preferenceDlg->raise(); }); }); /* 关于菜单 */ connect(ui->menuAbout, &QMenu::aboutToShow, [this] { ui->menuAbout->hide(); QTimer::singleShot(50, [this]() { m_aboutDlg->show(); m_aboutDlg->activateWindow(); m_aboutDlg->raise(); }); }); m_languageGroup = new QActionGroup(this); m_languageGroup->setExclusive(true); m_languageGroup->setEnabled(true); m_languageGroup->addAction(ui->actionCN); m_languageGroup->addAction(ui->actionTW); m_languageGroup->addAction(ui->actionEN); QString language = m_settings->value(CONFIG_LANGUAGE, QLocale().system().name()) .toString(); if (language == "zh_CN") { ui->actionCN->setChecked(true); } else if (language == "zh_TW") { ui->actionTW->setChecked(true); } else if (language == "en_US") { ui->actionEN->setChecked(true); } connect(ui->actionCN, &QAction::triggered, [this] { m_settings->setValue(CONFIG_LANGUAGE, "zh_CN"); QMessageBox msgBox(this); msgBox.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); msgBox.setIcon(QMessageBox::Information); msgBox.setWindowTitle(tr("提示")); msgBox.setText(tr("直到重启应用后,界面的语言才会生效")); msgBox.exec(); }); connect(ui->actionTW, &QAction::triggered, [this] { m_settings->setValue(CONFIG_LANGUAGE, "zh_TW"); QMessageBox msgBox(this); msgBox.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); msgBox.setIcon(QMessageBox::Information); msgBox.setWindowTitle(tr("提示")); msgBox.setText(tr("直到重启应用后,界面的语言才会生效")); msgBox.exec(); }); connect(ui->actionEN, &QAction::triggered, [this] { m_settings->setValue(CONFIG_LANGUAGE, "en_US"); QMessageBox msgBox(this); msgBox.setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); msgBox.setIcon(QMessageBox::Information); msgBox.setWindowTitle(tr("提示")); msgBox.setText(tr("直到重启应用后,界面的语言才会生效")); msgBox.exec(); }); m_themeGroup = new QActionGroup(this); m_themeGroup->setExclusive(true); m_themeGroup->setEnabled(true); m_themeGroup->addAction(ui->actionLightTheme); m_themeGroup->addAction(ui->actionDarkTheme); int theme = m_settings->value(CONFIG_THEME, ThemeUtils::Light).toInt(); if (theme == ThemeUtils::Light) { ui->actionLightTheme->setChecked(true); } else { ui->actionDarkTheme->setChecked(true); } connect(ui->actionLightTheme, &QAction::triggered, [this] { m_settings->setValue(CONFIG_THEME, ThemeUtils::Light); ThemeUtils::applyTheme(ThemeUtils::Light); refresh(); // 刷新界面以更新颜色 }); connect(ui->actionDarkTheme, &QAction::triggered, [this] { m_settings->setValue(CONFIG_THEME, ThemeUtils::Dark); ThemeUtils::applyTheme(ThemeUtils::Dark); refresh(); // 刷新界面以更新颜色 }); } void MainWindow::closeEvent(QCloseEvent *event) { // 如果托盘图标可见,则隐藏窗口而不是关闭 if (trayIcon->isVisible()) { hide(); // 阻止事件继续传播,防止应用关闭 event->ignore(); } else { // 如果没有托盘图标,则正常关闭 event->accept(); } } bool MainWindow::nativeEventFilter(const QByteArray &eventType, void *message, long *result) { Q_UNUSED(result) if (eventType == "windows_generic_MSG" || eventType == "windows_dispatcher_MSG") { MSG *msg = static_cast(message); if (msg->message == WM_HOTKEY) { static qint64 lastSoundTime = 0; qint64 currentTime = QDateTime::currentMSecsSinceEpoch(); bool canPlaySound = (currentTime - lastSoundTime > 500); int hotkeyId = msg->wParam; switch (hotkeyId) { case HOTKEY_INCREASE_SPEED: { int currentValue = ui->sliderCtrl->value(); if (currentValue < ui->sliderCtrl->maximum()) { if (canPlaySound) { std::thread([]() { Beep(400, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( currentValue + m_preferenceDlg->getIncreaseStep()); qDebug() << "全局快捷键: 增加速度到" << speedFactor(currentValue + m_preferenceDlg->getIncreaseStep()); } } break; case HOTKEY_DECREASE_SPEED: { int currentValue = ui->sliderCtrl->value(); if (currentValue > ui->sliderCtrl->minimum()) { if (canPlaySound) { std::thread([]() { Beep(400, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( currentValue - m_preferenceDlg->getDecreaseStep()); qDebug() << "全局快捷键: 降低速度到" << speedFactor(currentValue - m_preferenceDlg->getDecreaseStep()); } } break; case HOTKEY_RESET_SPEED: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue(0); qDebug() << "全局快捷键: 重置速度"; break; case HOTKEY_SHIFT1: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( sliderValue(m_preferenceDlg->getShift1())); break; case HOTKEY_SHIFT2: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( sliderValue(m_preferenceDlg->getShift2())); break; case HOTKEY_SHIFT3: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( sliderValue(m_preferenceDlg->getShift3())); break; case HOTKEY_SHIFT4: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( sliderValue(m_preferenceDlg->getShift4())); break; case HOTKEY_SHIFT5: if (canPlaySound) { std::thread([]() { Beep(1600, 5); }).detach(); lastSoundTime = currentTime; } ui->sliderCtrl->setValue( sliderValue(m_preferenceDlg->getShift5())); break; } return true; // 事件已处理 } } return false; // 让其他过滤器处理 } void MainWindow::on_autoStartCheckBox_stateChanged(int state) { QString execFilePath = QDir::toNativeSeparators(QApplication::applicationFilePath()); if (state == Qt::Checked) { qDebug() << QApplication::applicationName() << QApplication::applicationFilePath(); winutils::setAutoStart(true, QApplication::applicationName(), execFilePath); } else { winutils::setAutoStart(false, QApplication::applicationName(), execFilePath); } } ================================================ FILE: mainwindow.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MAINWINDOW_H #define MAINWINDOW_H #include "aboutdialog.h" #include "config.h" #include "cpuutils.h" #include "memutils.h" #include "preferencedialog.h" #include "processmonitor.h" #include "winutils.h" #include #include #include #include #include #define CONFIG_SLIDERVALUE_KEY "MainWindow/SliderValue" QT_BEGIN_NAMESPACE namespace Ui { class MainWindow; } QT_END_NAMESPACE class MainWindow : public QMainWindow , public QAbstractNativeEventFilter { Q_OBJECT public: MainWindow(QWidget* parent = nullptr); ~MainWindow(); private slots: void recreate(); void refresh(); void on_sliderCtrl_valueChanged(int value); void on_sliderInputSpinBox_editingFinished(); void on_processNameFilter_textChanged(const QString& text); void iconActivated(QSystemTrayIcon::ActivationReason reason); void recreateTray(); void on_sliderLabel_clicked(); void on_autoStartCheckBox_stateChanged(int arg1); private: Ui::MainWindow* ui; AboutDialog* m_aboutDlg; PreferenceDialog* m_preferenceDlg; QThread* m_thread; ProcessMonitor* m_processMonitor; QTimer* m_timer; QSystemTrayIcon* trayIcon; QMenu* trayMenu; QAction* showAction; QAction* hideAction; QAction* quitAction; CpuUtils* m_cpu; MemUtils* m_mem; QSettings* m_settings; int m_back; QActionGroup* m_languageGroup; QActionGroup* m_themeGroup; void init(); void createTray(); double speedFactor(int sliderValue); int sliderValue(double speedFactor); protected: void closeEvent(QCloseEvent* event) override; bool nativeEventFilter(const QByteArray& eventType, void* message, long* result) override; }; #endif // MAINWINDOW_H ================================================ FILE: mainwindow.ui ================================================ MainWindow 0 0 1024 768 0 0 800 480 16777215 16777215 MS PGothic OpenSpeedy QMainWindow { } Segoe UI Emoji 10 false PreferAntialias ⚡变速速率 微软雅黑 Qt::NoFocus 开机自启 false true 0 0 0 0 QFrame::StyledPanel QFrame::Raised 0 7 QLayout::SetMaximumSize QFormLayout::AllNonFixedFieldsGrow QFormLayout::DontWrapRows 12 Segoe UI Emoji true PreferAntialias true 🖥️ 操作系统 0 0 微软雅黑 windows 11 24H2 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Segoe UI Emoji true PreferAntialias true 🔥 CPU Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 0 0 微软雅黑 10.0% Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Segoe UI Emoji true PreferAntialias true 📊 内存 0 0 微软雅黑 ( 7.2G / 32.0G ) 12.3% Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Segoe UI Emoji true PreferAntialias true ♥️ 32bit 注入器 0 0 微软雅黑 正常 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter Segoe UI Emoji true PreferAntialias true ♥️ 64bit 注入器 0 0 微软雅黑 正常 Qt::AlignRight|Qt::AlignTrailing|Qt::AlignVCenter 0 0 微软雅黑 false PreferAntialias true color: #0078D4; ▲ 原速 Qt::AlignHCenter|Qt::AlignTop 0 0 0 100 0 微软雅黑 9 Qt::StrongFocus false false Qt::AlignCenter QAbstractSpinBox::UpDownArrows false true 0.010000000000000 1000.000000000000000 1.000000000000000 2 0 200 40 PointingHandCursor true false Qt::NoFocus QSlider::handle:horizontal { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(255, 255, 255, 0.9), stop:0.2 rgba(255, 255, 255, 0.7), stop:0.8 rgba(230, 230, 230, 0.8), stop:1 rgba(200, 200, 200, 0.9)); border: 1px solid rgba(150, 150, 150, 0.8); } QSlider::handle:horizontal:hover { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(255, 255, 255, 0.95), stop:0.2 rgba(227, 242, 253, 0.8), stop:0.8 rgba(144, 202, 249, 0.8), stop:1 rgba(100, 181, 246, 0.9)); border: 1px solid rgba(25, 118, 210, 0.8); } QSlider::handle:horizontal:pressed { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 rgba(227, 242, 253, 0.9), stop:0.3 rgba(144, 202, 249, 0.8), stop:0.7 rgba(66, 165, 245, 0.9), stop:1 rgba(25, 118, 210, 0.95)); border: 1px solid rgba(13, 71, 161, 0.9); } -99900 99900 100 0 true Qt::Horizontal true QSlider::TicksBothSides 3330 QFrame::Sunken 1 Qt::Vertical Qt::Horizontal 70 20 0 0 120 0 微软雅黑 14 PointingHandCursor Qt::NoFocus QPushButton { background-color: #0078D4; color: white; border-radius: 20px; padding: 10; } ✖️1.0倍 Qt::Horizontal QSizePolicy::Expanding 70 20 Segoe UI Emoji Ctrl + Alt + ⬆️ 增加速度 Segoe UI Emoji Ctrl + Alt + ⬇️ 减少速度 Segoe UI Emoji Ctrl + Alt + 0 重置速度 Qt::Horizontal Segoe UI Emoji 10 false PreferAntialias 💻进程 0 24 Microsoft YaHei UI height: 30px; border-radius: 15px; padding: 0px 8px; 🔍输入进程名搜索... true Qt::Horizontal QSizePolicy::Minimum 20 20 Qt::Horizontal QSizePolicy::Minimum 10 20 Qt::Horizontal 40 20 微软雅黑 9 Qt::NoFocus QTreeWidget::item { height: 30px; } QTreeWidget { border:none } true false true true 80 true true 进程名称 微软雅黑 true PID 微软雅黑 true 内存使用 微软雅黑 true 架构 微软雅黑 true 优先级 微软雅黑 true 是否加速 微软雅黑 true 微软雅黑 搜索到1200个进程, 已过滤展示20个 0 0 1024 18 false false 📖关于 false ⌨️快捷键 🌐语言 🎨主题 true 中文(简体) QAction::ApplicationSpecificRole true English QAction::ApplicationSpecificRole true 中文(繁體) QAction::ApplicationSpecificRole true 浅色 true 深色 processNameFilter processMonitorWidget ================================================ FILE: memutils.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "memutils.h" MemUtils::MemUtils() { } bool MemUtils::init() { if (PdhOpenQuery(NULL, NULL, &hQuery) != ERROR_SUCCESS) return false; if (PdhAddEnglishCounter(hQuery, L"\\Memory\\Available Bytes", NULL, &hCounter) != ERROR_SUCCESS) { PdhCloseQuery(hQuery); return false; } PdhCollectQueryData(hQuery); initialized = true; return true; } double MemUtils::getTotal() { MEMORYSTATUSEX memInfo; memInfo.dwLength = sizeof(MEMORYSTATUSEX); GlobalMemoryStatusEx(&memInfo); return memInfo.ullTotalPhys / (1024.0 * 1024.0 * 1024.0); } double MemUtils::getUsage() { if (!initialized) return -1; if (PdhCollectQueryData(hQuery) != ERROR_SUCCESS) return -1; PDH_FMT_COUNTERVALUE available; if (PdhGetFormattedCounterValue(hCounter, PDH_FMT_DOUBLE, NULL, &available) != ERROR_SUCCESS) return -1; double totalMemory = getTotal() * 1024 * 1024 * 1024; double usageMemory = totalMemory - available.doubleValue; return usageMemory / (1024.0 * 1024.0 * 1024.0); } ================================================ FILE: memutils.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MEMUTILS_H #define MEMUTILS_H #include #include class MemUtils { private: PDH_HQUERY hQuery = NULL; PDH_HCOUNTER hCounter = NULL; bool initialized = false; public: MemUtils(); bool init(); double getTotal(); double getUsage(); }; #endif // MEMUTILS_H ================================================ FILE: preferencedialog.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "preferencedialog.h" #include "ui_preferencedialog.h" #include #include #include PreferenceDialog::PreferenceDialog(HWND hMainWindow, QSettings* settings, QLabel* increaseSpeedLabel, QLabel* decreaseSpeedLabel, QLabel* resetSpeedLabel, QWidget* parent) : QDialog(parent) , ui(new Ui::PreferenceDialog) , m_settings(settings) , m_increaseSpeedLabel(increaseSpeedLabel) , m_decreaseSpeedLabel(decreaseSpeedLabel) , m_resetSpeedLabel(resetSpeedLabel) , m_mainwindow(hMainWindow) { ui->setupUi(this); setWindowFlags(Qt::Dialog | Qt::WindowTitleHint | Qt::CustomizeWindowHint); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(tr("确认")); ui->buttonBox->button(QDialogButtonBox::Cancel)->setText(tr("取消")); loadShortcut( HOTKEY_INCREASE_SPEED, CONFIG_HOTKEY_SPEEDUP, DEFAULT_HOTKEY_SPEEDUP); loadShortcut( HOTKEY_DECREASE_SPEED, CONFIG_HOTKEY_SPEEDDOWN, DEFAULT_HOTKEY_SPEEDDOWN); loadShortcut( HOTKEY_RESET_SPEED, CONFIG_HOTKEY_RESETSPEED, DEFAULT_HOTKEY_RERSETSPEED); loadShortcut(HOTKEY_SHIFT1, CONFIG_HOTKEY_SHIFT1, DEFAULT_HOTKEY_SHIFT1); loadShortcut(HOTKEY_SHIFT2, CONFIG_HOTKEY_SHIFT2, DEFAULT_HOTKEY_SHIFT2); loadShortcut(HOTKEY_SHIFT3, CONFIG_HOTKEY_SHIFT3, DEFAULT_HOTKEY_SHIFT3); loadShortcut(HOTKEY_SHIFT4, CONFIG_HOTKEY_SHIFT4, DEFAULT_HOTKEY_SHIFT4); loadShortcut(HOTKEY_SHIFT5, CONFIG_HOTKEY_SHIFT5, DEFAULT_HOTKEY_SHIFT5); m_shift1Value = m_settings->value(CONFIG_SHIFT1_VALUE, DEFAULT_SHIFT1_VALUE).toDouble(); m_shift2Value = m_settings->value(CONFIG_SHIFT2_VALUE, DEFAULT_SHIFT2_VALUE).toDouble(); m_shift3Value = m_settings->value(CONFIG_SHIFT3_VALUE, DEFAULT_SHIFT3_VALUE).toDouble(); m_shift4Value = m_settings->value(CONFIG_SHIFT4_VALUE, DEFAULT_SHIFT4_VALUE).toDouble(); m_shift5Value = m_settings->value(CONFIG_SHIFT5_VALUE, DEFAULT_SHIFT5_VALUE).toDouble(); m_increaseStep = m_settings->value(CONFIG_INCREASE_STEP, DEFAULT_INCREASE_STEP).toInt(); m_decreaseStep = m_settings->value(CONFIG_DECREASE_STEP, DEFAULT_DECREASE_STEP).toInt(); connect(QGuiApplication::primaryScreen(), &QScreen::logicalDotsPerInchChanged, this, &PreferenceDialog::recreate); redraw(); adjustSize(); setupGlobalHotkeys(); } PreferenceDialog::~PreferenceDialog() { unregisterGlobalHotkeys(); delete ui; } int PreferenceDialog::getIncreaseStep() { return m_increaseStep; } int PreferenceDialog::getDecreaseStep() { return m_decreaseStep; } double PreferenceDialog::getShift1() { return m_shift1Value; } double PreferenceDialog::getShift2() { return m_shift2Value; } double PreferenceDialog::getShift3() { return m_shift3Value; } double PreferenceDialog::getShift4() { return m_shift4Value; } double PreferenceDialog::getShift5() { return m_shift5Value; } void PreferenceDialog::show() { unregisterGlobalHotkeys(); QDialog::show(); } void PreferenceDialog::setupGlobalHotkeys() { for (auto it = m_shortcuts.begin(); it != m_shortcuts.end(); it++) { int id = it.key(); QtCombinedKey combined = it.value(); UINT vk = QSingleKeySequenceEdit::toVK(combined.key, combined.modifier); UINT modifier = QSingleKeySequenceEdit::toModifier(combined.modifier); RegisterHotKey(m_mainwindow, id, modifier, vk); } qDebug() << "全局快捷键已注册:"; } void PreferenceDialog::unregisterGlobalHotkeys() { for (auto it = m_shortcuts.begin(); it != m_shortcuts.end(); it++) { int id = it.key(); UnregisterHotKey(m_mainwindow, id); } qDebug() << "全局快捷键已注销"; } void PreferenceDialog::loadShortcut(int id, const QString& config, const QString& defaultValue) { m_shortcuts.insert(id, QSingleKeySequenceEdit::toQtCombinedKey( m_settings->value(config, defaultValue).toString())); } void PreferenceDialog::dump() { dumpShortcut(CONFIG_HOTKEY_SPEEDUP, ui->speedUpKeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SPEEDDOWN, ui->speedDownKeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_RESETSPEED, ui->resetSpeedKeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SHIFT1, ui->shift1KeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SHIFT2, ui->shift2KeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SHIFT3, ui->shift3KeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SHIFT4, ui->shift4KeySequenceEdit->getKeyText()); dumpShortcut(CONFIG_HOTKEY_SHIFT5, ui->shift5KeySequenceEdit->getKeyText()); m_settings->setValue(CONFIG_INCREASE_STEP, ui->increaseStepSpinBox->value()); m_settings->setValue(CONFIG_DECREASE_STEP, ui->decreaseStepSpinBox->value()); m_settings->setValue(CONFIG_SHIFT1_VALUE, ui->shift1DoubleSpinBox->value()); m_settings->setValue(CONFIG_SHIFT2_VALUE, ui->shift2DoubleSpinBox->value()); m_settings->setValue(CONFIG_SHIFT3_VALUE, ui->shift3DoubleSpinBox->value()); m_settings->setValue(CONFIG_SHIFT4_VALUE, ui->shift4DoubleSpinBox->value()); m_settings->setValue(CONFIG_SHIFT5_VALUE, ui->shift5DoubleSpinBox->value()); m_settings->sync(); } void PreferenceDialog::dumpShortcut(const QString& config, const QString& keyText) { m_settings->setValue(config, keyText); } void PreferenceDialog::updateShortcut(int id, QSingleKeySequenceEdit* keyEdit) { m_shortcuts[id] = keyEdit->getQtCombinedKey(); } void PreferenceDialog::update() { updateShortcut(HOTKEY_INCREASE_SPEED, ui->speedUpKeySequenceEdit); updateShortcut(HOTKEY_DECREASE_SPEED, ui->speedDownKeySequenceEdit); updateShortcut(HOTKEY_RESET_SPEED, ui->resetSpeedKeySequenceEdit); updateShortcut(HOTKEY_SHIFT1, ui->shift1KeySequenceEdit); updateShortcut(HOTKEY_SHIFT2, ui->shift2KeySequenceEdit); updateShortcut(HOTKEY_SHIFT3, ui->shift3KeySequenceEdit); updateShortcut(HOTKEY_SHIFT4, ui->shift4KeySequenceEdit); updateShortcut(HOTKEY_SHIFT5, ui->shift5KeySequenceEdit); m_increaseStep = ui->increaseStepSpinBox->value(); m_decreaseStep = ui->decreaseStepSpinBox->value(); m_shift1Value = ui->shift1DoubleSpinBox->value(); m_shift2Value = ui->shift2DoubleSpinBox->value(); m_shift3Value = ui->shift3DoubleSpinBox->value(); m_shift4Value = ui->shift4DoubleSpinBox->value(); m_shift5Value = ui->shift5DoubleSpinBox->value(); } void PreferenceDialog::redrawSpinBox(QSpinBox* spinbox, int value) { spinbox->setValue(value); } void PreferenceDialog::redrawSpinBox(QDoubleSpinBox* spinbox, double value) { spinbox->setValue(value); } void PreferenceDialog::redrawKeyEdit(QSingleKeySequenceEdit* keyEdit, int id) { QtCombinedKey combinedKey = m_shortcuts[id]; keyEdit->setKeySequence(combinedKey.key | combinedKey.modifier); } void PreferenceDialog::redraw() { redrawKeyEdit(ui->speedUpKeySequenceEdit, HOTKEY_INCREASE_SPEED); redrawKeyEdit(ui->speedDownKeySequenceEdit, HOTKEY_DECREASE_SPEED); redrawKeyEdit(ui->resetSpeedKeySequenceEdit, HOTKEY_RESET_SPEED); redrawKeyEdit(ui->shift1KeySequenceEdit, HOTKEY_SHIFT1); redrawKeyEdit(ui->shift2KeySequenceEdit, HOTKEY_SHIFT2); redrawKeyEdit(ui->shift3KeySequenceEdit, HOTKEY_SHIFT3); redrawKeyEdit(ui->shift4KeySequenceEdit, HOTKEY_SHIFT4); redrawKeyEdit(ui->shift5KeySequenceEdit, HOTKEY_SHIFT5); redrawSpinBox(ui->increaseStepSpinBox, m_increaseStep); redrawSpinBox(ui->decreaseStepSpinBox, m_decreaseStep); redrawSpinBox(ui->shift1DoubleSpinBox, m_shift1Value); redrawSpinBox(ui->shift2DoubleSpinBox, m_shift2Value); redrawSpinBox(ui->shift3DoubleSpinBox, m_shift3Value); redrawSpinBox(ui->shift4DoubleSpinBox, m_shift4Value); redrawSpinBox(ui->shift5DoubleSpinBox, m_shift5Value); m_increaseSpeedLabel->setText( QString(tr("%1 增加速度")) .arg(QSingleKeySequenceEdit::wrapText( ui->speedUpKeySequenceEdit->getKeyText()))); m_decreaseSpeedLabel->setText( QString(tr("%1 减少速度")) .arg(QSingleKeySequenceEdit::wrapText( ui->speedDownKeySequenceEdit->getKeyText()))); m_resetSpeedLabel->setText( QString(tr("%1 重置速度")) .arg(QSingleKeySequenceEdit::wrapText( ui->resetSpeedKeySequenceEdit->getKeyText()))); adjustSize(); } void PreferenceDialog::on_buttonBox_accepted() { update(); setupGlobalHotkeys(); redraw(); dump(); } void PreferenceDialog::on_buttonBox_rejected() { redraw(); setupGlobalHotkeys(); } void PreferenceDialog::recreate() { layout()->invalidate(); layout()->activate(); adjustSize(); } ================================================ FILE: preferencedialog.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef PREFERENCEDIALOG_H #define PREFERENCEDIALOG_H #include #include "config.h" #include "qsinglekeysequenceedit.h" #include #include #include #include #include #include namespace Ui { class PreferenceDialog; } #define CONFIG_HOTKEY_SPEEDUP "Hotkey/SpeedUp" #define CONFIG_HOTKEY_SPEEDDOWN "Hotkey/SpeedDown" #define CONFIG_HOTKEY_RESETSPEED "Hotkey/ResetSpeed" #define CONFIG_HOTKEY_SHIFT1 "Hotkey/Shift1" #define CONFIG_HOTKEY_SHIFT2 "Hotkey/Shift2" #define CONFIG_HOTKEY_SHIFT3 "Hotkey/Shift3" #define CONFIG_HOTKEY_SHIFT4 "Hotkey/Shift4" #define CONFIG_HOTKEY_SHIFT5 "Hotkey/Shift5" #define CONFIG_SHIFT1_VALUE "Shift/Shift1Value" #define CONFIG_SHIFT2_VALUE "Shift/Shift2Value" #define CONFIG_SHIFT3_VALUE "Shift/Shift3Value" #define CONFIG_SHIFT4_VALUE "Shift/Shift4Value" #define CONFIG_SHIFT5_VALUE "Shift/Shift5Value" #define CONFIG_INCREASE_STEP "Shift/IncreaseStep" #define CONFIG_DECREASE_STEP "Shift/DecreaseStep" #define DEFAULT_SHIFT1_VALUE 10.0 #define DEFAULT_SHIFT2_VALUE 20.0 #define DEFAULT_SHIFT3_VALUE 30.0 #define DEFAULT_SHIFT4_VALUE 40.0 #define DEFAULT_SHIFT5_VALUE 50.0 #define DEFAULT_INCREASE_STEP 1 #define DEFAULT_DECREASE_STEP 1 #define DEFAULT_HOTKEY_SPEEDUP "Ctrl+Alt+Up" #define DEFAULT_HOTKEY_SPEEDDOWN "Ctrl+Alt+Down" #define DEFAULT_HOTKEY_RERSETSPEED "Ctrl+Alt+0" #define DEFAULT_HOTKEY_SHIFT1 "Ctrl+Alt+1" #define DEFAULT_HOTKEY_SHIFT2 "Ctrl+Alt+2" #define DEFAULT_HOTKEY_SHIFT3 "Ctrl+Alt+3" #define DEFAULT_HOTKEY_SHIFT4 "Ctrl+Alt+4" #define DEFAULT_HOTKEY_SHIFT5 "Ctrl+Alt+5" class PreferenceDialog : public QDialog { Q_OBJECT public: explicit PreferenceDialog(HWND hMainWindow, QSettings* settings, QLabel* increaseSpeedLabel, QLabel* decreaseSpeedLabel, QLabel* resetSpeedLabel, QWidget* parent = nullptr); ~PreferenceDialog(); int getIncreaseStep(); int getDecreaseStep(); double getShift1(); double getShift2(); double getShift3(); double getShift4(); double getShift5(); public slots: void show(); private slots: void on_buttonBox_accepted(); void on_buttonBox_rejected(); void recreate(); private: void setupGlobalHotkeys(); void unregisterGlobalHotkeys(); void loadShortcut(int id, const QString& config, const QString& defaultValue); void dumpShortcut(const QString& config, const QString& keyText); void dump(); void updateShortcut(int id, QSingleKeySequenceEdit* keyEdit); void update(); void redrawSpinBox(QSpinBox* spinbox, int value); void redrawSpinBox(QDoubleSpinBox* spinbox, double value); void redrawKeyEdit(QSingleKeySequenceEdit* keyEdit, int id); void redraw(); Ui::PreferenceDialog* ui; QSettings* m_settings; QLabel* m_increaseSpeedLabel; QLabel* m_decreaseSpeedLabel; QLabel* m_resetSpeedLabel; QMap m_shortcuts; double m_shift1Value; double m_shift2Value; double m_shift3Value; double m_shift4Value; double m_shift5Value; int m_increaseStep; int m_decreaseStep; HWND m_mainwindow; }; #endif // PREFERENCEDIALOG_H ================================================ FILE: preferencedialog.ui ================================================ PreferenceDialog 0 0 355 375 0 0 快捷键 false true QLayout::SetFixedSize 微软雅黑 档位3 微软雅黑 速度 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter Ctrl+Alt+1 微软雅黑 减少速度 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 微软雅黑 按键 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter Qt::Horizontal 0.010000000000000 1000.000000000000000 50.000000000000000 Ctrl+Alt+5 微软雅黑 档位5 Ctrl+Alt+3 微软雅黑 Qt::LeftToRight Qt::Horizontal QDialogButtonBox::Cancel|QDialogButtonBox::Ok 微软雅黑 档位1 Ctrl+Alt+0 微软雅黑 重置速度 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter Ctrl+Alt+Up Ctrl+Alt+4 0.010000000000000 1000.000000000000000 30.000000000000000 微软雅黑 档位2 Ctrl+Alt+2 Ctrl+Alt+Down 0.010000000000000 1000.000000000000000 20.000000000000000 微软雅黑 增加速度 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 0.010000000000000 1000.000000000000000 QAbstractSpinBox::DefaultStepType 10.000000000000000 微软雅黑 档位4 0.010000000000000 1000.000000000000000 40.000000000000000 微软雅黑 按键 Qt::AlignLeading|Qt::AlignLeft|Qt::AlignVCenter 1 1000 1 1000 步幅 QSingleKeySequenceEdit QKeySequenceEdit
qsinglekeysequenceedit.h
speedUpKeySequenceEdit increaseStepSpinBox speedDownKeySequenceEdit decreaseStepSpinBox resetSpeedKeySequenceEdit shift1KeySequenceEdit shift1DoubleSpinBox shift2KeySequenceEdit shift2DoubleSpinBox shift3KeySequenceEdit shift3DoubleSpinBox shift4KeySequenceEdit shift4DoubleSpinBox shift5KeySequenceEdit shift5DoubleSpinBox buttonBox accepted() PreferenceDialog accept() 248 254 157 274 buttonBox rejected() PreferenceDialog reject() 316 260 286 274
================================================ FILE: processmonitor.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "config.h" #include "processmonitor.h" #include #include #include #include #include #include #include #include #include #include #include ProcessMonitor::ProcessMonitor(QSettings* settings, QTreeWidget* treeWidget, QLabel* treeStatusLabel, QLabel* injector32StatusLabel, QLabel* injector64StatusLabel, QObject* parent) : m_treeWidget(treeWidget) , m_treeStatusLabel(treeStatusLabel) , m_injector32StatusLabel(injector32StatusLabel) , m_injector64StatusLabel(injector64StatusLabel) , m_settings(settings) { m_treeWidget->header()->setMinimumHeight(40); m_treeWidget->setColumnWidth(0, 300); m_treeWidget->setColumnWidth(5, 50); m_treeWidget->setUniformRowHeights(true); m_treeWidget->sortByColumn(0, Qt::AscendingOrder); m_treeWidget->resizeColumnToContents(2); m_treeWidget->resizeColumnToContents(3); connect(m_treeWidget, &QTreeWidget::itemChanged, this, &ProcessMonitor::onItemChanged); this->startBridge32(); this->startBridge64(); init(); refresh(); } ProcessMonitor::~ProcessMonitor() { this->terminalBridge(); delete m_bridge32; delete m_bridge64; } void ProcessMonitor::setFilter(QString processName) { m_filter = processName.toLower(); } void ProcessMonitor::refresh() { healthcheckBridge(); QList processList = winutils::getProcessList(); if (m_filter == "") { update(processList); m_treeStatusLabel->setText(QString(tr("搜索到%1个进程, 已过滤展示%2个")) .arg(processList.size()) .arg(processList.size())); } else { QList filtered; for (ProcessInfo info : processList) { if (info.name.toLower().contains(m_filter)) filtered.append(info); } update(filtered); m_treeStatusLabel->setText(QString(tr("搜索到%1个进程, 已过滤展示%2个")) .arg(processList.size()) .arg(filtered.size())); } } void ProcessMonitor::start() { m_timer = new QTimer(this); connect(m_timer, &QTimer::timeout, this, &ProcessMonitor::refresh); m_timer->start(1000); } void ProcessMonitor::onItemChanged(QTreeWidgetItem* item, int column) { if (column == 5 && (item->flags() & Qt::ItemIsUserCheckable)) { bool state = m_treeWidget->blockSignals(true); Qt::CheckState checkState = item->checkState(column); QString processName = item->text(0); DWORD pid = item->text(1).toLong(); bool is64Bit = item->text(3) == "x64" ? true : false; if (checkState == Qt::Checked) { m_targetNames.insert(processName); this->injectDll(pid, is64Bit); item->setText(5, tr("加速中")); for (int col = 0; col < item->columnCount(); ++col) { item->setBackground(col, QBrush(QColor("#f3e5f5"))); item->setForeground(col, QBrush(QColor("#7b1fa2"))); } qDebug() << processName << "勾选"; dump(); } else { m_targetNames.remove(processName); this->unhookDll(pid, is64Bit); item->setText(5, ""); for (int col = 0; col < item->columnCount(); ++col) { item->setBackground(col, QBrush()); item->setForeground(col, QBrush()); } qDebug() << processName << "取消勾选"; dump(); } m_treeWidget->blockSignals(state); } } void ProcessMonitor::init() { QStringList targetNames = m_settings->value(CONFIG_TARGETNAMES_KEY).toStringList(); m_targetNames = QSet(targetNames.begin(), targetNames.end()); } void ProcessMonitor::dump() { m_settings->setValue(CONFIG_TARGETNAMES_KEY, QStringList(m_targetNames.values())); } void ProcessMonitor::update(const QList& processList) { // 跟踪现有进程,用于确定哪些已终止 QSet currentPids; for (const ProcessInfo& info : processList) { currentPids.insert(info.pid); } // 移除已终止的进程 QMutableMapIterator i(m_processItems); while (i.hasNext()) { i.next(); if (!currentPids.contains(i.key())) { QTreeWidgetItem* item = i.value(); QTreeWidgetItem* parent = item->parent(); if (parent) { parent->removeChild(item); } else { auto index = m_treeWidget->indexOfTopLevelItem(item); m_treeWidget->takeTopLevelItem(index); } while (item->childCount() > 0) { QTreeWidgetItem* child = item->takeChild(0); if (parent) { parent->addChild(child); } else { m_treeWidget->addTopLevelItem(child); } } // 删除节点 delete item; // 从映射中移除 i.remove(); } } // 添加或更新进程信息 for (const ProcessInfo& info : processList) { if (m_processItems.contains(info.pid)) { // 更新已存在的进程信息 QTreeWidgetItem* item = m_processItems[info.pid]; item->setText(1, QString::number(info.pid)); item->setData(1, Qt::UserRole, (long long)info.pid); item->setText(2, QString("%1 MB").arg(info.memoryUsage / 1024 / 1024)); item->setData(2, Qt::UserRole, (uint)info.memoryUsage); QString arch = info.is64Bit ? "x64" : "x86"; item->setText(3, arch); QString priority; switch (info.priorityClass) { case HIGH_PRIORITY_CLASS: priority = tr("高"); break; case NORMAL_PRIORITY_CLASS: priority = tr("中"); break; case IDLE_PRIORITY_CLASS: priority = tr("低"); break; case REALTIME_PRIORITY_CLASS: priority = tr("实时"); break; default: priority = tr("未知"); break; } item->setText(4, priority); if (m_targetNames.contains(info.name)) { if (item->checkState(5) == Qt::Unchecked) { item->setCheckState(5, Qt::Checked); } } else { if (item->checkState(5) == Qt::Checked) { item->setCheckState(5, Qt::Unchecked); } } } else { // 添加新进程 QTreeWidgetItem* item = new SortTreeWidgetItem(); item->setText(0, info.name); item->setData(0, Qt::UserRole, info.name.toLower()); item->setText(1, QString::number(info.pid)); item->setData(1, Qt::UserRole, (long long)info.pid); item->setText(2, QString("%1 MB").arg(info.memoryUsage / 1024 / 1024)); item->setData(2, Qt::UserRole, (uint)info.memoryUsage); QString arch = info.is64Bit ? "x64" : "x86"; item->setText(3, arch); // 加载进程图标 item->setIcon(0, getProcessIconCached(info.pid)); QString priority; switch (info.priorityClass) { case HIGH_PRIORITY_CLASS: priority = tr("高"); break; case NORMAL_PRIORITY_CLASS: priority = tr("中"); break; case IDLE_PRIORITY_CLASS: priority = tr("低"); break; case REALTIME_PRIORITY_CLASS: priority = tr("实时"); break; default: priority = tr("未知"); break; } item->setText(4, priority); item->setCheckState(5, Qt::Unchecked); m_treeWidget->addTopLevelItem(item); m_processItems[info.pid] = item; } } } void ProcessMonitor::injectDll(DWORD processId, bool is64Bit) { QString cmd = QString("inject %1\n").arg(processId); if (!is64Bit) { m_bridge32->write(cmd.toUtf8(), cmd.size()); m_bridge32->waitForBytesWritten(); } else { m_bridge64->write(cmd.toUtf8(), cmd.size()); m_bridge64->waitForBytesWritten(); } } void ProcessMonitor::unhookDll(DWORD processId, bool is64Bit) { QString cmd = QString("unhook %1\n").arg(processId); if (!is64Bit) { m_bridge32->write(cmd.toUtf8(), cmd.size()); m_bridge32->waitForBytesWritten(); } else { m_bridge64->write(cmd.toUtf8(), cmd.size()); m_bridge64->waitForBytesWritten(); } } void ProcessMonitor::startBridge32() { m_bridge32 = new QProcess(); QStringList params32; m_bridge32->start(BRIDGE32_EXE, params32); if (!m_bridge32->waitForStarted()) { QMessageBox::critical(nullptr, tr("启动失败"), tr("32位桥接子进程启动失败,请确保Speedy.exe和bridge32.exe在同一目录下"), QMessageBox::Ok); qDebug() << "32位桥接子进程启动失败"; } else { qDebug() << "32位桥接子进程已启动"; } m_bridge32->setProcessChannelMode(QProcess::MergedChannels); connect(m_bridge32, &QProcess::readyReadStandardOutput, [&]() { QByteArray data = m_bridge32->readAllStandardOutput(); qDebug() << "收到输出:" << QString(data).trimmed(); }); } void ProcessMonitor::startBridge64() { m_bridge64 = new QProcess(); QStringList params64; m_bridge64->start(BRIDGE64_EXE, params64); if (!m_bridge64->waitForStarted()) { QMessageBox::critical(nullptr, tr("启动失败"), tr("64位桥接子进程启动失败,请确保Speedy.exe和bridge64.exe在同一目录下"), QMessageBox::Ok); qDebug() << "64位桥接子进程启动失败"; } else { qDebug() << "64位桥接子进程已启动"; } m_bridge64->setProcessChannelMode(QProcess::MergedChannels); connect(m_bridge64, &QProcess::readyReadStandardOutput, [&]() { QByteArray data = m_bridge64->readAllStandardOutput(); qDebug() << "收到输出:" << QString(data).trimmed(); }); } void ProcessMonitor::healthcheckBridge() { // 获取当前主题下的高亮文本颜色 QColor highlightColor = QApplication::palette().color(QPalette::Highlight); // 如果是深色模式,使用亮绿色;如果是浅色模式,使用深绿色 QString greenColorStr = (QApplication::palette().color(QPalette::Window).value() < 128) ? "lightgreen" : "green"; if (this->m_bridge32->state() == QProcess::Running) { m_injector32StatusLabel->setStyleSheet(QString("color: %1").arg(greenColorStr)); m_injector32StatusLabel->setText(tr("正常")); } else { m_injector32StatusLabel->setStyleSheet("color: red"); m_injector32StatusLabel->setText(tr("异常退出")); } if (this->m_bridge64->state() == QProcess::Running) { m_injector64StatusLabel->setStyleSheet(QString("color: %1").arg(greenColorStr)); m_injector64StatusLabel->setText(tr("正常")); } else { m_injector64StatusLabel->setStyleSheet("color:red"); m_injector64StatusLabel->setText(tr("异常退出")); } } void ProcessMonitor::terminalBridge() { QString cmd = QString("exit\n"); m_bridge32->write(cmd.toUtf8(), cmd.size()); m_bridge32->waitForBytesWritten(); m_bridge64->write(cmd.toUtf8(), cmd.size()); m_bridge64->waitForBytesWritten(); } void ProcessMonitor::changeSpeed(double factor) { QString cmd = QString("change %1\n").arg(factor); m_bridge32->write(cmd.toUtf8(), cmd.size()); m_bridge32->waitForBytesWritten(); m_bridge64->write(cmd.toUtf8(), cmd.size()); m_bridge64->waitForBytesWritten(); } QIcon ProcessMonitor::getProcessIconCached(DWORD processId) { QString processPath = winutils::getProcessPath(processId); if (m_iconCache.contains(processPath)) { return m_iconCache[processPath]; } QIcon icon = getProcessIcon(processPath); m_iconCache.insert(processPath, icon); return icon; } QIcon ProcessMonitor::getDefaultIcon(const QString& processName) { // 根据进程名称或类型提供更有针对性的默认图标 if (processName != "") { // 使用SHGetFileInfo获取.exe文件的图标 SHFILEINFO sfi = {}; QIcon icon; if (SHGetFileInfo(reinterpret_cast(processName.utf16()), FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON)) { // 将HICON转换为QIcon icon = QtWin::fromHICON(sfi.hIcon); // 释放图标资源 DestroyIcon(sfi.hIcon); } return icon; } else { // 使用SHGetFileInfo获取.exe文件的图标 SHFILEINFO sfi = {}; QIcon icon; if (SHGetFileInfo(reinterpret_cast(L".exe"), FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_USEFILEATTRIBUTES | SHGFI_ICON | SHGFI_SMALLICON)) { // 将HICON转换为QIcon icon = QtWin::fromHICON(sfi.hIcon); // 释放图标资源 DestroyIcon(sfi.hIcon); } return icon; } } QIcon ProcessMonitor::getProcessIcon(QString processPath) { int lastSlashPos = std::max(processPath.lastIndexOf('/'), processPath.lastIndexOf('\\')); QString processName; if (lastSlashPos == -1) { processName = processPath; } processName = processPath.mid(lastSlashPos + 1); if (processPath.isEmpty()) { qDebug() << processPath << "无法获取进程完整路径"; return getDefaultIcon(processName); } SHFILEINFO sfi = {}; if (SHGetFileInfo(reinterpret_cast(processPath.utf16()), FILE_ATTRIBUTE_NORMAL, &sfi, sizeof(SHFILEINFO), SHGFI_ICON | SHGFI_LARGEICON | SHGFI_USEFILEATTRIBUTES)) { if (sfi.hIcon) { QIcon icon = QtWin::fromHICON(sfi.hIcon); DestroyIcon(sfi.hIcon); if (!icon.isNull()) { qDebug() << processPath << "通过SHGetFileInfo获取图标成功"; return icon; } } } HICON hIcon = ExtractIconW(nullptr, reinterpret_cast(processPath.utf16()), 0); if (hIcon) { QIcon icon = QtWin::fromHICON(hIcon); DestroyIcon(hIcon); if (!icon.isNull()) return icon; } QFileInfo fileInfo(processPath); if (fileInfo.exists()) { // 使用Qt的QFileIconProvider获取文件图标 QFileIconProvider iconProvider; return iconProvider.icon(fileInfo); } qDebug() << processPath << "无法获取进程图标使用默认图标"; return getDefaultIcon(processName); } ================================================ FILE: processmonitor.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef PROCESSMONITOR_H #define PROCESSMONITOR_H #include #include "winutils.h" #include #include #include #include #include #include #include #include #include #define CONFIG_TARGETNAMES_KEY "ProcessMonitor/TargetNames" class ProcessMonitor : public QObject { Q_OBJECT public: explicit ProcessMonitor(QSettings* settings, QTreeWidget* treeWidget, QLabel* treeStatusLabel, QLabel* injector32StatusLabel, QLabel* injector64StatusLabel, QObject* parent = nullptr); ~ProcessMonitor(); // 设置刷新间隔(毫秒) void setInterval(int msec); // 设置过滤 void setFilter(QString processName); void changeSpeed(double factor); public slots: // 定时刷新槽函数 void refresh(); void start(); private slots: void onItemChanged(QTreeWidgetItem* item, int column); private: QTreeWidget* m_treeWidget; QLabel* m_treeStatusLabel; QLabel* m_injector32StatusLabel; QLabel* m_injector64StatusLabel; QString m_filter; QTimer* m_timer = nullptr; QString m_dllPath; QProcess* m_bridge32; QProcess* m_bridge64; QSettings* m_settings; // 图标缓存 QHash m_iconCache; // 存储进程ID到TreeWidgetItem的映射 QMap m_processItems; // 存储需要加速的进程 QSet m_targetNames; void init(); void dump(); void update(const QList& processList); void injectDll(DWORD processId, bool is64Bit); void unhookDll(DWORD processId, bool is64Bit); void startBridge32(); void startBridge64(); void healthcheckBridge(); void terminalBridge(); // 获取进程图标 static QIcon getProcessIcon(QString processPath); static QIcon getDefaultIcon(const QString& processName); QIcon getProcessIconCached(DWORD proccessId); }; class SortTreeWidgetItem : public QTreeWidgetItem { public: SortTreeWidgetItem(QTreeWidget* parent = nullptr) : QTreeWidgetItem(parent) { } bool operator<(const QTreeWidgetItem& other) const override { int column = treeWidget()->sortColumn(); QVariant ldata = this->data(column, Qt::UserRole); QVariant rdata = other.data(column, Qt::UserRole); if (ldata.isValid() && rdata.isValid()) { if (ldata.type() == QVariant::UInt && rdata.type() == QVariant::UInt) { return ldata.toUInt() < rdata.toUInt(); } else { return ldata.toString() < rdata.toString(); } } else { QString ltext = this->text(column); QString rtext = other.text(column); return ltext < rtext; } } bool operator>(const QTreeWidgetItem& other) const { int column = treeWidget()->sortColumn(); QVariant ldata = this->data(column, Qt::UserRole); QVariant rdata = other.data(column, Qt::UserRole); if (ldata.isValid() && rdata.isValid()) { if (ldata.type() == QVariant::UInt && rdata.type() == QVariant::UInt) { return ldata.toUInt() > rdata.toUInt(); } else { return ldata.toString() > rdata.toString(); } } else { QString ltext = this->text(column); QString rtext = other.text(column); return ltext > rtext; } } }; #endif // PROCESSMONITOR_H ================================================ FILE: qsinglekeysequenceedit.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "qsinglekeysequenceedit.h" #include QSingleKeySequenceEdit::QSingleKeySequenceEdit(QWidget* parent) : QKeySequenceEdit(parent) { setStyleSheet(":focus {" " border: 2px solid #3498db;" " background-color: #ebf3fd;" " font-weight: bold;" " outline: none;" "}"); connect(this, &QKeySequenceEdit::keySequenceChanged, this, &QSingleKeySequenceEdit::update); } UINT QSingleKeySequenceEdit::getVK() { return toVK(m_key, m_modifier); } UINT QSingleKeySequenceEdit::getModifier() { return toModifier(m_modifier); } QtCombinedKey QSingleKeySequenceEdit::getQtCombinedKey() { return QtCombinedKey{ m_key, m_modifier }; } QString QSingleKeySequenceEdit::getKeyText() { return keySequence().toString(QKeySequence::NativeText); } void QSingleKeySequenceEdit::keyPressEvent(QKeyEvent* event) { int key = event->key(); Qt::KeyboardModifiers modifiers = event->modifiers(); // 忽略单独的修饰键 if (isModifierKey(key)) { return; } m_key = key; m_modifier = modifiers; // 创建单个按键序列 QKeySequence singleKey(key | modifiers); setKeySequence(singleKey); // 🔚 结束编辑 emit editingFinished(); clearFocus(); } void QSingleKeySequenceEdit::update() { QKeySequence sequence = keySequence(); if (sequence.isEmpty()) { m_key = 0; m_modifier = Qt::NoModifier; } else { int combinedKey = sequence[0]; m_modifier = Qt::KeyboardModifiers(combinedKey & Qt::KeyboardModifierMask); m_key = combinedKey & ~Qt::KeyboardModifierMask; } } bool QSingleKeySequenceEdit::isModifierKey(int key) const { return (key == Qt::Key_Control || key == Qt::Key_Alt || key == Qt::Key_Shift || key == Qt::Key_Meta); } UINT QSingleKeySequenceEdit::toVK(int qtKey, Qt::KeyboardModifiers qtMod) { // 🔤 字母键 A-Z if (qtKey >= Qt::Key_A && qtKey <= Qt::Key_Z) { return qtKey; // Qt 和 Windows 的 A-Z 键码相同 } // 🔢 小键盘 0-9 if (qtMod & Qt::KeypadModifier) { switch (qtKey) { // 数字键盘 case Qt::Key_0: return VK_NUMPAD0; case Qt::Key_1: return VK_NUMPAD1; case Qt::Key_2: return VK_NUMPAD2; case Qt::Key_3: return VK_NUMPAD3; case Qt::Key_4: return VK_NUMPAD4; case Qt::Key_5: return VK_NUMPAD5; case Qt::Key_6: return VK_NUMPAD6; case Qt::Key_7: return VK_NUMPAD7; case Qt::Key_8: return VK_NUMPAD8; case Qt::Key_9: return VK_NUMPAD9; } } // 🔢 数字键 0-9 if (qtKey >= Qt::Key_0 && qtKey <= Qt::Key_9) { return qtKey; // Qt 和 Windows 的 0-9 键码相同 } // 🎯 功能键映射 switch (qtKey) { // F1-F12 case Qt::Key_F1: return VK_F1; case Qt::Key_F2: return VK_F2; case Qt::Key_F3: return VK_F3; case Qt::Key_F4: return VK_F4; case Qt::Key_F5: return VK_F5; case Qt::Key_F6: return VK_F6; case Qt::Key_F7: return VK_F7; case Qt::Key_F8: return VK_F8; case Qt::Key_F9: return VK_F9; case Qt::Key_F10: return VK_F10; case Qt::Key_F11: return VK_F11; case Qt::Key_F12: return VK_F12; // 方向键 case Qt::Key_Left: return VK_LEFT; case Qt::Key_Right: return VK_RIGHT; case Qt::Key_Up: return VK_UP; case Qt::Key_Down: return VK_DOWN; // 特殊键 case Qt::Key_Enter: case Qt::Key_Return: return VK_RETURN; case Qt::Key_Escape: return VK_ESCAPE; case Qt::Key_Tab: return VK_TAB; case Qt::Key_Backspace: return VK_BACK; case Qt::Key_Delete: return VK_DELETE; case Qt::Key_Insert: return VK_INSERT; case Qt::Key_Home: return VK_HOME; case Qt::Key_End: return VK_END; case Qt::Key_PageUp: return VK_PRIOR; case Qt::Key_PageDown: return VK_NEXT; case Qt::Key_Space: return VK_SPACE; // 符号键 case Qt::Key_Semicolon: return VK_OEM_1; // ; case Qt::Key_Equal: return VK_OEM_PLUS; // = case Qt::Key_Comma: return VK_OEM_COMMA; // , case Qt::Key_Minus: return VK_OEM_MINUS; // - case Qt::Key_Period: return VK_OEM_PERIOD; // . case Qt::Key_Slash: return VK_OEM_2; // / case Qt::Key_QuoteLeft: return VK_OEM_3; // ` case Qt::Key_BracketLeft: return VK_OEM_4; // [ case Qt::Key_Backslash: return VK_OEM_5; // case Qt::Key_BracketRight: return VK_OEM_6; // ] case Qt::Key_Apostrophe: return VK_OEM_7; // ' // 其他常用键 case Qt::Key_CapsLock: return VK_CAPITAL; case Qt::Key_NumLock: return VK_NUMLOCK; case Qt::Key_ScrollLock: return VK_SCROLL; case Qt::Key_Pause: return VK_PAUSE; case Qt::Key_Print: return VK_PRINT; default: qDebug() << "Unknown Qt key:" << qtKey; return 0; // 未知按键 } } UINT QSingleKeySequenceEdit::toModifier(Qt::KeyboardModifiers qtMod) { UINT winMod = 0; if (qtMod & Qt::ControlModifier) { winMod |= MOD_CONTROL; } if (qtMod & Qt::AltModifier) { winMod |= MOD_ALT; } if (qtMod & Qt::ShiftModifier) { winMod |= MOD_SHIFT; } if (qtMod & Qt::MetaModifier) { winMod |= MOD_WIN; // Windows 键 } return winMod; } QString QSingleKeySequenceEdit::wrapText(QString keyText) { return keyText.replace("Up", "⬆️") .replace("Down", "⬇️") .replace("Left", "⬅️") .replace("Right", "➡️"); } QtCombinedKey QSingleKeySequenceEdit::toQtCombinedKey(const QString& keyText) { QKeySequence sequence = QKeySequence(keyText); if (!sequence.isEmpty()) { int combinedKey = sequence[0]; Qt::KeyboardModifiers modifier = Qt::KeyboardModifiers(combinedKey & Qt::KeyboardModifierMask); int key = combinedKey & ~Qt::KeyboardModifierMask; return QtCombinedKey{ key, modifier }; } else { return QtCombinedKey{ 0, Qt::NoModifier }; } } ================================================ FILE: qsinglekeysequenceedit.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef QSINGLEKEYSEQUENCEEDIT_H #define QSINGLEKEYSEQUENCEEDIT_H #include #include #include #include #define QKEYSEQUENCEEDIT_DEFAULT_PLACEHOLDER "点击设置热键" struct QtCombinedKey { int key; Qt::KeyboardModifiers modifier; }; class QSingleKeySequenceEdit : public QKeySequenceEdit { Q_OBJECT public: explicit QSingleKeySequenceEdit(QWidget* parent = nullptr); static UINT toVK(int qtKey, Qt::KeyboardModifiers qtMod); static UINT toModifier(Qt::KeyboardModifiers qtMod); static QtCombinedKey toQtCombinedKey(const QString& keyText); static QString wrapText(QString keyText); UINT getVK(); UINT getModifier(); QtCombinedKey getQtCombinedKey(); QString getKeyText(); protected: void keyPressEvent(QKeyEvent* event) override; private slots: void update(); private: bool isModifierKey(int key) const; int m_key; Qt::KeyboardModifiers m_modifier; }; #endif // QSINGLEKEYSEQUENCEEDIT_H ================================================ FILE: resources.qrc ================================================ images/icon.ico images/logo.png images/icon_16.ico images/icon_32.ico images/icon_64.ico translations/OpenSpeedy_en_US.qm translations/OpenSpeedy_zh_CN.qm translations/OpenSpeedy_zh_TW.qm ================================================ FILE: script/build32.bat ================================================ @echo off echo ================================= echo Build 32 bit Qt5.15 static library echo ================================= if "%VCINSTALLDIR%"=="" ( echo Initializing Visual Studio 2022 32-bit environment... call %VC_TOOLS_32BIT% ) else ( echo Visual Studio environment already initialized echo VCINSTALLDIR: %VCINSTALLDIR% ) set SCRIPT_DIR=%~dp0 set SOURCE_DIR=%SCRIPT_DIR%..\ set BUILD_DIR=%BUILD_DIR_32BIT% set QT_QMAKE_EXECUTABLE=%QT_QMAKE_EXECUTABLE_32BIT% REM 将命令执行结果存储在变量中 for /f "delims=" %%i in ('"%QT_QMAKE_EXECUTABLE%" -query QT_INSTALL_PREFIX') do set QT_INSTALL_PREFIX=%%i echo "%QT_QMAKE_EXECUTABLE%" echo "%QT_INSTALL_PREFIX%" cmake ^ -G "Ninja" ^ -DCMAKE_BUILD_TYPE=Release ^ -DQT_QMAKE_EXECUTABLE:FILEPATH="%QT_QMAKE_EXECUTABLE%" ^ -DCMAKE_PREFIX_PATH:PATH="%QT_INSTALL_PREFIX%" ^ -DCMAKE_BUILD_TYPE=Release ^ -S %SOURCE_DIR% ^ -B %BUILD_DIR% cmake --build "%BUILD_DIR%" --config Release ================================================ FILE: script/build64.bat ================================================ @echo off echo ================================= echo Build 64 bit Qt5.15 static library echo ================================= if "%VCINSTALLDIR%"=="" ( echo Initializing Visual Studio 2022 64-bit environment... call %VC_TOOLS_64BIT% ) else ( echo Visual Studio environment already initialized echo VCINSTALLDIR: %VCINSTALLDIR% ) set SCRIPT_DIR=%~dp0 set SOURCE_DIR=%SCRIPT_DIR%..\ set BUILD_DIR=%BUILD_DIR_64BIT% set QT_QMAKE_EXECUTABLE=%QT_QMAKE_EXECUTABLE_64BIT% REM 将命令执行结果存储在变量中 for /f "delims=" %%i in ('"%QT_QMAKE_EXECUTABLE%" -query QT_INSTALL_PREFIX') do set QT_INSTALL_PREFIX=%%i echo "%QT_QMAKE_EXECUTABLE%" echo "%QT_INSTALL_PREFIX%" cmake ^ -G "Ninja" ^ -DQT_QMAKE_EXECUTABLE:FILEPATH="%QT_QMAKE_EXECUTABLE%" ^ -DCMAKE_PREFIX_PATH:PATH="%QT_INSTALL_PREFIX%" ^ -DCMAKE_BUILD_TYPE=Release ^ -S %SOURCE_DIR% ^ -B %BUILD_DIR% cmake --build "%BUILD_DIR%" --config Release ================================================ FILE: script/initenv.bat ================================================ set VC_TOOLS_32BIT="D:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars32.bat" set VC_TOOLS_64BIT="D:\Program Files\Microsoft Visual Studio\2022\Community\VC\Auxiliary\Build\vcvars64.bat" set BUILD_DIR_32BIT="%~dp0..\build\CMAKE_x86_static-Release" set BUILD_DIR_64BIT="%~dp0..\build\CMAKE_x64_static-Release" set QT_QMAKE_EXECUTABLE_32BIT="E:\vcpkg-master\installed\x86-windows-static\tools\qt5\bin\qmake.exe" set QT_QMAKE_EXECUTABLE_64BIT="E:\vcpkg-master\installed\x64-windows-static\tools\qt5\bin\qmake.exe" ================================================ FILE: speedpatch/CMakeLists.txt ================================================ cmake_minimum_required(VERSION 3.16) project(speedpatch LANGUAGES CXX) set(CMAKE_AUTOUIC ON) set(CMAKE_AUTOMOC ON) set(CMAKE_AUTORCC ON) set(CMAKE_CXX_STANDARD 17) set(CMAKE_CXX_STANDARD_REQUIRED ON) set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ..) # 判断是32位还是64位 if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(SUFFIX "64") elseif(CMAKE_SIZEOF_VOID_P EQUAL 4) set(SUFFIX "32") else() set(SUFFIX "") endif() # 设置目标名带后缀 set(TARGET_NAME "speedpatch${SUFFIX}") add_library(${TARGET_NAME} SHARED speedpatch.cpp speedpatch.h vcpkg.json ) target_link_libraries(${TARGET_NAME} PRIVATE minhook ) target_compile_definitions(${TARGET_NAME} PRIVATE SPEEDPATCH_LIBRARY) ================================================ FILE: speedpatch/SpeedPatch_global.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SPEEDPATCH_GLOBAL_H #define SPEEDPATCH_GLOBAL_H #endif // SPEEDPATCH_GLOBAL_H ================================================ FILE: speedpatch/speedpatch.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it * and/or modify it under the terms of the GNU General * Public License as published by the Free Software * Foundation, either version 3 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be * useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public * License along with this program. If not, see * . */ #include #include #include "Minhook.h" #include "speedpatch.h" #include #include #include #include #pragma comment(lib, "winmm.lib") #pragma data_seg("shared") static std::atomic factor = 1.0; #pragma data_seg() #pragma comment(linker, "/section:shared,RWS") static std::shared_mutex mutex; static std::atomic pre_factor = 1.0; static HANDLE hShare; static bool* pEnable; typedef VOID (WINAPI* SLEEP) (DWORD); typedef DWORD (WINAPI* SLEEPEX) (DWORD, BOOL); typedef UINT_PTR (WINAPI* SETTIMER) ( HWND, UINT_PTR, UINT, TIMERPROC ); typedef DWORD (WINAPI* TIMEGETTIME) (VOID); typedef MMRESULT (WINAPI* TIMESETEVENT) ( UINT, UINT, LPTIMECALLBACK, DWORD_PTR, UINT ); typedef LONG (WINAPI* GETMESSAGETIME) (VOID); typedef DWORD (WINAPI* GETTICKCOUNT) (VOID); typedef ULONGLONG (WINAPI* GETTICKCOUNT64) (VOID); typedef BOOL (WINAPI* QUERYPERFORMANCECOUNTER) (LARGE_INTEGER*); typedef BOOL (WINAPI* QUERYPERFORMANCEFREQUENCY) (LARGE_INTEGER*); typedef VOID (WINAPI* GETSYSTEMTIMEASFILETIME) (LPFILETIME); typedef VOID (WINAPI* GETSYSTEMTIMEPRECISEASFILETIME) (LPFILETIME); typedef BOOL (WINAPI* SETWAITABLETIMEREX) ( HANDLE, const LARGE_INTEGER*, LONG, PTIMERAPCROUTINE, LPVOID, PREASON_CONTEXT, ULONG); inline VOID shouldUpdateAll(); static SLEEP pfnKernelSleep = NULL; static SLEEP pfnDetourSleep = NULL; static SLEEPEX pfnKernelSleepEx = NULL; static SLEEPEX pfnDetourSleepEx = NULL; static SETTIMER pfnKernelSetTimer = NULL; static SETTIMER pfnDetourSetTimer = NULL; static TIMEGETTIME pfnKernelTimeGetTime = NULL; static TIMEGETTIME pfnDetourTimeGetTime = NULL; static TIMESETEVENT pfnKernelTimeSetEvent = NULL; static TIMESETEVENT pfnDetourTimeSetEvent = NULL; static GETMESSAGETIME pfnKernelGetMessageTime = NULL; static GETMESSAGETIME pfnDetourGetMessageTime = NULL; static GETTICKCOUNT pfnKernelGetTickCount = NULL; static GETTICKCOUNT pfnDetourGetTickCount = NULL; static GETTICKCOUNT64 pfnKernelGetTickCount64 = NULL; static GETTICKCOUNT64 pfnDetourGetTickCount64 = NULL; static QUERYPERFORMANCECOUNTER pfnKernelQueryPerformanceCounter = NULL; static QUERYPERFORMANCECOUNTER pfnDetourQueryPerformanceCounter = NULL; static QUERYPERFORMANCEFREQUENCY pfnKernelQueryPerformanceFrequency = NULL; static QUERYPERFORMANCEFREQUENCY pfnDetourQueryPerformanceFrequency = NULL; static GETSYSTEMTIMEASFILETIME pfnKernelGetSystemTimeAsFileTime = NULL; static GETSYSTEMTIMEASFILETIME pfnDetourGetSystemTimeAsFileTime = NULL; static GETSYSTEMTIMEPRECISEASFILETIME pfnKernelGetSystemTimePreciseAsFileTime = NULL; static GETSYSTEMTIMEPRECISEASFILETIME pfnDetourGetSystemTimePreciseAsFileTime = NULL; static SETWAITABLETIMEREX pfnKernelSetWaitableTimerEx = NULL; static SETWAITABLETIMEREX pfnDetourSetWaitableTimerEx = NULL; SPEEDPATCH_API void ChangeSpeed(double factor_) { factor.store(factor_); } void Init() { DWORD processId = GetCurrentProcessId(); std::wstring filemapName = GetProcessFileMapName(processId); hShare = CreateFileMapping( INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof (bool), filemapName.c_str() ); if (hShare == NULL) { return; } pEnable = (bool*) MapViewOfFile( hShare, FILE_MAP_ALL_ACCESS, 0, 0, sizeof (bool) ); *pEnable = true; } void Clean() { if (hShare != NULL) { UnmapViewOfFile(pEnable); CloseHandle(hShare); } } BOOL GetStatus() { return *pEnable; } void SetProcessStatus(DWORD processId, BOOL status) { std::wstring filemapName = GetProcessFileMapName(processId); HANDLE hShare_ = OpenFileMapping(FILE_MAP_ALL_ACCESS, FALSE, filemapName.c_str() ); if (hShare_ == NULL) { return; } bool* pStatus = (bool*) MapViewOfFile(hShare_, FILE_MAP_ALL_ACCESS, 0, 0, sizeof (bool)); *pStatus = status; UnmapViewOfFile(pStatus); CloseHandle(hShare_); } std::wstring GetCurrentProcessName() { wchar_t processPath[MAX_PATH]; GetModuleFileName(NULL, processPath, MAX_PATH); std::wstring fullPath(processPath); size_t lastSlash = fullPath.find_last_of(L"\\"); if (lastSlash != std::wstring::npos) { fullPath = fullPath.substr(lastSlash + 1); } return fullPath; } std::wstring GetProcessFileMapName(DWORD processId) { std::wstringstream wss; wss << L"OpenSpeedy." << processId; return wss.str(); } double SpeedFactor() { if (GetStatus()) { return factor.load(); } else { return 1.0; } } VOID WINAPI DetourSleep(DWORD dwMilliseconds) { std::shared_lock lock(mutex); pfnKernelSleep(dwMilliseconds / SpeedFactor()); } DWORD WINAPI DetourSleepEx(DWORD dwMilliseconds, BOOL bAlertable) { std::shared_lock lock(mutex); return pfnKernelSleepEx(dwMilliseconds / SpeedFactor(), bAlertable); } UINT_PTR WINAPI DetourSetTimer(HWND hWnd, UINT_PTR nIDEvent, UINT uElapse, TIMERPROC lpTimerFunc) { std::shared_lock lock(mutex); return pfnKernelSetTimer( hWnd, nIDEvent, uElapse / SpeedFactor(), lpTimerFunc ); } static DWORD baselineKernelTimeGetTime = 0; static DWORD baselineDetourTimeGetTime = 0; static DWORD prevcallKernelTimeGetTime = 0; static DWORD prevcallDetourTimeGetTime = 0; static std::atomic shouldUpdateTimeGetTime = false; DWORD WINAPI DetourTimeGetTime(VOID) { std::shared_lock lock(mutex); if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateTimeGetTime.compare_exchange_weak(expected, false)) { baselineKernelTimeGetTime = prevcallKernelTimeGetTime; baselineDetourTimeGetTime = prevcallDetourTimeGetTime; } DWORD now = pfnKernelTimeGetTime(); prevcallKernelTimeGetTime = now; DWORD delta = SpeedFactor() * (now - baselineKernelTimeGetTime); prevcallDetourTimeGetTime = baselineDetourTimeGetTime + delta; return baselineDetourTimeGetTime + delta; } MMRESULT WINAPI DetourTimeSetEvent(UINT uDelay, UINT uResolution, LPTIMECALLBACK lpTimeProc, DWORD_PTR dwUser, UINT fuEvent) { return pfnKernelTimeSetEvent( uDelay / SpeedFactor(), uResolution, lpTimeProc, dwUser, fuEvent); } static LONG baselineKernelGetMessageTime = 0; static LONG baselineDetourGetMessageTime = 0; static LONG prevcallKernelGetMessageTime = 0; static LONG prevcallDetourGetMessageTime = 0; static std::atomic shouldUpdateGetMessageTime = false; LONG WINAPI DetourGetMessageTime(VOID) { std::shared_lock lock(mutex); if (pre_factor == SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateGetMessageTime.compare_exchange_weak(expected, false)) { baselineKernelGetMessageTime = prevcallKernelGetMessageTime; baselineDetourGetMessageTime = prevcallDetourGetMessageTime; } DWORD now = pfnKernelGetMessageTime(); prevcallKernelGetMessageTime = now; DWORD delta = SpeedFactor() * (now - baselineKernelGetMessageTime); prevcallDetourGetMessageTime = baselineDetourGetMessageTime + delta; return baselineDetourGetMessageTime + delta; } static DWORD baselineKernelGetTickCount = 0; static DWORD baselineDetourGetTickCount = 0; static DWORD prevcallKernelGetTickCount = 0; static DWORD prevcallDetourGetTickCount = 0; static std::atomic shouldUpdateGetTickCount = false; DWORD WINAPI DetourGetTickCount(VOID) { std::shared_lock lock(mutex); if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateGetTickCount.compare_exchange_weak(expected, false)) { baselineKernelGetTickCount = prevcallKernelGetTickCount; baselineDetourGetTickCount = prevcallDetourGetTickCount; } DWORD now = pfnKernelGetTickCount(); prevcallKernelGetTickCount = now; DWORD delta = SpeedFactor() * (now - baselineKernelGetTickCount); prevcallDetourGetTickCount = baselineDetourGetTickCount + delta; return baselineDetourGetTickCount + delta; } static ULONGLONG baselineKernelGetTickCount64 = 0; static ULONGLONG baselineDetourGetTickCount64 = 0; static ULONGLONG prevcallKernelGetTickCount64 = 0; static ULONGLONG prevcallDetourGetTickCount64 = 0; std::atomic shouldUpdateGetTickCount64 = false; ULONGLONG WINAPI DetourGetTickCount64(VOID) { std::shared_lock lock(mutex); if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateGetTickCount64.compare_exchange_weak(expected, false)) { baselineKernelGetTickCount64 = prevcallKernelGetTickCount64; baselineDetourGetTickCount64 = prevcallDetourGetTickCount64; } ULONGLONG now = pfnKernelGetTickCount64(); prevcallKernelGetTickCount64 = now; ULONGLONG delta = SpeedFactor() * (now - baselineKernelGetTickCount64); prevcallDetourGetTickCount64 = baselineDetourGetTickCount64 + delta; return baselineDetourGetTickCount64 + delta; } static LARGE_INTEGER baselineKernelQueryPerformanceCounter = { 0 }; static LARGE_INTEGER baselineDetourQueryPerformanceCounter = { 0 }; static LARGE_INTEGER prevcallKernelQueryPerformanceCounter = { 0 }; static LARGE_INTEGER prevcallDetourQueryPerformanceCounter = { 0 }; static std::atomic shouldUpdateQueryPerformanceCounter = false; BOOL WINAPI DetourQueryPerformanceCounter(LARGE_INTEGER* lpPerformanceCount) { std::shared_lock lock(mutex); if (lpPerformanceCount == NULL) { return FALSE; } if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } // 更新基准时间点 bool expected = true; if (shouldUpdateQueryPerformanceCounter.compare_exchange_weak(expected, false)) { baselineKernelQueryPerformanceCounter = prevcallKernelQueryPerformanceCounter; baselineDetourQueryPerformanceCounter = prevcallDetourQueryPerformanceCounter; } BOOL rtncode = pfnKernelQueryPerformanceCounter( &prevcallKernelQueryPerformanceCounter); if (rtncode == TRUE) { *lpPerformanceCount = prevcallKernelQueryPerformanceCounter; } LONGLONG delta = SpeedFactor() * (lpPerformanceCount->QuadPart - baselineKernelQueryPerformanceCounter.QuadPart) ; lpPerformanceCount->QuadPart = baselineDetourQueryPerformanceCounter.QuadPart + delta; prevcallDetourQueryPerformanceCounter = *lpPerformanceCount; return rtncode; } static LARGE_INTEGER baselineKernelQueryPerformanceFrequency = { 0 }; BOOL WINAPI DetourQueryPerformanceFrequency(LARGE_INTEGER* lpFrequency) { std::shared_lock lock(mutex); if (lpFrequency == NULL) { return FALSE; } else { BOOL rtncode = pfnKernelQueryPerformanceFrequency(lpFrequency); lpFrequency->QuadPart = SpeedFactor() * lpFrequency->QuadPart; return rtncode; } } static std::atomic baselineKernelGetSystemTimeAsFileTime({ 0 }); static std::atomic baselineDetourGetSystemTimeAsFileTime({ 0 }); static std::atomic prevcallKernelGetSystemTimeAsFileTime({ 0 }); static std::atomic prevcallDetourGetSystemTimeAsFileTime({ 0 }); static std::atomic shouldUpdateGetSystemTimeAsFileTime = false; VOID WINAPI DetourGetSystemTimeAsFileTime(LPFILETIME lpSystemTimeAsFileTime) { std::shared_lock lock(mutex); if (lpSystemTimeAsFileTime == NULL) { return; } if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateGetSystemTimeAsFileTime.compare_exchange_weak(expected, false)) { baselineKernelGetSystemTimeAsFileTime.store( prevcallKernelGetSystemTimeAsFileTime.load()); baselineDetourGetSystemTimeAsFileTime.store( prevcallDetourGetSystemTimeAsFileTime.load()); } // 从全局变量读取基准点快照到线程栈 FILETIME baselineKernelSnapshot = baselineKernelGetSystemTimeAsFileTime.load(); ULARGE_INTEGER baselineKernel = { baselineKernelSnapshot.dwLowDateTime, baselineKernelSnapshot.dwHighDateTime }; FILETIME baselineDetourSnapshot = baselineDetourGetSystemTimeAsFileTime.load(); ULARGE_INTEGER baselineDetour = { baselineDetourSnapshot.dwLowDateTime, baselineDetourSnapshot.dwHighDateTime }; FILETIME ftNow = { 0 }; pfnKernelGetSystemTimeAsFileTime(&ftNow); prevcallKernelGetSystemTimeAsFileTime.store(ftNow); ULARGE_INTEGER ulNow = { ftNow.dwLowDateTime, ftNow.dwHighDateTime }; ULONGLONG delta = SpeedFactor() * (ulNow.QuadPart - baselineKernel.QuadPart); ULARGE_INTEGER ulRtn = { 0 }; ulRtn.QuadPart = baselineDetour.QuadPart + delta; prevcallDetourGetSystemTimeAsFileTime.store( { ulRtn.LowPart, ulRtn.HighPart }); (*lpSystemTimeAsFileTime) = { ulRtn.LowPart, ulRtn.HighPart }; } static std::atomic baselineKernelGetSystemTimePreciseAsFileTime({ 0 }); static std::atomic baselineDetourGetSystemTimePreciseAsFileTime({ 0 }); static std::atomic prevcallKernelGetSystemTimePreciseAsFileTime({ 0 }); static std::atomic prevcallDetourGetSystemTimePreciseAsFileTime({ 0 }); static std::atomic shouldUpdateGetSystemTimePreciseAsFileTime = false; VOID WINAPI DetourGetSystemTimePreciseAsFileTime(LPFILETIME lpSystemTimeAsFileTime) { std::shared_lock lock(mutex); if (lpSystemTimeAsFileTime == NULL) { return; } if (pre_factor != SpeedFactor()) { pre_factor = SpeedFactor(); shouldUpdateAll(); } bool expected = true; if (shouldUpdateGetSystemTimePreciseAsFileTime.compare_exchange_weak( expected, false)) { baselineKernelGetSystemTimePreciseAsFileTime.store( prevcallKernelGetSystemTimePreciseAsFileTime.load()); baselineDetourGetSystemTimePreciseAsFileTime.store( prevcallDetourGetSystemTimePreciseAsFileTime.load()); } // 从全局变量读取基准点快照到线程栈 FILETIME baselineKernelSnapshot = baselineKernelGetSystemTimePreciseAsFileTime.load(); ULARGE_INTEGER baselineKernel = { baselineKernelSnapshot.dwLowDateTime, baselineKernelSnapshot.dwHighDateTime }; FILETIME baselineDetourSnapshot = baselineDetourGetSystemTimePreciseAsFileTime.load(); ULARGE_INTEGER baselineDetour = { baselineDetourSnapshot.dwLowDateTime, baselineDetourSnapshot.dwHighDateTime }; FILETIME ftNow = { 0 }; pfnKernelGetSystemTimePreciseAsFileTime(&ftNow); prevcallKernelGetSystemTimePreciseAsFileTime.store(ftNow); ULARGE_INTEGER ulNow = { ftNow.dwLowDateTime, ftNow.dwHighDateTime }; ULONGLONG delta = SpeedFactor() * (ulNow.QuadPart - baselineKernel.QuadPart); ULARGE_INTEGER ulRtn = { 0 }; ulRtn.QuadPart = baselineDetour.QuadPart + delta; prevcallDetourGetSystemTimePreciseAsFileTime.store({ ulRtn.LowPart, ulRtn.HighPart }); (*lpSystemTimeAsFileTime) = { ulRtn.LowPart, ulRtn.HighPart }; } BOOL WINAPI DetourSetWaitableTimerEx( HANDLE hTimer, const LARGE_INTEGER* lpDueTime, LONG lPeriod, PTIMERAPCROUTINE pfnCompletionRoutine, LPVOID lpArgToCompletionRoutine, PREASON_CONTEXT WakeContext, ULONG TolerableDelay ) { LARGE_INTEGER dueTime = {0}; dueTime.QuadPart = lpDueTime->QuadPart / SpeedFactor(); return pfnKernelSetWaitableTimerEx(hTimer, &dueTime, lPeriod, pfnCompletionRoutine, lpArgToCompletionRoutine, WakeContext, TolerableDelay); } inline VOID shouldUpdateAll() { shouldUpdateTimeGetTime = true; shouldUpdateGetMessageTime = true; shouldUpdateGetTickCount = true; shouldUpdateGetTickCount64 = true; shouldUpdateQueryPerformanceCounter = true; shouldUpdateGetSystemTimeAsFileTime = true; shouldUpdateGetSystemTimePreciseAsFileTime = true; } template inline VOID MH_HOOK(S* pTarget, S* pDetour, T** ppOriginal) { if (MH_CreateHook(reinterpret_cast (pTarget), reinterpret_cast (pDetour), reinterpret_cast (ppOriginal)) != MH_OK) { MessageBoxW(NULL, L"MH装载失败", L"DLL", MB_OK); } if (MH_EnableHook(reinterpret_cast (pTarget)) != MH_OK) { MessageBoxW(NULL, L"MH装载失败", L"DLL", MB_OK); } } template VOID MH_UNHOOK(T* pTarget) { MH_RemoveHook(reinterpret_cast (pTarget)); } LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam) { if (nCode >= 0) { // Hook被触发,DLL已经注入到目标进程 // 在这里执行需要的操作 // 只执行一次,然后移除Hook static bool executed = false; if (!executed) { executed = true; } } return CallNextHookEx(NULL, nCode, wParam, lParam); } BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call, LPVOID lpReserved) { FILETIME now = { 0 }; HMODULE hKernel32; SETWAITABLETIMEREX pSetWaitableTimerEx; switch (ul_reason_for_call) { case DLL_PROCESS_ATTACH: hKernel32 = GetModuleHandleW(L"kernel32.dll"); if (MH_Initialize() != MH_OK) { MessageBoxW(NULL, L"MH装载失败", L"DLL", MB_OK); return FALSE; } Init(); /* Initial timeGetTime */ baselineKernelTimeGetTime = timeGetTime(); prevcallKernelTimeGetTime = baselineKernelTimeGetTime; baselineDetourTimeGetTime = baselineKernelTimeGetTime; prevcallDetourTimeGetTime = baselineKernelTimeGetTime; baselineKernelGetMessageTime = GetMessageTime(); prevcallKernelGetMessageTime = baselineKernelGetMessageTime; baselineDetourGetMessageTime = baselineKernelGetMessageTime; prevcallDetourGetMessageTime = baselineKernelGetMessageTime; /* Initial GetTickCount */ baselineKernelGetTickCount = GetTickCount(); prevcallKernelGetTickCount = baselineKernelGetTickCount; baselineDetourGetTickCount = baselineKernelGetTickCount; prevcallDetourGetTickCount = baselineKernelGetTickCount; baselineKernelGetTickCount64 = GetTickCount64(); prevcallKernelGetTickCount64 = baselineKernelGetTickCount64; baselineDetourGetTickCount64 = baselineKernelGetTickCount64; prevcallDetourGetTickCount64 = baselineKernelGetTickCount64; /* Initial QueryPerformanceCounter */ QueryPerformanceCounter(&baselineKernelQueryPerformanceCounter); prevcallKernelQueryPerformanceCounter = baselineKernelQueryPerformanceCounter; baselineDetourQueryPerformanceCounter = baselineKernelQueryPerformanceCounter; prevcallDetourQueryPerformanceCounter = baselineKernelQueryPerformanceCounter; /* Initial QueryPerformanceFrequency */ QueryPerformanceFrequency(&baselineKernelQueryPerformanceFrequency); /* Initial GetSystemTimeAsFileTime */ GetSystemTimeAsFileTime(&now); baselineKernelGetSystemTimeAsFileTime.store(now); prevcallKernelGetSystemTimeAsFileTime.store(now); baselineDetourGetSystemTimeAsFileTime.store(now); prevcallDetourGetSystemTimeAsFileTime.store(now); /* Initial GetSystemTimePreciseAsFileTime */ GetSystemTimePreciseAsFileTime(&now); baselineKernelGetSystemTimePreciseAsFileTime.store(now); prevcallKernelGetSystemTimePreciseAsFileTime.store(now); baselineDetourGetSystemTimePreciseAsFileTime.store(now); prevcallDetourGetSystemTimePreciseAsFileTime.store(now); MH_HOOK(&Sleep, &DetourSleep, reinterpret_cast (&pfnKernelSleep)); MH_HOOK(&SleepEx, &DetourSleepEx, reinterpret_cast(&pfnKernelSleepEx)); pSetWaitableTimerEx = (SETWAITABLETIMEREX)GetProcAddress(hKernel32, "SetWaitableTimerEx"); MH_HOOK(pSetWaitableTimerEx, &DetourSetWaitableTimerEx, reinterpret_cast(&pfnKernelSetWaitableTimerEx)); MH_HOOK(&SetTimer, &DetourSetTimer, reinterpret_cast (&pfnKernelSetTimer)); MH_HOOK(&timeGetTime, &DetourTimeGetTime, reinterpret_cast (&pfnKernelTimeGetTime)); MH_HOOK(&timeSetEvent, &DetourTimeSetEvent, reinterpret_cast(&pfnKernelTimeSetEvent)); MH_HOOK(&GetMessageTime, &DetourGetMessageTime, reinterpret_cast(&pfnKernelGetMessageTime)); MH_HOOK(&GetTickCount, &DetourGetTickCount, reinterpret_cast (&pfnKernelGetTickCount)); MH_HOOK(&GetTickCount64, &DetourGetTickCount64, reinterpret_cast (&pfnKernelGetTickCount64)); MH_HOOK(&QueryPerformanceCounter, &DetourQueryPerformanceCounter, reinterpret_cast (&pfnKernelQueryPerformanceCounter)); MH_HOOK(&GetSystemTimeAsFileTime, &DetourGetSystemTimeAsFileTime, reinterpret_cast (&pfnKernelGetSystemTimeAsFileTime)); MH_HOOK(&GetSystemTimePreciseAsFileTime, &DetourGetSystemTimePreciseAsFileTime, reinterpret_cast ( &pfnKernelGetSystemTimePreciseAsFileTime)); break; case DLL_THREAD_ATTACH: break; case DLL_THREAD_DETACH: break; case DLL_PROCESS_DETACH: { { std::unique_lock lock(mutex); MH_DisableHook(MH_ALL_HOOKS); } { std::unique_lock lock(mutex); MH_UNHOOK(pfnKernelSleep); MH_UNHOOK(pfnKernelSetTimer); MH_UNHOOK(pfnKernelTimeGetTime); MH_UNHOOK(pfnKernelTimeSetEvent); MH_UNHOOK(pfnKernelGetTickCount); MH_UNHOOK(pfnKernelGetTickCount64); MH_UNHOOK(pfnKernelQueryPerformanceCounter); MH_UNHOOK(pfnKernelGetSystemTimeAsFileTime); MH_UNHOOK(pfnKernelGetSystemTimePreciseAsFileTime); } // Wait for All threads to finish detour api Sleep(1000); { std::unique_lock lock(mutex); if (MH_Uninitialize() != MH_OK) { MessageBoxW(NULL, L"DLL卸载失败", L"DLL", MB_OK); return FALSE; } } Clean(); break; } } return TRUE; } ================================================ FILE: speedpatch/speedpatch.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef SPEEDPATCH_H #define SPEEDPATCH_H #include #include #if defined(SPEEDPATCH_LIBRARY) #define SPEEDPATCH_API __declspec(dllexport) #else #define SPEEDPATCH_API __declspec(dllimport) #endif std::wstring GetCurrentProcessName(); std::wstring GetProcessFileMapName(DWORD processId); extern "C" { SPEEDPATCH_API void Init(); SPEEDPATCH_API void Clean(); SPEEDPATCH_API BOOL GetStatus(); SPEEDPATCH_API void SetProcessStatus(DWORD processId,BOOL status); SPEEDPATCH_API void ChangeSpeed(double factor_); SPEEDPATCH_API LRESULT CALLBACK HookProc(int nCode, WPARAM wParam, LPARAM lParam ); } #endif // SPEEDPATCH_H ================================================ FILE: speedpatch/vcpkg.json ================================================ { "$schema": "https://raw.githubusercontent.com/microsoft/vcpkg-tool/main/docs/vcpkg.schema.json", "name": "mypackage", "version-string": "0.0.1", "dependencies": [ "minhook" ] } ================================================ FILE: taskscheduler.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "taskscheduler.h" #include #include #include TaskScheduler::TaskScheduler(QObject *parent) : QObject{parent} { } TaskScheduler::~TaskScheduler() { } bool TaskScheduler::createStartupTask(const QString &taskName, const QString &executablePath) { if (taskName.isEmpty() || executablePath.isEmpty()) { qWarning() << "任务名称或可执行文件路径不能为空"; return false; } if (!QFile::exists(executablePath)) { qWarning() << "可执行文件不存在" << executablePath; return false; } QStringList arguments; arguments << "/create" << "/f" << "/tn" << taskName << "/tr" << QString("\"%1\" --minimize-to-tray").arg(executablePath) << "/sc" << "onlogon" << "/delay" << "0000:10" << "/rl" << "highest"; return execute(arguments); } bool TaskScheduler::deleteTask(const QString &taskName) { if (taskName.isEmpty()) { qWarning() << "任务名称不能为空"; return false; } if (!isTaskExists(taskName)) { qWarning() << "任务不存在, 无需删除" << taskName; return true; } QStringList arguments; arguments << "/delete" << "/f" << "/tn" << taskName; return execute(arguments); } bool TaskScheduler::enableTask(const QString &taskName, bool enable) { if (!isTaskExists(taskName)) { qWarning() << "任务不存在:" << taskName; return false; } QStringList arguments; arguments << "/change" << "/tn" << taskName << (enable ? "/enable" : "/disable"); return execute(arguments); } bool TaskScheduler::isTaskExists(const QString &taskName) { QStringList arguments; arguments << "/query" << "/tn" << taskName; return execute(arguments); } bool TaskScheduler::execute(const QStringList &arguments) { QProcess process; process.setProgram("schtasks"); process.setArguments(arguments); const int timeout = 10000; process.start(); if (!process.waitForStarted(timeout)) { qWarning() << "无法运行:" << process.errorString(); return false; } if (!process.waitForFinished(timeout)) { qWarning() << "执行超时"; process.kill(); return false; } int exitcode = process.exitCode(); QString stdout_ = QString::fromLocal8Bit(process.readAllStandardOutput()); QString stderr_ = QString::fromLocal8Bit(process.readAllStandardError()); if (exitcode == 0) { qDebug() << "执行成功:" << arguments; qDebug() << "输出:" << stdout_; return true; } else { qDebug() << "执行失败:" << arguments; qDebug() << "错误输出:" << stderr_; qDebug() << "标准输出:" << stdout_; return false; } } bool TaskScheduler::createStartupShortcut(const QString &taskName, const QString &executablePath) { QString home = QDir::homePath(); QString startupDir = home + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"; QString shortcutPath = QDir(startupDir).absoluteFilePath(taskName + ".lnk"); QString arguments = "--minimize-to-tray"; QString psScript = QString("$WScriptShell = New-Object -ComObject WScript.Shell; " "$Shortcut = $WScriptShell.CreateShortcut('%1'); " "$Shortcut.TargetPath = '%2'; " "$Shortcut.Arguments = '%3'; " "$Shortcut.Description = '%4'; " "$Shortcut.Save()") .arg(shortcutPath, executablePath, arguments, QString("启动 %1").arg(QFileInfo(executablePath).baseName())); return executePs(psScript); } bool TaskScheduler::deleteStartupShortcut(const QString &taskName) { QString home = QDir::homePath(); QString startupDir = home + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"; QString shortcutPath = QDir(startupDir).absoluteFilePath(taskName + ".lnk"); QString psScript = QString("Remove-Item '%1' -Force").arg(shortcutPath); return executePs(psScript); } bool TaskScheduler::isStartupShortcutExists(const QString &taskName) { QString home = QDir::homePath(); QString startupDir = home + "\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup"; QString shortcutPath = QDir(startupDir).absoluteFilePath(taskName + ".lnk"); return QFile::exists(shortcutPath); } bool TaskScheduler::executePs(const QString &psScript) { QProcess process; process.setProgram("powershell"); process.setArguments({"-ExecutionPolicy", "Bypass", "-Command", psScript}); process.start(); if (!process.waitForStarted(5000)) { qDebug() << "PowerShell 启动失败:" << process.errorString(); return false; } if (process.waitForFinished(5000) && process.exitCode() == 0) { qDebug() << "PowerShell 执行成功"; return true; } else { QString error = QString::fromLocal8Bit(process.readAllStandardError()); qDebug() << "PowerShell 执行失败:" << error; } return false; } ================================================ FILE: taskscheduler.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef TASKSCHEDULER_H #define TASKSCHEDULER_H #include #include #include class TaskScheduler : public QObject { Q_OBJECT public: explicit TaskScheduler(QObject *parent = nullptr); ~TaskScheduler(); bool createStartupTask(const QString &taskName, const QString &executablePath); bool deleteTask(const QString &taskName); bool enableTask(const QString &taskName, bool enable); bool isTaskExists(const QString &taskName); bool execute(const QStringList &arguments); bool createStartupShortcut(const QString &taskName, const QString &executablePath); bool deleteStartupShortcut(const QString &taskName); bool isStartupShortcutExists(const QString &taskName); bool executePs(const QString &psScript); }; #endif // TASKSCHEDULER_H ================================================ FILE: themeutils.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "themeutils.h" #include #include #include #include #include #include void ThemeUtils::applyTheme(Theme theme) { if (theme == System) { if (isSystemDarkMode()) { setDarkTheme(); } else { setLightTheme(); } } else if (theme == Dark) { setDarkTheme(); } else { setLightTheme(); } } void ThemeUtils::setDarkTheme() { QApplication* app = static_cast(QApplication::instance()); if (!app) return; // 深色模式必须使用 Fusion 风格,因为 WindowsVista 风格强制使用浅色控件 app->setStyle(QStyleFactory::create("Fusion")); QPalette darkPalette; QColor darkColor = QColor(45, 45, 45); QColor disabledColor = QColor(127, 127, 127); darkPalette.setColor(QPalette::Window, darkColor); darkPalette.setColor(QPalette::WindowText, Qt::white); darkPalette.setColor(QPalette::Base, QColor(18, 18, 18)); darkPalette.setColor(QPalette::AlternateBase, darkColor); darkPalette.setColor(QPalette::ToolTipBase, Qt::white); darkPalette.setColor(QPalette::ToolTipText, Qt::white); darkPalette.setColor(QPalette::Text, Qt::white); darkPalette.setColor(QPalette::Disabled, QPalette::Text, disabledColor); darkPalette.setColor(QPalette::Button, darkColor); darkPalette.setColor(QPalette::ButtonText, Qt::white); darkPalette.setColor(QPalette::Disabled, QPalette::ButtonText, disabledColor); darkPalette.setColor(QPalette::BrightText, Qt::red); darkPalette.setColor(QPalette::Link, QColor(42, 130, 218)); darkPalette.setColor(QPalette::Highlight, QColor(42, 130, 218)); darkPalette.setColor(QPalette::HighlightedText, Qt::black); darkPalette.setColor(QPalette::Disabled, QPalette::HighlightedText, disabledColor); app->setPalette(darkPalette); app->setStyleSheet("QToolTip { color: #ffffff; background-color: #2a82da; border: 1px solid white; }"); } void ThemeUtils::setLightTheme() { QApplication* app = static_cast(QApplication::instance()); if (!app) return; // 浅色模式优先使用 WindowsVista (原生) 风格 QStyle* style = QStyleFactory::create("Fusion"); if (!style) { style = QStyleFactory::create("Windows"); } app->setStyle(style); // 恢复默认调色板 app->setPalette(style->standardPalette()); // 清除全局样式表 app->setStyleSheet(""); } bool ThemeUtils::isSystemDarkMode() { #ifdef Q_OS_WIN QSettings settings("HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize", QSettings::NativeFormat); return settings.value("AppsUseLightTheme", 1).toInt() == 0; #else return false; #endif } ================================================ FILE: themeutils.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef THEMEUTILS_H #define THEMEUTILS_H #include class ThemeUtils { public: enum Theme { Light, Dark, System }; static void applyTheme(Theme theme); static void setDarkTheme(); static void setLightTheme(); static bool isSystemDarkMode(); }; #endif // THEMEUTILS_H ================================================ FILE: third_party/minhook/.editorconfig ================================================ # EditorConfig is awesome: http://EditorConfig.org # top-most EditorConfig file root = true # Windows-style newlines with a newline ending every file [*] end_of_line = crlf insert_final_newline = true # 4 space indentation [*.{c,h,def}] indent_style = space indent_size = 4 # Trim trailing whitespaces [*.{c,h,def,txt}] trim_trailing_whitespace = true # UTF-8 with BOM [*.{c,h,def,txt}] charset=utf-8-bom # C/C++ code formatting [*.{c,h}] cpp_space_pointer_reference_alignment = right ================================================ FILE: third_party/minhook/.github/workflows/msbuild.yml ================================================ name: Build on: workflow_dispatch: push: branches: [ "master" ] env: # Path to the solution file relative to the root of the project. SOLUTION_FILE_PATH: build/VC17/MinHookVC17.sln # Configuration type to build. # You can convert this to a build matrix if you need coverage of multiple configuration types. # https://docs.github.com/actions/learn-github-actions/managing-complex-workflows#using-a-build-matrix BUILD_CONFIGURATION: Release jobs: build: runs-on: windows-latest steps: - uses: actions/checkout@v4 - name: Add MSBuild to PATH uses: microsoft/setup-msbuild@v2 - name: Build Win32 # Add additional options to the MSBuild command line here (like platform or verbosity level). # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference run: msbuild /m /p:Configuration=${{ env.BUILD_CONFIGURATION }} /p:Platform="Win32" ${{ env.SOLUTION_FILE_PATH }} - name: Build x64 # Add additional options to the MSBuild command line here (like platform or verbosity level). # See https://docs.microsoft.com/visualstudio/msbuild/msbuild-command-line-reference run: msbuild /m /p:Configuration=${{ env.BUILD_CONFIGURATION }} /p:Platform="x64" ${{ env.SOLUTION_FILE_PATH }} - name: Collect artifacts shell: bash run: | mkdir "${{ runner.temp }}/artifacts" mv "build/VC17/bin/${{ env.BUILD_CONFIGURATION }}" "${{ runner.temp }}/artifacts/bin" mv "build/VC17/lib/${{ env.BUILD_CONFIGURATION }}" "${{ runner.temp }}/artifacts/lib" cp -r include "${{ runner.temp }}/artifacts/include" - name: Package bin uses: actions/upload-artifact@v4 with: name: MinHook_bin path: | ${{ runner.temp }}/artifacts/bin/ ${{ runner.temp }}/artifacts/include/ - name: Package lib uses: actions/upload-artifact@v4 with: name: MinHook_lib path: | ${{ runner.temp }}/artifacts/lib/ ${{ runner.temp }}/artifacts/include/ ================================================ FILE: third_party/minhook/.gitignore ================================================ #OS junk files [Tt]humbs.db *.DS_Store #Visual Studio files *.[Oo]bj *.user *.aps *.pch *.vspscc *.vssscc *_i.c *_p.c *.ncb *.suo *.tlb *.tlh *.bak *.[Cc]ache *.ilk *.log *.sbr *.sdf *.opensdf *.unsuccessfulbuild ipch/ obj/ [Ll]ib [Bb]in [Dd]ebug*/ [Rr]elease*/ Ankh.NoLoad *.VC.db .vs/ #GCC files *.o *.d *.res *.dll *.a #Visual Studio Code files .vscode/ ================================================ FILE: third_party/minhook/AUTHORS.txt ================================================ Tsuda Kageyu Creator, maintainer Michael Maltsev Added "Queue" functions. A lot of bug fixes. Andrey Unis Rewrote the hook engine in plain C. ================================================ FILE: third_party/minhook/CMakeLists.txt ================================================ # MinHook - The Minimalistic API Hooking Library for x64/x86 # Copyright (C) 2009-2017 Tsuda Kageyu. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. cmake_minimum_required(VERSION 3.0...3.5) project(minhook LANGUAGES C) include(CMakePackageConfigHelpers) set(MINHOOK_MAJOR_VERSION 1) set(MINHOOK_MINOR_VERSION 3) set(MINHOOK_PATCH_VERSION 3) set(MINHOOK_VERSION ${MINHOOK_MAJOR_VERSION}.${MINHOOK_MINOR_VERSION}.${MINHOOK_PATCH_VERSION}) ################ # BUILD # ################ option(BUILD_SHARED_LIBS "build shared version" OFF) set(SOURCES_MINHOOK "src/buffer.c" "src/hook.c" "src/trampoline.c" ) if(CMAKE_SIZEOF_VOID_P EQUAL 8) set(SOURCES_HDE "src/hde/hde64.c") else() set(SOURCES_HDE "src/hde/hde32.c") endif() if(BUILD_SHARED_LIBS) set(RESOURCES "dll_resources/MinHook.rc" "dll_resources/MinHook.def" ) endif() add_library(minhook ${SOURCES_MINHOOK} ${SOURCES_HDE} ${RESOURCES}) target_include_directories(minhook PUBLIC $ $ ) target_include_directories(minhook PRIVATE "src/") target_include_directories(minhook PRIVATE "src/hde/") if(WIN32) set_target_properties(minhook PROPERTIES PREFIX "") if(CMAKE_SIZEOF_VOID_P EQUAL 8) set_target_properties(minhook PROPERTIES DEBUG_POSTFIX ".x64d") set_target_properties(minhook PROPERTIES RELEASE_POSTFIX ".x64") set_target_properties(minhook PROPERTIES RELWITHDEBINFO_POSTFIX ".x64") set_target_properties(minhook PROPERTIES MINSIZEREL_POSTFIX ".x64") else() set_target_properties(minhook PROPERTIES DEBUG_POSTFIX ".x32d") set_target_properties(minhook PROPERTIES RELEASE_POSTFIX ".x32") set_target_properties(minhook PROPERTIES RELWITHDEBINFO_POSTFIX ".x32") set_target_properties(minhook PROPERTIES MINSIZEREL_POSTFIX ".x32") endif() else() set_target_properties(minhook PROPERTIES PREFIX "lib") set_target_properties(minhook PROPERTIES POSTFIX "") set_target_properties(minhook PROPERTIES DEBUG_POSTFIX "d") endif() ################ # CMAKE CONFIG # ################ configure_package_config_file( "cmake/minhook-config.cmake.in" "minhook-config.cmake" INSTALL_DESTINATION "lib/minhook" ) write_basic_package_version_file( "minhook-config-version.cmake" VERSION ${MINHOOK_VERSION} COMPATIBILITY AnyNewerVersion ) install( FILES "${CMAKE_CURRENT_BINARY_DIR}/minhook-config.cmake" "${CMAKE_CURRENT_BINARY_DIR}/minhook-config-version.cmake" DESTINATION "lib/minhook" ) ################### # INSTALL # ################### install(TARGETS minhook EXPORT minhook-targets RUNTIME DESTINATION "bin" ARCHIVE DESTINATION "lib" LIBRARY DESTINATION "lib" ) install( EXPORT minhook-targets NAMESPACE minhook:: DESTINATION "lib/minhook" ) install( DIRECTORY include DESTINATION . ) ================================================ FILE: third_party/minhook/LICENSE.txt ================================================ MinHook - The Minimalistic API Hooking Library for x64/x86 Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================================================ Portions of this software are Copyright (c) 2008-2009, Vyacheslav Patkov. ================================================================================ Hacker Disassembler Engine 32 C Copyright (c) 2008-2009, Vyacheslav Patkov. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------- Hacker Disassembler Engine 64 C Copyright (c) 2008-2009, Vyacheslav Patkov. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ================================================ FILE: third_party/minhook/README.md ================================================ # MinHook [![License](https://img.shields.io/badge/License-BSD%202--Clause-orange.svg)](https://opensource.org/licenses/BSD-2-Clause) The Minimalistic x86/x64 API Hooking Library for Windows http://www.codeproject.com/KB/winsdk/LibMinHook.aspx ### Version history - **v1.3.4 - 28 Mar 2025** * Improved error handling for enumerating and suspending threads. * Visual Studio 2022 support. * CMake support. * Fixed compilation with Clang. * Fixed compilation as C++ code. - **v1.3.3 - 8 Jan 2017** * Added a helper function ```MH_CreateHookApiEx```. (Thanks to asm256) * Support Visual Studio 2017 RC. - **v1.3.2.1 - 9 Nov 2015** (Nuget package only) * Fixed an insufficient support for Visual Studio 2015. - **v1.3.2 - 1 Nov 2015** * Support Visual Studio 2015. * Support MinGW. - **v1.3.2-beta3 - 21 Jul 2015** (Nuget package only) * Support MinGW. (Experimental) - **v1.3.2-beta2 - 18 May 2015** * Fixed some subtle bugs. (Thanks to RaMMicHaeL) * Added a helper function ```MH_StatusToString```. (Thanks to Jan Klass) - **v1.3.2-beta - 12 May 2015** * Fixed a possible thread deadlock in x64 mode. (Thanks to Aleh Kazakevich) * Reduced the footprint a little more. * Support Visual Studio 2015 RC. (Experimental) - **v1.3.1.1 - 7 Apr 2015** (Nuget package only) * Support for WDK8.0 and 8.1. - **v1.3.1 - 19 Mar 2015** * No major changes from v1.3.1-beta. - **v1.3.1-beta - 11 Mar 2015** * Added a helper function ```MH_CreateHookApi```. (Thanks to uniskz). * Fixed a false memory leak reported by some tools. * Fixed a degradated compatibility issue. - **v1.3 - 13 Sep 2014** * No major changes from v1.3-beta3. - **v1.3-beta3 - 31 Jul 2014** * Fixed some small bugs. * Improved the memory management. - **v1.3-beta2 - 21 Jul 2014** * Changed the parameters to Windows-friendly types. (void* to LPVOID) * Fixed some small bugs. * Reorganized the source files. * Reduced the footprint a little more. - **v1.3-beta - 17 Jul 2014** * Rewrote in plain C to reduce the footprint and memory usage. (suggested by Andrey Unis) * Simplified the overall code base to make it more readable and maintainable. * Changed the license from 3-clause to 2-clause BSD License. - **v1.2 - 28 Sep 2013** * Removed boost dependency ([jarredholman](https://github.com/jarredholman/minhook)). * Fixed a small bug in the GetRelativeBranchDestination function ([pillbug99](http://www.codeproject.com/Messages/4058892/Small-Bug-Found.aspx)). * Added the ```MH_RemoveHook``` function, which removes a hook created with the ```MH_CreateHook``` function. * Added the following functions to enable or disable multiple hooks in one go: ```MH_QueueEnableHook```, ```MH_QueueDisableHook```, ```MH_ApplyQueued```. This is the preferred way of handling multiple hooks as every call to `MH_EnableHook` or `MH_DisableHook` suspends and resumes all threads. * Made the functions ```MH_EnableHook``` and ```MH_DisableHook``` enable/disable all created hooks when the ```MH_ALL_HOOKS``` parameter is passed. This, too, is an efficient way of handling multiple hooks. * If the target function is too small to be patched with a jump, MinHook tries to place the jump above the function. If that fails as well, the ```MH_CreateHook``` function returns ```MH_ERROR_UNSUPPORTED_FUNCTION```. This fixes an issue of hooking the LoadLibraryExW function on Windows 7 x64 ([reported by Obble](http://www.codeproject.com/Messages/4578613/Re-Bug-LoadLibraryExW-hook-fails-on-windows-2008-r.aspx)). - **v1.1 - 26 Nov 2009** * Changed the interface to create a hook and a trampoline function in one go to prevent the detour function from being called before the trampoline function is created. ([reported by xliqz](http://www.codeproject.com/Messages/3280374/Unsafe.aspx)) * Shortened the function names from ```MinHook_*``` to ```MH_*``` to make them handier. - **v1.0 - 22 Nov 2009** * Initial release. ### Building MinHook - Using vcpkg You can download and install MinHook using the [vcpkg](https://github.com/Microsoft/vcpkg) dependency manager: git clone https://github.com/microsoft/vcpkg .\vcpkg\bootstrap-vcpkg.bat .\vcpkg\vcpkg integrate install .\vcpkg\vcpkg install minhook The MinHook port in vcpkg is kept up to date by Microsoft team members and community contributors. If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. ================================================ FILE: third_party/minhook/build/MinGW/make.bat ================================================ windres -i ../../dll_resources/MinHook.rc -o MinHook_rc.o && dllwrap --driver-name g++ -o MinHook.dll -masm=intel --def ../../dll_resources/MinHook.def -Wl,-enable-stdcall-fixup -Wall MinHook_rc.o ../../src/*.c ../../src/HDE/*.c -I../../include -I../../src -Werror -std=c++11 -s -static-libgcc -static-libstdc++|| pause ================================================ FILE: third_party/minhook/build/MinGW/make.sh ================================================ x86_64-w64-mingw32-windres -i ../../dll_resources/MinHook.rc -o MinHook_rc.o && x86_64-w64-mingw32-dllwrap -o MinHook.dll -masm=intel --def ../../dll_resources/MinHook.def -Wl,-enable-stdcall-fixup -Wall MinHook_rc.o ../../src/*.c ../../src/hde/*.c -I../../include -I../../src -Werror -s -static-libgcc -static-libstdc++ ================================================ FILE: third_party/minhook/cmake/minhook-config.cmake.in ================================================ # MinHook - The Minimalistic API Hooking Library for x64/x86 # Copyright (C) 2009-2017 Tsuda Kageyu. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # 2. Redistributions in binary form must reproduce the above copyright # notice, this list of conditions and the following disclaimer in the # documentation and/or other materials provided with the distribution. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED # TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A # PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER # OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, # EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR # PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF # LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. set(MINHOOK_MAJOR_VERSION "@MINHOOK_MAJOR_VERSION@") set(MINHOOK_MINOR_VERSION "@MINHOOK_MINOR_VERSION@") set(MINHOOK_PATCH_VERSION "@MINHOOK_PATCH_VERSION@") set(MINHOOK_VERSION "@MINHOOK_VERSION@") @PACKAGE_INIT@ set(MINHOOK_FOUND ON) set_and_check(MINHOOK_INCLUDE_DIRS "${PACKAGE_PREFIX_DIR}/include/") set_and_check(MINHOOK_LIBRARY_DIRS "${PACKAGE_PREFIX_DIR}/lib") include("${PACKAGE_PREFIX_DIR}/lib/minhook/minhook-targets.cmake") ================================================ FILE: third_party/minhook/dll_resources/MinHook.def ================================================ EXPORTS MH_Initialize MH_Uninitialize MH_CreateHook MH_CreateHookApi MH_CreateHookApiEx MH_RemoveHook MH_EnableHook MH_DisableHook MH_QueueEnableHook MH_QueueDisableHook MH_ApplyQueued MH_StatusToString ================================================ FILE: third_party/minhook/include/MinHook.h ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #if !(defined _M_IX86) && !(defined _M_X64) && !(defined __i386__) && !(defined __x86_64__) #error MinHook supports only x86 and x64 systems. #endif #include // MinHook Error Codes. typedef enum MH_STATUS { // Unknown error. Should not be returned. MH_UNKNOWN = -1, // Successful. MH_OK = 0, // MinHook is already initialized. MH_ERROR_ALREADY_INITIALIZED, // MinHook is not initialized yet, or already uninitialized. MH_ERROR_NOT_INITIALIZED, // The hook for the specified target function is already created. MH_ERROR_ALREADY_CREATED, // The hook for the specified target function is not created yet. MH_ERROR_NOT_CREATED, // The hook for the specified target function is already enabled. MH_ERROR_ENABLED, // The hook for the specified target function is not enabled yet, or already // disabled. MH_ERROR_DISABLED, // The specified pointer is invalid. It points the address of non-allocated // and/or non-executable region. MH_ERROR_NOT_EXECUTABLE, // The specified target function cannot be hooked. MH_ERROR_UNSUPPORTED_FUNCTION, // Failed to allocate memory. MH_ERROR_MEMORY_ALLOC, // Failed to change the memory protection. MH_ERROR_MEMORY_PROTECT, // The specified module is not loaded. MH_ERROR_MODULE_NOT_FOUND, // The specified function is not found. MH_ERROR_FUNCTION_NOT_FOUND } MH_STATUS; // Can be passed as a parameter to MH_EnableHook, MH_DisableHook, // MH_QueueEnableHook or MH_QueueDisableHook. #define MH_ALL_HOOKS NULL #ifdef __cplusplus extern "C" { #endif // Initialize the MinHook library. You must call this function EXACTLY ONCE // at the beginning of your program. MH_STATUS WINAPI MH_Initialize(VOID); // Uninitialize the MinHook library. You must call this function EXACTLY // ONCE at the end of your program. MH_STATUS WINAPI MH_Uninitialize(VOID); // Creates a hook for the specified target function, in disabled state. // Parameters: // pTarget [in] A pointer to the target function, which will be // overridden by the detour function. // pDetour [in] A pointer to the detour function, which will override // the target function. // ppOriginal [out] A pointer to the trampoline function, which will be // used to call the original target function. // This parameter can be NULL. MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal); // Creates a hook for the specified API function, in disabled state. // Parameters: // pszModule [in] A pointer to the loaded module name which contains the // target function. // pszProcName [in] A pointer to the target function name, which will be // overridden by the detour function. // pDetour [in] A pointer to the detour function, which will override // the target function. // ppOriginal [out] A pointer to the trampoline function, which will be // used to call the original target function. // This parameter can be NULL. MH_STATUS WINAPI MH_CreateHookApi( LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal); // Creates a hook for the specified API function, in disabled state. // Parameters: // pszModule [in] A pointer to the loaded module name which contains the // target function. // pszProcName [in] A pointer to the target function name, which will be // overridden by the detour function. // pDetour [in] A pointer to the detour function, which will override // the target function. // ppOriginal [out] A pointer to the trampoline function, which will be // used to call the original target function. // This parameter can be NULL. // ppTarget [out] A pointer to the target function, which will be used // with other functions. // This parameter can be NULL. MH_STATUS WINAPI MH_CreateHookApiEx( LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget); // Removes an already created hook. // Parameters: // pTarget [in] A pointer to the target function. MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget); // Enables an already created hook. // Parameters: // pTarget [in] A pointer to the target function. // If this parameter is MH_ALL_HOOKS, all created hooks are // enabled in one go. MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget); // Disables an already created hook. // Parameters: // pTarget [in] A pointer to the target function. // If this parameter is MH_ALL_HOOKS, all created hooks are // disabled in one go. MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget); // Queues to enable an already created hook. // Parameters: // pTarget [in] A pointer to the target function. // If this parameter is MH_ALL_HOOKS, all created hooks are // queued to be enabled. MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget); // Queues to disable an already created hook. // Parameters: // pTarget [in] A pointer to the target function. // If this parameter is MH_ALL_HOOKS, all created hooks are // queued to be disabled. MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget); // Applies all queued changes in one go. MH_STATUS WINAPI MH_ApplyQueued(VOID); // Translates the MH_STATUS to its name as a string. const char *WINAPI MH_StatusToString(MH_STATUS status); #ifdef __cplusplus } #endif ================================================ FILE: third_party/minhook/src/buffer.c ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include "buffer.h" // Size of each memory block. (= page size of VirtualAlloc) #define MEMORY_BLOCK_SIZE 0x1000 // Max range for seeking a memory block. (= 1024MB) #define MAX_MEMORY_RANGE 0x40000000 // Memory protection flags to check the executable address. #define PAGE_EXECUTE_FLAGS \ (PAGE_EXECUTE | PAGE_EXECUTE_READ | PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY) // Memory slot. typedef struct _MEMORY_SLOT { union { struct _MEMORY_SLOT *pNext; UINT8 buffer[MEMORY_SLOT_SIZE]; }; } MEMORY_SLOT, *PMEMORY_SLOT; // Memory block info. Placed at the head of each block. typedef struct _MEMORY_BLOCK { struct _MEMORY_BLOCK *pNext; PMEMORY_SLOT pFree; // First element of the free slot list. UINT usedCount; } MEMORY_BLOCK, *PMEMORY_BLOCK; //------------------------------------------------------------------------- // Global Variables: //------------------------------------------------------------------------- // First element of the memory block list. static PMEMORY_BLOCK g_pMemoryBlocks; //------------------------------------------------------------------------- VOID InitializeBuffer(VOID) { // Nothing to do for now. } //------------------------------------------------------------------------- VOID UninitializeBuffer(VOID) { PMEMORY_BLOCK pBlock = g_pMemoryBlocks; g_pMemoryBlocks = NULL; while (pBlock) { PMEMORY_BLOCK pNext = pBlock->pNext; VirtualFree(pBlock, 0, MEM_RELEASE); pBlock = pNext; } } //------------------------------------------------------------------------- #if defined(_M_X64) || defined(__x86_64__) static LPVOID FindPrevFreeRegion(LPVOID pAddress, LPVOID pMinAddr, DWORD dwAllocationGranularity) { ULONG_PTR tryAddr = (ULONG_PTR)pAddress; // Round down to the allocation granularity. tryAddr -= tryAddr % dwAllocationGranularity; // Start from the previous allocation granularity multiply. tryAddr -= dwAllocationGranularity; while (tryAddr >= (ULONG_PTR)pMinAddr) { MEMORY_BASIC_INFORMATION mbi; if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) break; if (mbi.State == MEM_FREE) return (LPVOID)tryAddr; if ((ULONG_PTR)mbi.AllocationBase < dwAllocationGranularity) break; tryAddr = (ULONG_PTR)mbi.AllocationBase - dwAllocationGranularity; } return NULL; } #endif //------------------------------------------------------------------------- #if defined(_M_X64) || defined(__x86_64__) static LPVOID FindNextFreeRegion(LPVOID pAddress, LPVOID pMaxAddr, DWORD dwAllocationGranularity) { ULONG_PTR tryAddr = (ULONG_PTR)pAddress; // Round down to the allocation granularity. tryAddr -= tryAddr % dwAllocationGranularity; // Start from the next allocation granularity multiply. tryAddr += dwAllocationGranularity; while (tryAddr <= (ULONG_PTR)pMaxAddr) { MEMORY_BASIC_INFORMATION mbi; if (VirtualQuery((LPVOID)tryAddr, &mbi, sizeof(mbi)) == 0) break; if (mbi.State == MEM_FREE) return (LPVOID)tryAddr; tryAddr = (ULONG_PTR)mbi.BaseAddress + mbi.RegionSize; // Round up to the next allocation granularity. tryAddr += dwAllocationGranularity - 1; tryAddr -= tryAddr % dwAllocationGranularity; } return NULL; } #endif //------------------------------------------------------------------------- static PMEMORY_BLOCK GetMemoryBlock(LPVOID pOrigin) { PMEMORY_BLOCK pBlock; #if defined(_M_X64) || defined(__x86_64__) ULONG_PTR minAddr; ULONG_PTR maxAddr; SYSTEM_INFO si; GetSystemInfo(&si); minAddr = (ULONG_PTR)si.lpMinimumApplicationAddress; maxAddr = (ULONG_PTR)si.lpMaximumApplicationAddress; // pOrigin ± 512MB if ((ULONG_PTR)pOrigin > MAX_MEMORY_RANGE && minAddr < (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE) minAddr = (ULONG_PTR)pOrigin - MAX_MEMORY_RANGE; if (maxAddr > (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE) maxAddr = (ULONG_PTR)pOrigin + MAX_MEMORY_RANGE; // Make room for MEMORY_BLOCK_SIZE bytes. maxAddr -= MEMORY_BLOCK_SIZE - 1; #endif // Look the registered blocks for a reachable one. for (pBlock = g_pMemoryBlocks; pBlock != NULL; pBlock = pBlock->pNext) { #if defined(_M_X64) || defined(__x86_64__) // Ignore the blocks too far. if ((ULONG_PTR)pBlock < minAddr || (ULONG_PTR)pBlock >= maxAddr) continue; #endif // The block has at least one unused slot. if (pBlock->pFree != NULL) return pBlock; } #if defined(_M_X64) || defined(__x86_64__) // Alloc a new block above if not found. { LPVOID pAlloc = pOrigin; while ((ULONG_PTR)pAlloc >= minAddr) { pAlloc = FindPrevFreeRegion(pAlloc, (LPVOID)minAddr, si.dwAllocationGranularity); if (pAlloc == NULL) break; pBlock = (PMEMORY_BLOCK)VirtualAlloc( pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (pBlock != NULL) break; } } // Alloc a new block below if not found. if (pBlock == NULL) { LPVOID pAlloc = pOrigin; while ((ULONG_PTR)pAlloc <= maxAddr) { pAlloc = FindNextFreeRegion(pAlloc, (LPVOID)maxAddr, si.dwAllocationGranularity); if (pAlloc == NULL) break; pBlock = (PMEMORY_BLOCK)VirtualAlloc( pAlloc, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (pBlock != NULL) break; } } #else // In x86 mode, a memory block can be placed anywhere. pBlock = (PMEMORY_BLOCK)VirtualAlloc( NULL, MEMORY_BLOCK_SIZE, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); #endif if (pBlock != NULL) { // Build a linked list of all the slots. PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBlock + 1; pBlock->pFree = NULL; pBlock->usedCount = 0; do { pSlot->pNext = pBlock->pFree; pBlock->pFree = pSlot; pSlot++; } while ((ULONG_PTR)pSlot - (ULONG_PTR)pBlock <= MEMORY_BLOCK_SIZE - MEMORY_SLOT_SIZE); pBlock->pNext = g_pMemoryBlocks; g_pMemoryBlocks = pBlock; } return pBlock; } //------------------------------------------------------------------------- LPVOID AllocateBuffer(LPVOID pOrigin) { PMEMORY_SLOT pSlot; PMEMORY_BLOCK pBlock = GetMemoryBlock(pOrigin); if (pBlock == NULL) return NULL; // Remove an unused slot from the list. pSlot = pBlock->pFree; pBlock->pFree = pSlot->pNext; pBlock->usedCount++; #ifdef _DEBUG // Fill the slot with INT3 for debugging. memset(pSlot, 0xCC, sizeof(MEMORY_SLOT)); #endif return pSlot; } //------------------------------------------------------------------------- VOID FreeBuffer(LPVOID pBuffer) { PMEMORY_BLOCK pBlock = g_pMemoryBlocks; PMEMORY_BLOCK pPrev = NULL; ULONG_PTR pTargetBlock = ((ULONG_PTR)pBuffer / MEMORY_BLOCK_SIZE) * MEMORY_BLOCK_SIZE; while (pBlock != NULL) { if ((ULONG_PTR)pBlock == pTargetBlock) { PMEMORY_SLOT pSlot = (PMEMORY_SLOT)pBuffer; #ifdef _DEBUG // Clear the released slot for debugging. memset(pSlot, 0x00, sizeof(MEMORY_SLOT)); #endif // Restore the released slot to the list. pSlot->pNext = pBlock->pFree; pBlock->pFree = pSlot; pBlock->usedCount--; // Free if unused. if (pBlock->usedCount == 0) { if (pPrev) pPrev->pNext = pBlock->pNext; else g_pMemoryBlocks = pBlock->pNext; VirtualFree(pBlock, 0, MEM_RELEASE); } break; } pPrev = pBlock; pBlock = pBlock->pNext; } } //------------------------------------------------------------------------- BOOL IsExecutableAddress(LPVOID pAddress) { MEMORY_BASIC_INFORMATION mi; VirtualQuery(pAddress, &mi, sizeof(mi)); return (mi.State == MEM_COMMIT && (mi.Protect & PAGE_EXECUTE_FLAGS)); } ================================================ FILE: third_party/minhook/src/buffer.h ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once // Size of each memory slot. #if defined(_M_X64) || defined(__x86_64__) #define MEMORY_SLOT_SIZE 64 #else #define MEMORY_SLOT_SIZE 32 #endif VOID InitializeBuffer(VOID); VOID UninitializeBuffer(VOID); LPVOID AllocateBuffer(LPVOID pOrigin); VOID FreeBuffer(LPVOID pBuffer); BOOL IsExecutableAddress(LPVOID pAddress); ================================================ FILE: third_party/minhook/src/hde/hde32.c ================================================ /* * Hacker Disassembler Engine 32 C * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * */ #if defined(_M_IX86) || defined(__i386__) #include #include "hde32.h" #include "table32.h" unsigned int hde32_disasm(const void *code, hde32s *hs) { uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; uint8_t *ht = hde32_table, m_mod, m_reg, m_rm, disp_size = 0; memset(hs, 0, sizeof(hde32s)); for (x = 16; x; x--) switch (c = *p++) { case 0xf3: hs->p_rep = c; pref |= PRE_F3; break; case 0xf2: hs->p_rep = c; pref |= PRE_F2; break; case 0xf0: hs->p_lock = c; pref |= PRE_LOCK; break; case 0x26: case 0x2e: case 0x36: case 0x3e: case 0x64: case 0x65: hs->p_seg = c; pref |= PRE_SEG; break; case 0x66: hs->p_66 = c; pref |= PRE_66; break; case 0x67: hs->p_67 = c; pref |= PRE_67; break; default: goto pref_done; } pref_done: hs->flags = (uint32_t)pref << 23; if (!pref) pref |= PRE_NONE; if ((hs->opcode = c) == 0x0f) { hs->opcode2 = c = *p++; ht += DELTA_OPCODES; } else if (c >= 0xa0 && c <= 0xa3) { if (pref & PRE_67) pref |= PRE_66; else pref &= ~PRE_66; } opcode = c; cflags = ht[ht[opcode / 4] + (opcode % 4)]; if (cflags == C_ERROR) { hs->flags |= F_ERROR | F_ERROR_OPCODE; cflags = 0; if ((opcode & -3) == 0x24) cflags++; } x = 0; if (cflags & C_GROUP) { uint16_t t; t = *(uint16_t *)(ht + (cflags & 0x7f)); cflags = (uint8_t)t; x = (uint8_t)(t >> 8); } if (hs->opcode2) { ht = hde32_table + DELTA_PREFIXES; if (ht[ht[opcode / 4] + (opcode % 4)] & pref) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (cflags & C_MODRM) { hs->flags |= F_MODRM; hs->modrm = c = *p++; hs->modrm_mod = m_mod = c >> 6; hs->modrm_rm = m_rm = c & 7; hs->modrm_reg = m_reg = (c & 0x3f) >> 3; if (x && ((x << m_reg) & 0x80)) hs->flags |= F_ERROR | F_ERROR_OPCODE; if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { uint8_t t = opcode - 0xd9; if (m_mod == 3) { ht = hde32_table + DELTA_FPU_MODRM + t*8; t = ht[m_reg] << m_rm; } else { ht = hde32_table + DELTA_FPU_REG; t = ht[t] << m_reg; } if (t & 0x80) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (pref & PRE_LOCK) { if (m_mod == 3) { hs->flags |= F_ERROR | F_ERROR_LOCK; } else { uint8_t *table_end, op = opcode; if (hs->opcode2) { ht = hde32_table + DELTA_OP2_LOCK_OK; table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; } else { ht = hde32_table + DELTA_OP_LOCK_OK; table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; op &= -2; } for (; ht != table_end; ht++) if (*ht++ == op) { if (!((*ht << m_reg) & 0x80)) goto no_lock_error; else break; } hs->flags |= F_ERROR | F_ERROR_LOCK; no_lock_error: ; } } if (hs->opcode2) { switch (opcode) { case 0x20: case 0x22: m_mod = 3; if (m_reg > 4 || m_reg == 1) goto error_operand; else goto no_error_operand; case 0x21: case 0x23: m_mod = 3; if (m_reg == 4 || m_reg == 5) goto error_operand; else goto no_error_operand; } } else { switch (opcode) { case 0x8c: if (m_reg > 5) goto error_operand; else goto no_error_operand; case 0x8e: if (m_reg == 1 || m_reg > 5) goto error_operand; else goto no_error_operand; } } if (m_mod == 3) { uint8_t *table_end; if (hs->opcode2) { ht = hde32_table + DELTA_OP2_ONLY_MEM; table_end = ht + sizeof(hde32_table) - DELTA_OP2_ONLY_MEM; } else { ht = hde32_table + DELTA_OP_ONLY_MEM; table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; } for (; ht != table_end; ht += 2) if (*ht++ == opcode) { if ((*ht++ & pref) && !((*ht << m_reg) & 0x80)) goto error_operand; else break; } goto no_error_operand; } else if (hs->opcode2) { switch (opcode) { case 0x50: case 0xd7: case 0xf7: if (pref & (PRE_NONE | PRE_66)) goto error_operand; break; case 0xd6: if (pref & (PRE_F2 | PRE_F3)) goto error_operand; break; case 0xc5: goto error_operand; } goto no_error_operand; } else goto no_error_operand; error_operand: hs->flags |= F_ERROR | F_ERROR_OPERAND; no_error_operand: c = *p++; if (m_reg <= 1) { if (opcode == 0xf6) cflags |= C_IMM8; else if (opcode == 0xf7) cflags |= C_IMM_P66; } switch (m_mod) { case 0: if (pref & PRE_67) { if (m_rm == 6) disp_size = 2; } else if (m_rm == 5) disp_size = 4; break; case 1: disp_size = 1; break; case 2: disp_size = 2; if (!(pref & PRE_67)) disp_size <<= 1; break; } if (m_mod != 3 && m_rm == 4 && !(pref & PRE_67)) { hs->flags |= F_SIB; p++; hs->sib = c; hs->sib_scale = c >> 6; hs->sib_index = (c & 0x3f) >> 3; if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) disp_size = 4; } p--; switch (disp_size) { case 1: hs->flags |= F_DISP8; hs->disp.disp8 = *p; break; case 2: hs->flags |= F_DISP16; hs->disp.disp16 = *(uint16_t *)p; break; case 4: hs->flags |= F_DISP32; hs->disp.disp32 = *(uint32_t *)p; break; } p += disp_size; } else if (pref & PRE_LOCK) hs->flags |= F_ERROR | F_ERROR_LOCK; if (cflags & C_IMM_P66) { if (cflags & C_REL32) { if (pref & PRE_66) { hs->flags |= F_IMM16 | F_RELATIVE; hs->imm.imm16 = *(uint16_t *)p; p += 2; goto disasm_done; } goto rel32_ok; } if (pref & PRE_66) { hs->flags |= F_IMM16; hs->imm.imm16 = *(uint16_t *)p; p += 2; } else { hs->flags |= F_IMM32; hs->imm.imm32 = *(uint32_t *)p; p += 4; } } if (cflags & C_IMM16) { if (hs->flags & F_IMM32) { hs->flags |= F_IMM16; hs->disp.disp16 = *(uint16_t *)p; } else if (hs->flags & F_IMM16) { hs->flags |= F_2IMM16; hs->disp.disp16 = *(uint16_t *)p; } else { hs->flags |= F_IMM16; hs->imm.imm16 = *(uint16_t *)p; } p += 2; } if (cflags & C_IMM8) { hs->flags |= F_IMM8; hs->imm.imm8 = *p++; } if (cflags & C_REL32) { rel32_ok: hs->flags |= F_IMM32 | F_RELATIVE; hs->imm.imm32 = *(uint32_t *)p; p += 4; } else if (cflags & C_REL8) { hs->flags |= F_IMM8 | F_RELATIVE; hs->imm.imm8 = *p++; } disasm_done: if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { hs->flags |= F_ERROR | F_ERROR_LENGTH; hs->len = 15; } return (unsigned int)hs->len; } #endif // defined(_M_IX86) || defined(__i386__) ================================================ FILE: third_party/minhook/src/hde/hde32.h ================================================ /* * Hacker Disassembler Engine 32 * Copyright (c) 2006-2009, Vyacheslav Patkov. * All rights reserved. * * hde32.h: C/C++ header file * */ #ifndef _HDE32_H_ #define _HDE32_H_ /* stdint.h - C99 standard header * http://en.wikipedia.org/wiki/stdint.h * * if your compiler doesn't contain "stdint.h" header (for * example, Microsoft Visual C++), you can download file: * http://www.azillionmonkeys.com/qed/pstdint.h * and change next line to: * #include "pstdint.h" */ #include "pstdint.h" #define F_MODRM 0x00000001 #define F_SIB 0x00000002 #define F_IMM8 0x00000004 #define F_IMM16 0x00000008 #define F_IMM32 0x00000010 #define F_DISP8 0x00000020 #define F_DISP16 0x00000040 #define F_DISP32 0x00000080 #define F_RELATIVE 0x00000100 #define F_2IMM16 0x00000800 #define F_ERROR 0x00001000 #define F_ERROR_OPCODE 0x00002000 #define F_ERROR_LENGTH 0x00004000 #define F_ERROR_LOCK 0x00008000 #define F_ERROR_OPERAND 0x00010000 #define F_PREFIX_REPNZ 0x01000000 #define F_PREFIX_REPX 0x02000000 #define F_PREFIX_REP 0x03000000 #define F_PREFIX_66 0x04000000 #define F_PREFIX_67 0x08000000 #define F_PREFIX_LOCK 0x10000000 #define F_PREFIX_SEG 0x20000000 #define F_PREFIX_ANY 0x3f000000 #define PREFIX_SEGMENT_CS 0x2e #define PREFIX_SEGMENT_SS 0x36 #define PREFIX_SEGMENT_DS 0x3e #define PREFIX_SEGMENT_ES 0x26 #define PREFIX_SEGMENT_FS 0x64 #define PREFIX_SEGMENT_GS 0x65 #define PREFIX_LOCK 0xf0 #define PREFIX_REPNZ 0xf2 #define PREFIX_REPX 0xf3 #define PREFIX_OPERAND_SIZE 0x66 #define PREFIX_ADDRESS_SIZE 0x67 #pragma pack(push,1) typedef struct { uint8_t len; uint8_t p_rep; uint8_t p_lock; uint8_t p_seg; uint8_t p_66; uint8_t p_67; uint8_t opcode; uint8_t opcode2; uint8_t modrm; uint8_t modrm_mod; uint8_t modrm_reg; uint8_t modrm_rm; uint8_t sib; uint8_t sib_scale; uint8_t sib_index; uint8_t sib_base; union { uint8_t imm8; uint16_t imm16; uint32_t imm32; } imm; union { uint8_t disp8; uint16_t disp16; uint32_t disp32; } disp; uint32_t flags; } hde32s; #pragma pack(pop) #ifdef __cplusplus extern "C" { #endif /* __cdecl */ unsigned int hde32_disasm(const void *code, hde32s *hs); #ifdef __cplusplus } #endif #endif /* _HDE32_H_ */ ================================================ FILE: third_party/minhook/src/hde/hde64.c ================================================ /* * Hacker Disassembler Engine 64 C * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * */ #if defined(_M_X64) || defined(__x86_64__) #include #include "hde64.h" #include "table64.h" unsigned int hde64_disasm(const void *code, hde64s *hs) { uint8_t x, c, *p = (uint8_t *)code, cflags, opcode, pref = 0; uint8_t *ht = hde64_table, m_mod, m_reg, m_rm, disp_size = 0; uint8_t op64 = 0; memset(hs, 0, sizeof(hde64s)); for (x = 16; x; x--) switch (c = *p++) { case 0xf3: hs->p_rep = c; pref |= PRE_F3; break; case 0xf2: hs->p_rep = c; pref |= PRE_F2; break; case 0xf0: hs->p_lock = c; pref |= PRE_LOCK; break; case 0x26: case 0x2e: case 0x36: case 0x3e: case 0x64: case 0x65: hs->p_seg = c; pref |= PRE_SEG; break; case 0x66: hs->p_66 = c; pref |= PRE_66; break; case 0x67: hs->p_67 = c; pref |= PRE_67; break; default: goto pref_done; } pref_done: hs->flags = (uint32_t)pref << 23; if (!pref) pref |= PRE_NONE; if ((c & 0xf0) == 0x40) { hs->flags |= F_PREFIX_REX; if ((hs->rex_w = (c & 0xf) >> 3) && (*p & 0xf8) == 0xb8) op64++; hs->rex_r = (c & 7) >> 2; hs->rex_x = (c & 3) >> 1; hs->rex_b = c & 1; if (((c = *p++) & 0xf0) == 0x40) { opcode = c; goto error_opcode; } } if ((hs->opcode = c) == 0x0f) { hs->opcode2 = c = *p++; ht += DELTA_OPCODES; } else if (c >= 0xa0 && c <= 0xa3) { op64++; if (pref & PRE_67) pref |= PRE_66; else pref &= ~PRE_66; } opcode = c; cflags = ht[ht[opcode / 4] + (opcode % 4)]; if (cflags == C_ERROR) { error_opcode: hs->flags |= F_ERROR | F_ERROR_OPCODE; cflags = 0; if ((opcode & -3) == 0x24) cflags++; } x = 0; if (cflags & C_GROUP) { uint16_t t; t = *(uint16_t *)(ht + (cflags & 0x7f)); cflags = (uint8_t)t; x = (uint8_t)(t >> 8); } if (hs->opcode2) { ht = hde64_table + DELTA_PREFIXES; if (ht[ht[opcode / 4] + (opcode % 4)] & pref) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (cflags & C_MODRM) { hs->flags |= F_MODRM; hs->modrm = c = *p++; hs->modrm_mod = m_mod = c >> 6; hs->modrm_rm = m_rm = c & 7; hs->modrm_reg = m_reg = (c & 0x3f) >> 3; if (x && ((x << m_reg) & 0x80)) hs->flags |= F_ERROR | F_ERROR_OPCODE; if (!hs->opcode2 && opcode >= 0xd9 && opcode <= 0xdf) { uint8_t t = opcode - 0xd9; if (m_mod == 3) { ht = hde64_table + DELTA_FPU_MODRM + t*8; t = ht[m_reg] << m_rm; } else { ht = hde64_table + DELTA_FPU_REG; t = ht[t] << m_reg; } if (t & 0x80) hs->flags |= F_ERROR | F_ERROR_OPCODE; } if (pref & PRE_LOCK) { if (m_mod == 3) { hs->flags |= F_ERROR | F_ERROR_LOCK; } else { uint8_t *table_end, op = opcode; if (hs->opcode2) { ht = hde64_table + DELTA_OP2_LOCK_OK; table_end = ht + DELTA_OP_ONLY_MEM - DELTA_OP2_LOCK_OK; } else { ht = hde64_table + DELTA_OP_LOCK_OK; table_end = ht + DELTA_OP2_LOCK_OK - DELTA_OP_LOCK_OK; op &= -2; } for (; ht != table_end; ht++) if (*ht++ == op) { if (!((*ht << m_reg) & 0x80)) goto no_lock_error; else break; } hs->flags |= F_ERROR | F_ERROR_LOCK; no_lock_error: ; } } if (hs->opcode2) { switch (opcode) { case 0x20: case 0x22: m_mod = 3; if (m_reg > 4 || m_reg == 1) goto error_operand; else goto no_error_operand; case 0x21: case 0x23: m_mod = 3; if (m_reg == 4 || m_reg == 5) goto error_operand; else goto no_error_operand; } } else { switch (opcode) { case 0x8c: if (m_reg > 5) goto error_operand; else goto no_error_operand; case 0x8e: if (m_reg == 1 || m_reg > 5) goto error_operand; else goto no_error_operand; } } if (m_mod == 3) { uint8_t *table_end; if (hs->opcode2) { ht = hde64_table + DELTA_OP2_ONLY_MEM; table_end = ht + sizeof(hde64_table) - DELTA_OP2_ONLY_MEM; } else { ht = hde64_table + DELTA_OP_ONLY_MEM; table_end = ht + DELTA_OP2_ONLY_MEM - DELTA_OP_ONLY_MEM; } for (; ht != table_end; ht += 2) if (*ht++ == opcode) { if ((*ht++ & pref) && !((*ht << m_reg) & 0x80)) goto error_operand; else break; } goto no_error_operand; } else if (hs->opcode2) { switch (opcode) { case 0x50: case 0xd7: case 0xf7: if (pref & (PRE_NONE | PRE_66)) goto error_operand; break; case 0xd6: if (pref & (PRE_F2 | PRE_F3)) goto error_operand; break; case 0xc5: goto error_operand; } goto no_error_operand; } else goto no_error_operand; error_operand: hs->flags |= F_ERROR | F_ERROR_OPERAND; no_error_operand: c = *p++; if (m_reg <= 1) { if (opcode == 0xf6) cflags |= C_IMM8; else if (opcode == 0xf7) cflags |= C_IMM_P66; } switch (m_mod) { case 0: if (pref & PRE_67) { if (m_rm == 6) disp_size = 2; } else if (m_rm == 5) disp_size = 4; break; case 1: disp_size = 1; break; case 2: disp_size = 2; if (!(pref & PRE_67)) disp_size <<= 1; break; } if (m_mod != 3 && m_rm == 4) { hs->flags |= F_SIB; p++; hs->sib = c; hs->sib_scale = c >> 6; hs->sib_index = (c & 0x3f) >> 3; if ((hs->sib_base = c & 7) == 5 && !(m_mod & 1)) disp_size = 4; } p--; switch (disp_size) { case 1: hs->flags |= F_DISP8; hs->disp.disp8 = *p; break; case 2: hs->flags |= F_DISP16; hs->disp.disp16 = *(uint16_t *)p; break; case 4: hs->flags |= F_DISP32; hs->disp.disp32 = *(uint32_t *)p; break; } p += disp_size; } else if (pref & PRE_LOCK) hs->flags |= F_ERROR | F_ERROR_LOCK; if (cflags & C_IMM_P66) { if (cflags & C_REL32) { if (pref & PRE_66) { hs->flags |= F_IMM16 | F_RELATIVE; hs->imm.imm16 = *(uint16_t *)p; p += 2; goto disasm_done; } goto rel32_ok; } if (op64) { hs->flags |= F_IMM64; hs->imm.imm64 = *(uint64_t *)p; p += 8; } else if (!(pref & PRE_66)) { hs->flags |= F_IMM32; hs->imm.imm32 = *(uint32_t *)p; p += 4; } else goto imm16_ok; } if (cflags & C_IMM16) { imm16_ok: hs->flags |= F_IMM16; hs->imm.imm16 = *(uint16_t *)p; p += 2; } if (cflags & C_IMM8) { hs->flags |= F_IMM8; hs->imm.imm8 = *p++; } if (cflags & C_REL32) { rel32_ok: hs->flags |= F_IMM32 | F_RELATIVE; hs->imm.imm32 = *(uint32_t *)p; p += 4; } else if (cflags & C_REL8) { hs->flags |= F_IMM8 | F_RELATIVE; hs->imm.imm8 = *p++; } disasm_done: if ((hs->len = (uint8_t)(p-(uint8_t *)code)) > 15) { hs->flags |= F_ERROR | F_ERROR_LENGTH; hs->len = 15; } return (unsigned int)hs->len; } #endif // defined(_M_X64) || defined(__x86_64__) ================================================ FILE: third_party/minhook/src/hde/hde64.h ================================================ /* * Hacker Disassembler Engine 64 * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * * hde64.h: C/C++ header file * */ #ifndef _HDE64_H_ #define _HDE64_H_ /* stdint.h - C99 standard header * http://en.wikipedia.org/wiki/stdint.h * * if your compiler doesn't contain "stdint.h" header (for * example, Microsoft Visual C++), you can download file: * http://www.azillionmonkeys.com/qed/pstdint.h * and change next line to: * #include "pstdint.h" */ #include "pstdint.h" #define F_MODRM 0x00000001 #define F_SIB 0x00000002 #define F_IMM8 0x00000004 #define F_IMM16 0x00000008 #define F_IMM32 0x00000010 #define F_IMM64 0x00000020 #define F_DISP8 0x00000040 #define F_DISP16 0x00000080 #define F_DISP32 0x00000100 #define F_RELATIVE 0x00000200 #define F_ERROR 0x00001000 #define F_ERROR_OPCODE 0x00002000 #define F_ERROR_LENGTH 0x00004000 #define F_ERROR_LOCK 0x00008000 #define F_ERROR_OPERAND 0x00010000 #define F_PREFIX_REPNZ 0x01000000 #define F_PREFIX_REPX 0x02000000 #define F_PREFIX_REP 0x03000000 #define F_PREFIX_66 0x04000000 #define F_PREFIX_67 0x08000000 #define F_PREFIX_LOCK 0x10000000 #define F_PREFIX_SEG 0x20000000 #define F_PREFIX_REX 0x40000000 #define F_PREFIX_ANY 0x7f000000 #define PREFIX_SEGMENT_CS 0x2e #define PREFIX_SEGMENT_SS 0x36 #define PREFIX_SEGMENT_DS 0x3e #define PREFIX_SEGMENT_ES 0x26 #define PREFIX_SEGMENT_FS 0x64 #define PREFIX_SEGMENT_GS 0x65 #define PREFIX_LOCK 0xf0 #define PREFIX_REPNZ 0xf2 #define PREFIX_REPX 0xf3 #define PREFIX_OPERAND_SIZE 0x66 #define PREFIX_ADDRESS_SIZE 0x67 #pragma pack(push,1) typedef struct { uint8_t len; uint8_t p_rep; uint8_t p_lock; uint8_t p_seg; uint8_t p_66; uint8_t p_67; uint8_t rex; uint8_t rex_w; uint8_t rex_r; uint8_t rex_x; uint8_t rex_b; uint8_t opcode; uint8_t opcode2; uint8_t modrm; uint8_t modrm_mod; uint8_t modrm_reg; uint8_t modrm_rm; uint8_t sib; uint8_t sib_scale; uint8_t sib_index; uint8_t sib_base; union { uint8_t imm8; uint16_t imm16; uint32_t imm32; uint64_t imm64; } imm; union { uint8_t disp8; uint16_t disp16; uint32_t disp32; } disp; uint32_t flags; } hde64s; #pragma pack(pop) #ifdef __cplusplus extern "C" { #endif /* __cdecl */ unsigned int hde64_disasm(const void *code, hde64s *hs); #ifdef __cplusplus } #endif #endif /* _HDE64_H_ */ ================================================ FILE: third_party/minhook/src/hde/pstdint.h ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include // Integer types for HDE. typedef INT8 int8_t; typedef INT16 int16_t; typedef INT32 int32_t; typedef INT64 int64_t; typedef UINT8 uint8_t; typedef UINT16 uint16_t; typedef UINT32 uint32_t; typedef UINT64 uint64_t; ================================================ FILE: third_party/minhook/src/hde/table32.h ================================================ /* * Hacker Disassembler Engine 32 C * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * */ #define C_NONE 0x00 #define C_MODRM 0x01 #define C_IMM8 0x02 #define C_IMM16 0x04 #define C_IMM_P66 0x10 #define C_REL8 0x20 #define C_REL32 0x40 #define C_GROUP 0x80 #define C_ERROR 0xff #define PRE_ANY 0x00 #define PRE_NONE 0x01 #define PRE_F2 0x02 #define PRE_F3 0x04 #define PRE_66 0x08 #define PRE_67 0x10 #define PRE_LOCK 0x20 #define PRE_SEG 0x40 #define PRE_ALL 0xff #define DELTA_OPCODES 0x4a #define DELTA_FPU_REG 0xf1 #define DELTA_FPU_MODRM 0xf8 #define DELTA_PREFIXES 0x130 #define DELTA_OP_LOCK_OK 0x1a1 #define DELTA_OP2_LOCK_OK 0x1b9 #define DELTA_OP_ONLY_MEM 0x1cb #define DELTA_OP2_ONLY_MEM 0x1da unsigned char hde32_table[] = { 0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3,0xa8,0xa3, 0xa8,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xaa,0xac,0xaa,0xb2,0xaa,0x9f,0x9f, 0x9f,0x9f,0xb5,0xa3,0xa3,0xa4,0xaa,0xaa,0xba,0xaa,0x96,0xaa,0xa8,0xaa,0xc3, 0xc3,0x96,0x96,0xb7,0xae,0xd6,0xbd,0xa3,0xc5,0xa3,0xa3,0x9f,0xc3,0x9c,0xaa, 0xaa,0xac,0xaa,0xbf,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0x90, 0x82,0x7d,0x97,0x59,0x59,0x59,0x59,0x59,0x7f,0x59,0x59,0x60,0x7d,0x7f,0x7f, 0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x9a,0x88,0x7d, 0x59,0x50,0x50,0x50,0x50,0x59,0x59,0x59,0x59,0x61,0x94,0x61,0x9e,0x59,0x59, 0x85,0x59,0x92,0xa3,0x60,0x60,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59,0x59, 0x59,0x59,0x9f,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xcc,0x01,0xbc,0x03,0xf0, 0x10,0x10,0x10,0x10,0x50,0x50,0x50,0x50,0x14,0x20,0x20,0x20,0x20,0x01,0x01, 0x01,0x01,0xc4,0x02,0x10,0x00,0x00,0x00,0x00,0x01,0x01,0xc0,0xc2,0x10,0x11, 0x02,0x03,0x11,0x03,0x03,0x04,0x00,0x00,0x14,0x00,0x02,0x00,0x00,0xc6,0xc8, 0x02,0x02,0x02,0x02,0x00,0x00,0xff,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0xca, 0x01,0x01,0x01,0x00,0x06,0x00,0x04,0x00,0xc0,0xc2,0x01,0x01,0x03,0x01,0xff, 0xff,0x01,0x00,0x03,0xc4,0xc4,0xc6,0x03,0x01,0x01,0x01,0xff,0x03,0x03,0x03, 0xc8,0x40,0x00,0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00, 0x00,0x00,0x00,0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00, 0x00,0xff,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x00,0xff,0xff,0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, 0x7f,0x00,0x00,0xff,0x4a,0x4a,0x4a,0x4a,0x4b,0x52,0x4a,0x4a,0x4a,0x4a,0x4f, 0x4c,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x55,0x45,0x40,0x4a,0x4a,0x4a, 0x45,0x59,0x4d,0x46,0x4a,0x5d,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a,0x4a, 0x4a,0x4a,0x4a,0x4a,0x4a,0x61,0x63,0x67,0x4e,0x4a,0x4a,0x6b,0x6d,0x4a,0x4a, 0x45,0x6d,0x4a,0x4a,0x44,0x45,0x4a,0x4a,0x00,0x00,0x00,0x02,0x0d,0x06,0x06, 0x06,0x06,0x0e,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x00,0x06,0x06,0x02,0x06, 0x00,0x0a,0x0a,0x07,0x07,0x06,0x02,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 0x04,0x04,0x00,0x00,0x00,0x0e,0x05,0x06,0x06,0x06,0x01,0x06,0x00,0x00,0x08, 0x00,0x10,0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01, 0x86,0x00,0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba, 0xf8,0xbb,0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00, 0xc4,0xff,0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00, 0x13,0x09,0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07, 0xb2,0xff,0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf, 0xe7,0x08,0x00,0xf0,0x02,0x00 }; ================================================ FILE: third_party/minhook/src/hde/table64.h ================================================ /* * Hacker Disassembler Engine 64 C * Copyright (c) 2008-2009, Vyacheslav Patkov. * All rights reserved. * */ #define C_NONE 0x00 #define C_MODRM 0x01 #define C_IMM8 0x02 #define C_IMM16 0x04 #define C_IMM_P66 0x10 #define C_REL8 0x20 #define C_REL32 0x40 #define C_GROUP 0x80 #define C_ERROR 0xff #define PRE_ANY 0x00 #define PRE_NONE 0x01 #define PRE_F2 0x02 #define PRE_F3 0x04 #define PRE_66 0x08 #define PRE_67 0x10 #define PRE_LOCK 0x20 #define PRE_SEG 0x40 #define PRE_ALL 0xff #define DELTA_OPCODES 0x4a #define DELTA_FPU_REG 0xfd #define DELTA_FPU_MODRM 0x104 #define DELTA_PREFIXES 0x13c #define DELTA_OP_LOCK_OK 0x1ae #define DELTA_OP2_LOCK_OK 0x1c6 #define DELTA_OP_ONLY_MEM 0x1d8 #define DELTA_OP2_ONLY_MEM 0x1e7 unsigned char hde64_table[] = { 0xa5,0xaa,0xa5,0xb8,0xa5,0xaa,0xa5,0xaa,0xa5,0xb8,0xa5,0xb8,0xa5,0xb8,0xa5, 0xb8,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xc0,0xac,0xc0,0xcc,0xc0,0xa1,0xa1, 0xa1,0xa1,0xb1,0xa5,0xa5,0xa6,0xc0,0xc0,0xd7,0xda,0xe0,0xc0,0xe4,0xc0,0xea, 0xea,0xe0,0xe0,0x98,0xc8,0xee,0xf1,0xa5,0xd3,0xa5,0xa5,0xa1,0xea,0x9e,0xc0, 0xc0,0xc2,0xc0,0xe6,0x03,0x7f,0x11,0x7f,0x01,0x7f,0x01,0x3f,0x01,0x01,0xab, 0x8b,0x90,0x64,0x5b,0x5b,0x5b,0x5b,0x5b,0x92,0x5b,0x5b,0x76,0x90,0x92,0x92, 0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x6a,0x73,0x90, 0x5b,0x52,0x52,0x52,0x52,0x5b,0x5b,0x5b,0x5b,0x77,0x7c,0x77,0x85,0x5b,0x5b, 0x70,0x5b,0x7a,0xaf,0x76,0x76,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b,0x5b, 0x5b,0x5b,0x86,0x01,0x03,0x01,0x04,0x03,0xd5,0x03,0xd5,0x03,0xcc,0x01,0xbc, 0x03,0xf0,0x03,0x03,0x04,0x00,0x50,0x50,0x50,0x50,0xff,0x20,0x20,0x20,0x20, 0x01,0x01,0x01,0x01,0xc4,0x02,0x10,0xff,0xff,0xff,0x01,0x00,0x03,0x11,0xff, 0x03,0xc4,0xc6,0xc8,0x02,0x10,0x00,0xff,0xcc,0x01,0x01,0x01,0x00,0x00,0x00, 0x00,0x01,0x01,0x03,0x01,0xff,0xff,0xc0,0xc2,0x10,0x11,0x02,0x03,0x01,0x01, 0x01,0xff,0xff,0xff,0x00,0x00,0x00,0xff,0x00,0x00,0xff,0xff,0xff,0xff,0x10, 0x10,0x10,0x10,0x02,0x10,0x00,0x00,0xc6,0xc8,0x02,0x02,0x02,0x02,0x06,0x00, 0x04,0x00,0x02,0xff,0x00,0xc0,0xc2,0x01,0x01,0x03,0x03,0x03,0xca,0x40,0x00, 0x0a,0x00,0x04,0x00,0x00,0x00,0x00,0x7f,0x00,0x33,0x01,0x00,0x00,0x00,0x00, 0x00,0x00,0xff,0xbf,0xff,0xff,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0xff,0x00, 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff, 0x00,0x00,0x00,0xbf,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x7f,0x00,0x00, 0xff,0x40,0x40,0x40,0x40,0x41,0x49,0x40,0x40,0x40,0x40,0x4c,0x42,0x40,0x40, 0x40,0x40,0x40,0x40,0x40,0x40,0x4f,0x44,0x53,0x40,0x40,0x40,0x44,0x57,0x43, 0x5c,0x40,0x60,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40,0x40, 0x40,0x40,0x64,0x66,0x6e,0x6b,0x40,0x40,0x6a,0x46,0x40,0x40,0x44,0x46,0x40, 0x40,0x5b,0x44,0x40,0x40,0x00,0x00,0x00,0x00,0x06,0x06,0x06,0x06,0x01,0x06, 0x06,0x02,0x06,0x06,0x00,0x06,0x00,0x0a,0x0a,0x00,0x00,0x00,0x02,0x07,0x07, 0x06,0x02,0x0d,0x06,0x06,0x06,0x0e,0x05,0x05,0x02,0x02,0x00,0x00,0x04,0x04, 0x04,0x04,0x05,0x06,0x06,0x06,0x00,0x00,0x00,0x0e,0x00,0x00,0x08,0x00,0x10, 0x00,0x18,0x00,0x20,0x00,0x28,0x00,0x30,0x00,0x80,0x01,0x82,0x01,0x86,0x00, 0xf6,0xcf,0xfe,0x3f,0xab,0x00,0xb0,0x00,0xb1,0x00,0xb3,0x00,0xba,0xf8,0xbb, 0x00,0xc0,0x00,0xc1,0x00,0xc7,0xbf,0x62,0xff,0x00,0x8d,0xff,0x00,0xc4,0xff, 0x00,0xc5,0xff,0x00,0xff,0xff,0xeb,0x01,0xff,0x0e,0x12,0x08,0x00,0x13,0x09, 0x00,0x16,0x08,0x00,0x17,0x09,0x00,0x2b,0x09,0x00,0xae,0xff,0x07,0xb2,0xff, 0x00,0xb4,0xff,0x00,0xb5,0xff,0x00,0xc3,0x01,0x00,0xc7,0xff,0xbf,0xe7,0x08, 0x00,0xf0,0x02,0x00 }; ================================================ FILE: third_party/minhook/src/hook.c ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #include #include #include "../include/MinHook.h" #include "buffer.h" #include "trampoline.h" #ifndef ARRAYSIZE #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) #endif // Initial capacity of the HOOK_ENTRY buffer. #define INITIAL_HOOK_CAPACITY 32 // Initial capacity of the thread IDs buffer. #define INITIAL_THREAD_CAPACITY 128 // Special hook position values. #define INVALID_HOOK_POS UINT_MAX #define ALL_HOOKS_POS UINT_MAX // Freeze() action argument defines. #define ACTION_DISABLE 0 #define ACTION_ENABLE 1 #define ACTION_APPLY_QUEUED 2 // Thread access rights for suspending/resuming threads. #define THREAD_ACCESS \ (THREAD_SUSPEND_RESUME | THREAD_GET_CONTEXT | THREAD_QUERY_INFORMATION | THREAD_SET_CONTEXT) // Hook information. typedef struct _HOOK_ENTRY { LPVOID pTarget; // Address of the target function. LPVOID pDetour; // Address of the detour or relay function. LPVOID pTrampoline; // Address of the trampoline function. UINT8 backup[8]; // Original prologue of the target function. UINT8 patchAbove : 1; // Uses the hot patch area. UINT8 isEnabled : 1; // Enabled. UINT8 queueEnable : 1; // Queued for enabling/disabling when != isEnabled. UINT nIP : 4; // Count of the instruction boundaries. UINT8 oldIPs[8]; // Instruction boundaries of the target function. UINT8 newIPs[8]; // Instruction boundaries of the trampoline function. } HOOK_ENTRY, *PHOOK_ENTRY; // Suspended threads for Freeze()/Unfreeze(). typedef struct _FROZEN_THREADS { LPDWORD pItems; // Data heap UINT capacity; // Size of allocated data heap, items UINT size; // Actual number of data items } FROZEN_THREADS, *PFROZEN_THREADS; //------------------------------------------------------------------------- // Global Variables: //------------------------------------------------------------------------- // Spin lock flag for EnterSpinLock()/LeaveSpinLock(). static volatile LONG g_isLocked = FALSE; // Private heap handle. If not NULL, this library is initialized. static HANDLE g_hHeap = NULL; // Hook entries. static struct { PHOOK_ENTRY pItems; // Data heap UINT capacity; // Size of allocated data heap, items UINT size; // Actual number of data items } g_hooks; //------------------------------------------------------------------------- // Returns INVALID_HOOK_POS if not found. static UINT FindHookEntry(LPVOID pTarget) { UINT i; for (i = 0; i < g_hooks.size; ++i) { if ((ULONG_PTR)pTarget == (ULONG_PTR)g_hooks.pItems[i].pTarget) return i; } return INVALID_HOOK_POS; } //------------------------------------------------------------------------- static PHOOK_ENTRY AddHookEntry() { if (g_hooks.pItems == NULL) { g_hooks.capacity = INITIAL_HOOK_CAPACITY; g_hooks.pItems = (PHOOK_ENTRY)HeapAlloc( g_hHeap, 0, g_hooks.capacity * sizeof(HOOK_ENTRY)); if (g_hooks.pItems == NULL) return NULL; } else if (g_hooks.size >= g_hooks.capacity) { PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity * 2) * sizeof(HOOK_ENTRY)); if (p == NULL) return NULL; g_hooks.capacity *= 2; g_hooks.pItems = p; } return &g_hooks.pItems[g_hooks.size++]; } //------------------------------------------------------------------------- static VOID DeleteHookEntry(UINT pos) { if (pos < g_hooks.size - 1) g_hooks.pItems[pos] = g_hooks.pItems[g_hooks.size - 1]; g_hooks.size--; if (g_hooks.capacity / 2 >= INITIAL_HOOK_CAPACITY && g_hooks.capacity / 2 >= g_hooks.size) { PHOOK_ENTRY p = (PHOOK_ENTRY)HeapReAlloc( g_hHeap, 0, g_hooks.pItems, (g_hooks.capacity / 2) * sizeof(HOOK_ENTRY)); if (p == NULL) return; g_hooks.capacity /= 2; g_hooks.pItems = p; } } //------------------------------------------------------------------------- static DWORD_PTR FindOldIP(PHOOK_ENTRY pHook, DWORD_PTR ip) { UINT i; if (pHook->patchAbove && ip == ((DWORD_PTR)pHook->pTarget - sizeof(JMP_REL))) return (DWORD_PTR)pHook->pTarget; for (i = 0; i < pHook->nIP; ++i) { if (ip == ((DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i])) return (DWORD_PTR)pHook->pTarget + pHook->oldIPs[i]; } #if defined(_M_X64) || defined(__x86_64__) // Check relay function. if (ip == (DWORD_PTR)pHook->pDetour) return (DWORD_PTR)pHook->pTarget; #endif return 0; } //------------------------------------------------------------------------- static DWORD_PTR FindNewIP(PHOOK_ENTRY pHook, DWORD_PTR ip) { UINT i; for (i = 0; i < pHook->nIP; ++i) { if (ip == ((DWORD_PTR)pHook->pTarget + pHook->oldIPs[i])) return (DWORD_PTR)pHook->pTrampoline + pHook->newIPs[i]; } return 0; } //------------------------------------------------------------------------- static VOID ProcessThreadIPs(HANDLE hThread, UINT pos, UINT action) { // If the thread suspended in the overwritten area, // move IP to the proper address. CONTEXT c; #if defined(_M_X64) || defined(__x86_64__) DWORD64 *pIP = &c.Rip; #else DWORD *pIP = &c.Eip; #endif UINT count; c.ContextFlags = CONTEXT_CONTROL; if (!GetThreadContext(hThread, &c)) return; if (pos == ALL_HOOKS_POS) { pos = 0; count = g_hooks.size; } else { count = pos + 1; } for (; pos < count; ++pos) { PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; BOOL enable; DWORD_PTR ip; switch (action) { case ACTION_DISABLE: enable = FALSE; break; case ACTION_ENABLE: enable = TRUE; break; default: // ACTION_APPLY_QUEUED enable = pHook->queueEnable; break; } if (pHook->isEnabled == enable) continue; if (enable) ip = FindNewIP(pHook, *pIP); else ip = FindOldIP(pHook, *pIP); if (ip != 0) { *pIP = ip; SetThreadContext(hThread, &c); } } } //------------------------------------------------------------------------- static BOOL EnumerateThreads(PFROZEN_THREADS pThreads) { BOOL succeeded = FALSE; HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapshot != INVALID_HANDLE_VALUE) { THREADENTRY32 te; te.dwSize = sizeof(THREADENTRY32); if (Thread32First(hSnapshot, &te)) { succeeded = TRUE; do { if (te.dwSize >= (FIELD_OFFSET(THREADENTRY32, th32OwnerProcessID) + sizeof(DWORD)) && te.th32OwnerProcessID == GetCurrentProcessId() && te.th32ThreadID != GetCurrentThreadId()) { if (pThreads->pItems == NULL) { pThreads->capacity = INITIAL_THREAD_CAPACITY; pThreads->pItems = (LPDWORD)HeapAlloc(g_hHeap, 0, pThreads->capacity * sizeof(DWORD)); if (pThreads->pItems == NULL) { succeeded = FALSE; break; } } else if (pThreads->size >= pThreads->capacity) { LPDWORD p; pThreads->capacity *= 2; p = (LPDWORD)HeapReAlloc( g_hHeap, 0, pThreads->pItems, pThreads->capacity * sizeof(DWORD)); if (p == NULL) { succeeded = FALSE; break; } pThreads->pItems = p; } pThreads->pItems[pThreads->size++] = te.th32ThreadID; } te.dwSize = sizeof(THREADENTRY32); } while (Thread32Next(hSnapshot, &te)); if (succeeded && GetLastError() != ERROR_NO_MORE_FILES) succeeded = FALSE; if (!succeeded && pThreads->pItems != NULL) { HeapFree(g_hHeap, 0, pThreads->pItems); pThreads->pItems = NULL; } } CloseHandle(hSnapshot); } return succeeded; } //------------------------------------------------------------------------- static MH_STATUS Freeze(PFROZEN_THREADS pThreads, UINT pos, UINT action) { MH_STATUS status = MH_OK; pThreads->pItems = NULL; pThreads->capacity = 0; pThreads->size = 0; if (!EnumerateThreads(pThreads)) { status = MH_ERROR_MEMORY_ALLOC; } else if (pThreads->pItems != NULL) { UINT i; for (i = 0; i < pThreads->size; ++i) { HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, pThreads->pItems[i]); BOOL suspended = FALSE; if (hThread != NULL) { DWORD result = SuspendThread(hThread); if (result != 0xFFFFFFFF) { suspended = TRUE; ProcessThreadIPs(hThread, pos, action); } CloseHandle(hThread); } if (!suspended) { // Mark thread as not suspended, so it's not resumed later on. pThreads->pItems[i] = 0; } } } return status; } //------------------------------------------------------------------------- static VOID Unfreeze(PFROZEN_THREADS pThreads) { if (pThreads->pItems != NULL) { UINT i; for (i = 0; i < pThreads->size; ++i) { DWORD threadId = pThreads->pItems[i]; if (threadId != 0) { HANDLE hThread = OpenThread(THREAD_ACCESS, FALSE, threadId); if (hThread != NULL) { ResumeThread(hThread); CloseHandle(hThread); } } } HeapFree(g_hHeap, 0, pThreads->pItems); } } //------------------------------------------------------------------------- static MH_STATUS EnableHookLL(UINT pos, BOOL enable) { PHOOK_ENTRY pHook = &g_hooks.pItems[pos]; DWORD oldProtect; SIZE_T patchSize = sizeof(JMP_REL); LPBYTE pPatchTarget = (LPBYTE)pHook->pTarget; if (pHook->patchAbove) { pPatchTarget -= sizeof(JMP_REL); patchSize += sizeof(JMP_REL_SHORT); } if (!VirtualProtect(pPatchTarget, patchSize, PAGE_EXECUTE_READWRITE, &oldProtect)) return MH_ERROR_MEMORY_PROTECT; if (enable) { PJMP_REL pJmp = (PJMP_REL)pPatchTarget; pJmp->opcode = 0xE9; pJmp->operand = (UINT32)((LPBYTE)pHook->pDetour - (pPatchTarget + sizeof(JMP_REL))); if (pHook->patchAbove) { PJMP_REL_SHORT pShortJmp = (PJMP_REL_SHORT)pHook->pTarget; pShortJmp->opcode = 0xEB; pShortJmp->operand = (UINT8)(0 - (sizeof(JMP_REL_SHORT) + sizeof(JMP_REL))); } } else { if (pHook->patchAbove) memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); else memcpy(pPatchTarget, pHook->backup, sizeof(JMP_REL)); } VirtualProtect(pPatchTarget, patchSize, oldProtect, &oldProtect); // Just-in-case measure. FlushInstructionCache(GetCurrentProcess(), pPatchTarget, patchSize); pHook->isEnabled = enable; pHook->queueEnable = enable; return MH_OK; } //------------------------------------------------------------------------- static MH_STATUS EnableAllHooksLL(BOOL enable) { MH_STATUS status = MH_OK; UINT i, first = INVALID_HOOK_POS; for (i = 0; i < g_hooks.size; ++i) { if (g_hooks.pItems[i].isEnabled != enable) { first = i; break; } } if (first != INVALID_HOOK_POS) { FROZEN_THREADS threads; status = Freeze(&threads, ALL_HOOKS_POS, enable ? ACTION_ENABLE : ACTION_DISABLE); if (status == MH_OK) { for (i = first; i < g_hooks.size; ++i) { if (g_hooks.pItems[i].isEnabled != enable) { status = EnableHookLL(i, enable); if (status != MH_OK) break; } } Unfreeze(&threads); } } return status; } //------------------------------------------------------------------------- static VOID EnterSpinLock(VOID) { SIZE_T spinCount = 0; // Wait until the flag is FALSE. while (InterlockedCompareExchange(&g_isLocked, TRUE, FALSE) != FALSE) { // No need to generate a memory barrier here, since InterlockedCompareExchange() // generates a full memory barrier itself. // Prevent the loop from being too busy. if (spinCount < 32) Sleep(0); else Sleep(1); spinCount++; } } //------------------------------------------------------------------------- static VOID LeaveSpinLock(VOID) { // No need to generate a memory barrier here, since InterlockedExchange() // generates a full memory barrier itself. InterlockedExchange(&g_isLocked, FALSE); } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_Initialize(VOID) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap == NULL) { g_hHeap = HeapCreate(0, 0, 0); if (g_hHeap != NULL) { // Initialize the internal function buffer. InitializeBuffer(); } else { status = MH_ERROR_MEMORY_ALLOC; } } else { status = MH_ERROR_ALREADY_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_Uninitialize(VOID) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap != NULL) { status = EnableAllHooksLL(FALSE); if (status == MH_OK) { // Free the internal function buffer. // HeapFree is actually not required, but some tools detect a false // memory leak without HeapFree. UninitializeBuffer(); HeapFree(g_hHeap, 0, g_hooks.pItems); HeapDestroy(g_hHeap); g_hHeap = NULL; g_hooks.pItems = NULL; g_hooks.capacity = 0; g_hooks.size = 0; } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_CreateHook(LPVOID pTarget, LPVOID pDetour, LPVOID *ppOriginal) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap != NULL) { if (IsExecutableAddress(pTarget) && IsExecutableAddress(pDetour)) { UINT pos = FindHookEntry(pTarget); if (pos == INVALID_HOOK_POS) { LPVOID pBuffer = AllocateBuffer(pTarget); if (pBuffer != NULL) { TRAMPOLINE ct; ct.pTarget = pTarget; ct.pDetour = pDetour; ct.pTrampoline = pBuffer; if (CreateTrampolineFunction(&ct)) { PHOOK_ENTRY pHook = AddHookEntry(); if (pHook != NULL) { pHook->pTarget = ct.pTarget; #if defined(_M_X64) || defined(__x86_64__) pHook->pDetour = ct.pRelay; #else pHook->pDetour = ct.pDetour; #endif pHook->pTrampoline = ct.pTrampoline; pHook->patchAbove = ct.patchAbove; pHook->isEnabled = FALSE; pHook->queueEnable = FALSE; pHook->nIP = ct.nIP; memcpy(pHook->oldIPs, ct.oldIPs, ARRAYSIZE(ct.oldIPs)); memcpy(pHook->newIPs, ct.newIPs, ARRAYSIZE(ct.newIPs)); // Back up the target function. if (ct.patchAbove) { memcpy( pHook->backup, (LPBYTE)pTarget - sizeof(JMP_REL), sizeof(JMP_REL) + sizeof(JMP_REL_SHORT)); } else { memcpy(pHook->backup, pTarget, sizeof(JMP_REL)); } if (ppOriginal != NULL) *ppOriginal = pHook->pTrampoline; } else { status = MH_ERROR_MEMORY_ALLOC; } } else { status = MH_ERROR_UNSUPPORTED_FUNCTION; } if (status != MH_OK) { FreeBuffer(pBuffer); } } else { status = MH_ERROR_MEMORY_ALLOC; } } else { status = MH_ERROR_ALREADY_CREATED; } } else { status = MH_ERROR_NOT_EXECUTABLE; } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_RemoveHook(LPVOID pTarget) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap != NULL) { UINT pos = FindHookEntry(pTarget); if (pos != INVALID_HOOK_POS) { if (g_hooks.pItems[pos].isEnabled) { FROZEN_THREADS threads; status = Freeze(&threads, pos, ACTION_DISABLE); if (status == MH_OK) { status = EnableHookLL(pos, FALSE); Unfreeze(&threads); } } if (status == MH_OK) { FreeBuffer(g_hooks.pItems[pos].pTrampoline); DeleteHookEntry(pos); } } else { status = MH_ERROR_NOT_CREATED; } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- static MH_STATUS EnableHook(LPVOID pTarget, BOOL enable) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap != NULL) { if (pTarget == MH_ALL_HOOKS) { status = EnableAllHooksLL(enable); } else { UINT pos = FindHookEntry(pTarget); if (pos != INVALID_HOOK_POS) { if (g_hooks.pItems[pos].isEnabled != enable) { FROZEN_THREADS threads; status = Freeze(&threads, pos, ACTION_ENABLE); if (status == MH_OK) { status = EnableHookLL(pos, enable); Unfreeze(&threads); } } else { status = enable ? MH_ERROR_ENABLED : MH_ERROR_DISABLED; } } else { status = MH_ERROR_NOT_CREATED; } } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_EnableHook(LPVOID pTarget) { return EnableHook(pTarget, TRUE); } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_DisableHook(LPVOID pTarget) { return EnableHook(pTarget, FALSE); } //------------------------------------------------------------------------- static MH_STATUS QueueHook(LPVOID pTarget, BOOL queueEnable) { MH_STATUS status = MH_OK; EnterSpinLock(); if (g_hHeap != NULL) { if (pTarget == MH_ALL_HOOKS) { UINT i; for (i = 0; i < g_hooks.size; ++i) g_hooks.pItems[i].queueEnable = queueEnable; } else { UINT pos = FindHookEntry(pTarget); if (pos != INVALID_HOOK_POS) { g_hooks.pItems[pos].queueEnable = queueEnable; } else { status = MH_ERROR_NOT_CREATED; } } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_QueueEnableHook(LPVOID pTarget) { return QueueHook(pTarget, TRUE); } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_QueueDisableHook(LPVOID pTarget) { return QueueHook(pTarget, FALSE); } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_ApplyQueued(VOID) { MH_STATUS status = MH_OK; UINT i, first = INVALID_HOOK_POS; EnterSpinLock(); if (g_hHeap != NULL) { for (i = 0; i < g_hooks.size; ++i) { if (g_hooks.pItems[i].isEnabled != g_hooks.pItems[i].queueEnable) { first = i; break; } } if (first != INVALID_HOOK_POS) { FROZEN_THREADS threads; status = Freeze(&threads, ALL_HOOKS_POS, ACTION_APPLY_QUEUED); if (status == MH_OK) { for (i = first; i < g_hooks.size; ++i) { PHOOK_ENTRY pHook = &g_hooks.pItems[i]; if (pHook->isEnabled != pHook->queueEnable) { status = EnableHookLL(i, pHook->queueEnable); if (status != MH_OK) break; } } Unfreeze(&threads); } } } else { status = MH_ERROR_NOT_INITIALIZED; } LeaveSpinLock(); return status; } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_CreateHookApiEx( LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal, LPVOID *ppTarget) { HMODULE hModule; LPVOID pTarget; hModule = GetModuleHandleW(pszModule); if (hModule == NULL) return MH_ERROR_MODULE_NOT_FOUND; pTarget = (LPVOID)GetProcAddress(hModule, pszProcName); if (pTarget == NULL) return MH_ERROR_FUNCTION_NOT_FOUND; if (ppTarget != NULL) *ppTarget = pTarget; return MH_CreateHook(pTarget, pDetour, ppOriginal); } //------------------------------------------------------------------------- MH_STATUS WINAPI MH_CreateHookApi( LPCWSTR pszModule, LPCSTR pszProcName, LPVOID pDetour, LPVOID *ppOriginal) { return MH_CreateHookApiEx(pszModule, pszProcName, pDetour, ppOriginal, NULL); } //------------------------------------------------------------------------- const char *WINAPI MH_StatusToString(MH_STATUS status) { #define MH_ST2STR(x) \ case x: \ return #x; switch (status) { MH_ST2STR(MH_UNKNOWN) MH_ST2STR(MH_OK) MH_ST2STR(MH_ERROR_ALREADY_INITIALIZED) MH_ST2STR(MH_ERROR_NOT_INITIALIZED) MH_ST2STR(MH_ERROR_ALREADY_CREATED) MH_ST2STR(MH_ERROR_NOT_CREATED) MH_ST2STR(MH_ERROR_ENABLED) MH_ST2STR(MH_ERROR_DISABLED) MH_ST2STR(MH_ERROR_NOT_EXECUTABLE) MH_ST2STR(MH_ERROR_UNSUPPORTED_FUNCTION) MH_ST2STR(MH_ERROR_MEMORY_ALLOC) MH_ST2STR(MH_ERROR_MEMORY_PROTECT) MH_ST2STR(MH_ERROR_MODULE_NOT_FOUND) MH_ST2STR(MH_ERROR_FUNCTION_NOT_FOUND) } #undef MH_ST2STR return "(unknown)"; } ================================================ FILE: third_party/minhook/src/trampoline.c ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include #if defined(_MSC_VER) && !defined(MINHOOK_DISABLE_INTRINSICS) #define ALLOW_INTRINSICS #include #endif #ifndef ARRAYSIZE #define ARRAYSIZE(A) (sizeof(A)/sizeof((A)[0])) #endif #if defined(_M_X64) || defined(__x86_64__) #include "./hde/hde64.h" typedef hde64s HDE; #define HDE_DISASM(code, hs) hde64_disasm(code, hs) #else #include "./hde/hde32.h" typedef hde32s HDE; #define HDE_DISASM(code, hs) hde32_disasm(code, hs) #endif #include "trampoline.h" #include "buffer.h" // Maximum size of a trampoline function. #if defined(_M_X64) || defined(__x86_64__) #define TRAMPOLINE_MAX_SIZE (MEMORY_SLOT_SIZE - sizeof(JMP_ABS)) #else #define TRAMPOLINE_MAX_SIZE MEMORY_SLOT_SIZE #endif //------------------------------------------------------------------------- static BOOL IsCodePadding(LPBYTE pInst, UINT size) { UINT i; if (pInst[0] != 0x00 && pInst[0] != 0x90 && pInst[0] != 0xCC) return FALSE; for (i = 1; i < size; ++i) { if (pInst[i] != pInst[0]) return FALSE; } return TRUE; } //------------------------------------------------------------------------- BOOL CreateTrampolineFunction(PTRAMPOLINE ct) { #if defined(_M_X64) || defined(__x86_64__) CALL_ABS call = { 0xFF, 0x15, 0x00000002, // FF15 00000002: CALL [RIP+8] 0xEB, 0x08, // EB 08: JMP +10 0x0000000000000000ULL // Absolute destination address }; JMP_ABS jmp = { 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 0x0000000000000000ULL // Absolute destination address }; JCC_ABS jcc = { 0x70, 0x0E, // 7* 0E: J** +16 0xFF, 0x25, 0x00000000, // FF25 00000000: JMP [RIP+6] 0x0000000000000000ULL // Absolute destination address }; #else CALL_REL call = { 0xE8, // E8 xxxxxxxx: CALL +5+xxxxxxxx 0x00000000 // Relative destination address }; JMP_REL jmp = { 0xE9, // E9 xxxxxxxx: JMP +5+xxxxxxxx 0x00000000 // Relative destination address }; JCC_REL jcc = { 0x0F, 0x80, // 0F8* xxxxxxxx: J** +6+xxxxxxxx 0x00000000 // Relative destination address }; #endif UINT8 oldPos = 0; UINT8 newPos = 0; ULONG_PTR jmpDest = 0; // Destination address of an internal jump. BOOL finished = FALSE; // Is the function completed? #if defined(_M_X64) || defined(__x86_64__) UINT8 instBuf[16]; #endif ct->patchAbove = FALSE; ct->nIP = 0; do { HDE hs; UINT copySize; LPVOID pCopySrc; ULONG_PTR pOldInst = (ULONG_PTR)ct->pTarget + oldPos; ULONG_PTR pNewInst = (ULONG_PTR)ct->pTrampoline + newPos; copySize = HDE_DISASM((LPVOID)pOldInst, &hs); if (hs.flags & F_ERROR) return FALSE; pCopySrc = (LPVOID)pOldInst; if (oldPos >= sizeof(JMP_REL)) { // The trampoline function is long enough. // Complete the function with the jump to the target function. #if defined(_M_X64) || defined(__x86_64__) jmp.address = pOldInst; #else jmp.operand = (UINT32)(pOldInst - (pNewInst + sizeof(jmp))); #endif pCopySrc = &jmp; copySize = sizeof(jmp); finished = TRUE; } #if defined(_M_X64) || defined(__x86_64__) else if ((hs.modrm & 0xC7) == 0x05) { // Instructions using RIP relative addressing. (ModR/M = 00???101B) // Modify the RIP relative address. PUINT32 pRelAddr; // Avoid using memcpy to reduce the footprint. #ifndef ALLOW_INTRINSICS memcpy(instBuf, (LPBYTE)pOldInst, copySize); #else __movsb(instBuf, (LPBYTE)pOldInst, copySize); #endif pCopySrc = instBuf; // Relative address is stored at (instruction length - immediate value length - 4). pRelAddr = (PUINT32)(instBuf + hs.len - ((hs.flags & 0x3C) >> 2) - 4); *pRelAddr = (UINT32)((pOldInst + hs.len + (INT32)hs.disp.disp32) - (pNewInst + hs.len)); // Complete the function if JMP (FF /4). if (hs.opcode == 0xFF && hs.modrm_reg == 4) finished = TRUE; } #endif else if (hs.opcode == 0xE8) { // Direct relative CALL ULONG_PTR dest = pOldInst + hs.len + (INT32)hs.imm.imm32; #if defined(_M_X64) || defined(__x86_64__) call.address = dest; #else call.operand = (UINT32)(dest - (pNewInst + sizeof(call))); #endif pCopySrc = &call; copySize = sizeof(call); } else if ((hs.opcode & 0xFD) == 0xE9) { // Direct relative JMP (EB or E9) ULONG_PTR dest = pOldInst + hs.len; if (hs.opcode == 0xEB) // isShort jmp dest += (INT8)hs.imm.imm8; else dest += (INT32)hs.imm.imm32; // Simply copy an internal jump. if ((ULONG_PTR)ct->pTarget <= dest && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) { if (jmpDest < dest) jmpDest = dest; } else { #if defined(_M_X64) || defined(__x86_64__) jmp.address = dest; #else jmp.operand = (UINT32)(dest - (pNewInst + sizeof(jmp))); #endif pCopySrc = &jmp; copySize = sizeof(jmp); // Exit the function if it is not in the branch. finished = (pOldInst >= jmpDest); } } else if ((hs.opcode & 0xF0) == 0x70 || (hs.opcode & 0xFC) == 0xE0 || (hs.opcode2 & 0xF0) == 0x80) { // Direct relative Jcc ULONG_PTR dest = pOldInst + hs.len; if ((hs.opcode & 0xF0) == 0x70 // Jcc || (hs.opcode & 0xFC) == 0xE0) // LOOPNZ/LOOPZ/LOOP/JECXZ dest += (INT8)hs.imm.imm8; else dest += (INT32)hs.imm.imm32; // Simply copy an internal jump. if ((ULONG_PTR)ct->pTarget <= dest && dest < ((ULONG_PTR)ct->pTarget + sizeof(JMP_REL))) { if (jmpDest < dest) jmpDest = dest; } else if ((hs.opcode & 0xFC) == 0xE0) { // LOOPNZ/LOOPZ/LOOP/JCXZ/JECXZ to the outside are not supported. return FALSE; } else { UINT8 cond = ((hs.opcode != 0x0F ? hs.opcode : hs.opcode2) & 0x0F); #if defined(_M_X64) || defined(__x86_64__) // Invert the condition in x64 mode to simplify the conditional jump logic. jcc.opcode = 0x71 ^ cond; jcc.address = dest; #else jcc.opcode1 = 0x80 | cond; jcc.operand = (UINT32)(dest - (pNewInst + sizeof(jcc))); #endif pCopySrc = &jcc; copySize = sizeof(jcc); } } else if ((hs.opcode & 0xFE) == 0xC2) { // RET (C2 or C3) // Complete the function if not in a branch. finished = (pOldInst >= jmpDest); } // Can't alter the instruction length in a branch. if (pOldInst < jmpDest && copySize != hs.len) return FALSE; // Trampoline function is too large. if ((newPos + copySize) > TRAMPOLINE_MAX_SIZE) return FALSE; // Trampoline function has too many instructions. if (ct->nIP >= ARRAYSIZE(ct->oldIPs)) return FALSE; ct->oldIPs[ct->nIP] = oldPos; ct->newIPs[ct->nIP] = newPos; ct->nIP++; // Avoid using memcpy to reduce the footprint. #ifndef ALLOW_INTRINSICS memcpy((LPBYTE)ct->pTrampoline + newPos, pCopySrc, copySize); #else __movsb((LPBYTE)ct->pTrampoline + newPos, (LPBYTE)pCopySrc, copySize); #endif newPos += copySize; oldPos += hs.len; } while (!finished); // Is there enough place for a long jump? if (oldPos < sizeof(JMP_REL) && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL) - oldPos)) { // Is there enough place for a short jump? if (oldPos < sizeof(JMP_REL_SHORT) && !IsCodePadding((LPBYTE)ct->pTarget + oldPos, sizeof(JMP_REL_SHORT) - oldPos)) { return FALSE; } // Can we place the long jump above the function? if (!IsExecutableAddress((LPBYTE)ct->pTarget - sizeof(JMP_REL))) return FALSE; if (!IsCodePadding((LPBYTE)ct->pTarget - sizeof(JMP_REL), sizeof(JMP_REL))) return FALSE; ct->patchAbove = TRUE; } #if defined(_M_X64) || defined(__x86_64__) // Create a relay function. jmp.address = (ULONG_PTR)ct->pDetour; ct->pRelay = (LPBYTE)ct->pTrampoline + newPos; memcpy(ct->pRelay, &jmp, sizeof(jmp)); #endif return TRUE; } ================================================ FILE: third_party/minhook/src/trampoline.h ================================================ /* * MinHook - The Minimalistic API Hooking Library for x64/x86 * Copyright (C) 2009-2017 Tsuda Kageyu. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A * PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER * OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #pragma pack(push, 1) // Structs for writing x86/x64 instructions. // 8-bit relative jump. typedef struct _JMP_REL_SHORT { UINT8 opcode; // EB xx: JMP +2+xx UINT8 operand; } JMP_REL_SHORT, *PJMP_REL_SHORT; // 32-bit direct relative jump/call. typedef struct _JMP_REL { UINT8 opcode; // E9/E8 xxxxxxxx: JMP/CALL +5+xxxxxxxx UINT32 operand; // Relative destination address } JMP_REL, *PJMP_REL, CALL_REL; // 64-bit indirect absolute jump. typedef struct _JMP_ABS { UINT8 opcode0; // FF25 00000000: JMP [+6] UINT8 opcode1; UINT32 dummy; UINT64 address; // Absolute destination address } JMP_ABS, *PJMP_ABS; // 64-bit indirect absolute call. typedef struct _CALL_ABS { UINT8 opcode0; // FF15 00000002: CALL [+6] UINT8 opcode1; UINT32 dummy0; UINT8 dummy1; // EB 08: JMP +10 UINT8 dummy2; UINT64 address; // Absolute destination address } CALL_ABS; // 32-bit direct relative conditional jumps. typedef struct _JCC_REL { UINT8 opcode0; // 0F8* xxxxxxxx: J** +6+xxxxxxxx UINT8 opcode1; UINT32 operand; // Relative destination address } JCC_REL; // 64bit indirect absolute conditional jumps that x64 lacks. typedef struct _JCC_ABS { UINT8 opcode; // 7* 0E: J** +16 UINT8 dummy0; UINT8 dummy1; // FF25 00000000: JMP [+6] UINT8 dummy2; UINT32 dummy3; UINT64 address; // Absolute destination address } JCC_ABS; #pragma pack(pop) typedef struct _TRAMPOLINE { LPVOID pTarget; // [In] Address of the target function. LPVOID pDetour; // [In] Address of the detour function. LPVOID pTrampoline; // [In] Buffer address for the trampoline and relay function. #if defined(_M_X64) || defined(__x86_64__) LPVOID pRelay; // [Out] Address of the relay function. #endif BOOL patchAbove; // [Out] Should use the hot patch area? UINT nIP; // [Out] Number of the instruction boundaries. UINT8 oldIPs[8]; // [Out] Instruction boundaries of the target function. UINT8 newIPs[8]; // [Out] Instruction boundaries of the trampoline function. } TRAMPOLINE, *PTRAMPOLINE; BOOL CreateTrampolineFunction(PTRAMPOLINE ct); ================================================ FILE: windbg.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef WINDBG_H #define WINDBG_H #include #include #include #include // 链接dbghelp库 #pragma comment(lib, "dbghelp.lib") typedef BOOL(WINAPI *MINIDUMPWRITEDUMP)( HANDLE hProcess, DWORD ProcessId, HANDLE hFile, MINIDUMP_TYPE DumpType, PMINIDUMP_EXCEPTION_INFORMATION ExceptionParam, PMINIDUMP_USER_STREAM_INFORMATION UserStreamParam, PMINIDUMP_CALLBACK_INFORMATION CallbackParam); // 自定义异常处理函数 LONG WINAPI createMiniDump(EXCEPTION_POINTERS *exceptionPointers) { // 创建dump文件目录 QDir dumpDir(QDir::currentPath() + "/dumps"); if (!dumpDir.exists()) { dumpDir.mkpath("."); } // 生成带时间戳的文件名 QString dumpFileName = QString("%1/crash_%2.dmp") .arg(dumpDir.absolutePath()) .arg(QDateTime::currentDateTime().toString("yyyy-MM-dd_hh-mm-ss")); // 创建文件 HANDLE hFile = CreateFile(dumpFileName.toStdWString().c_str(), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { return EXCEPTION_CONTINUE_SEARCH; } // 加载dbghelp.dll HMODULE dbgHelp = LoadLibrary(L"dbghelp.dll"); if (!dbgHelp) { CloseHandle(hFile); return EXCEPTION_CONTINUE_SEARCH; } // 获取MiniDumpWriteDump函数地址 MINIDUMPWRITEDUMP miniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress(dbgHelp, "MiniDumpWriteDump"); if (!miniDumpWriteDump) { FreeLibrary(dbgHelp); CloseHandle(hFile); return EXCEPTION_CONTINUE_SEARCH; } // 配置异常信息 MINIDUMP_EXCEPTION_INFORMATION exInfo; exInfo.ThreadId = GetCurrentThreadId(); exInfo.ExceptionPointers = exceptionPointers; exInfo.ClientPointers = FALSE; // 设置dump类型 MINIDUMP_TYPE dumpType = (MINIDUMP_TYPE)(MiniDumpWithFullMemory | // 包含完整内存 MiniDumpWithFullMemoryInfo | // 包含内存信息 MiniDumpWithHandleData | // 包含句柄数据 MiniDumpWithThreadInfo | // 包含线程信息 MiniDumpWithUnloadedModules // 包含卸载的模块 ); // 写入dump文件 BOOL success = miniDumpWriteDump(GetCurrentProcess(), GetCurrentProcessId(), hFile, dumpType, &exInfo, NULL, NULL); // 清理资源 FreeLibrary(dbgHelp); CloseHandle(hFile); // 显示通知 if (success) { std::wstring message = QString("程序遇到错误已退出,崩溃转储文件已保存到:\n%1") .arg(dumpFileName) .toStdWString(); MessageBoxW(nullptr, message.c_str(), L"程序崩溃", MB_OK | MB_ICONERROR); } return EXCEPTION_EXECUTE_HANDLER; } #endif // WINDBG_H ================================================ FILE: winutils.cpp ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include "winutils.h" #include #include #include #include #include #include #include static QSet systemNames = { L"svchost.exe", L"wininit.exe", L"RuntimeBroker.exe", }; winutils::winutils() { } bool winutils::injectDll(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process:" << GetLastError(); return false; } if (checkDllExist(processId, dllPath)) { qDebug() << "Process already have been injected"; return true; } else if (injectDllViaCRTW(processId, dllPath)) { return true; } else if (injectDllViaCRTA(processId, dllPath)) { return true; } injectDllViaAPCW(processId, dllPath); injectDllViaAPCA(processId, dllPath); if (checkDllExist(processId, dllPath)) { return true; } else if (injectDllViaWHKW(processId, dllPath)) { return true; } else if (injectDllViaWHKA(processId, dllPath)) { return true; } else { return false; } } bool winutils::injectDllViaCRTA(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process:" << GetLastError(); return false; } if (checkDllExist(processId, dllPath)) { qDebug() << "Process already have been injected"; return true; } SIZE_T pathSize = (dllPath.size() + 1) * sizeof(char); LPVOID pDllPath = VirtualAllocEx(hProcess, nullptr, pathSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pDllPath) { qDebug() << "Failed to allocate memory in target process:" << GetLastError(); CloseHandle(hProcess); return false; } if (!WriteProcessMemory(hProcess, pDllPath, dllPath.toStdString().c_str(), pathSize, nullptr)) { qDebug() << "Failed to write memory in target process:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll"); if (!hKernel32) { qDebug() << "Failed to get handle for kernel32.dll:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } FARPROC pLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA"); if (!pLoadLibraryA) { qDebug() << "Failed to get address of LoadLibraryA:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)pLoadLibraryA, pDllPath, 0, nullptr); if (!hThread) { qDebug() << "Failed to create remote thread:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } WaitForSingleObject(hThread, INFINITE); // 检查LoadLibrary是否执行成功 DWORD exitCode = 0; if (GetExitCodeThread(hThread, &exitCode)) { qDebug() << "Remote thread exit code:" << exitCode; // LoadLibrary返回的是模块句柄,如果为0则失败 if (exitCode == 0) { VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); CloseHandle(hThread); qDebug() << "LoadLibrary failed in remote process"; return false; } } VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hThread); CloseHandle(hProcess); return true; } bool winutils::injectDllViaCRTW(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process:" << GetLastError(); return false; } if (checkDllExist(processId, dllPath)) { qDebug() << "Process already have been injected"; return true; } SIZE_T pathSize = (dllPath.size() + 1) * sizeof(wchar_t); LPVOID pDllPath = VirtualAllocEx(hProcess, nullptr, pathSize, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE); if (!pDllPath) { qDebug() << "Failed to allocate memory in target process:" << GetLastError(); CloseHandle(hProcess); return false; } if (!WriteProcessMemory(hProcess, pDllPath, dllPath.toStdWString().c_str(), pathSize, nullptr)) { qDebug() << "Failed to write memory in target process:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll"); if (!hKernel32) { qDebug() << "Failed to get handle for kernel32.dll:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } FARPROC pLoadLibraryW = GetProcAddress(hKernel32, "LoadLibraryW"); if (!pLoadLibraryW) { qDebug() << "Failed to get address of LoadLibraryW:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)pLoadLibraryW, pDllPath, 0, nullptr); if (!hThread) { qDebug() << "Failed to create remote thread:" << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } WaitForSingleObject(hThread, INFINITE); // 检查LoadLibrary是否执行成功 DWORD exitCode = 0; if (GetExitCodeThread(hThread, &exitCode)) { qDebug() << "Remote thread exit code:" << exitCode; // LoadLibrary返回的是模块句柄,如果为0则失败 if (exitCode == 0) { VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); CloseHandle(hThread); qDebug() << "LoadLibrary failed in remote process"; return false; } } VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hThread); CloseHandle(hProcess); return true; } bool winutils::injectDllViaAPCA(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process: " << GetLastError(); return false; } if (checkDllExist(processId, dllPath)) { qDebug() << "Process already have been injected"; return true; } // 在目标进程中分配内存并写入DLL路径 SIZE_T pathSize = (dllPath.toStdString().size() + 1) * sizeof(char); LPVOID pDllPath = VirtualAllocEx(hProcess, NULL, pathSize, MEM_COMMIT, PAGE_READWRITE); if (!pDllPath) { qDebug() << "Failed to allocate memory: " << GetLastError(); CloseHandle(hProcess); return false; } if (!WriteProcessMemory(hProcess, pDllPath, dllPath.toStdString().c_str(), pathSize, NULL)) { qDebug() << "Failed to write memory: " << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 获取LoadLibraryW的地址 HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll"); if (!hKernel32) { qDebug() << "Failed to get kernel32 handle"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } FARPROC pLoadLibraryA = GetProcAddress(hKernel32, "LoadLibraryA"); if (!pLoadLibraryA) { qDebug() << "Failed to get LoadLibraryA address"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 获取进程中的所有线程 DWORD threadId = getProcessMainThread(processId); if (!threadId) { qDebug() << "No threads found in the process"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 向目标进程的所有线程队列中添加APC调用 bool success = false; // 打开线程 HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, threadId); if (hThread) { // 将LoadLibraryA作为APC函数加入队列 PostThreadMessageA(threadId, WM_PAINT, 0, 0); DWORD result = QueueUserAPC((PAPCFUNC)pLoadLibraryA, hThread, (ULONG_PTR)pDllPath); PostThreadMessageA(threadId, WM_PAINT, 0, 0); if (result != 0) { success = true; qDebug() << "APC queued to thread " << threadId; } CloseHandle(hThread); } if (!success) { qDebug() << "Failed to queue APC to any thread"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 注意:我们不释放分配的内存,因为APC函数尚未执行 // 内存将在DLL加载后释放 CloseHandle(hProcess); return true; } bool winutils::injectDllViaAPCW(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process: " << GetLastError(); return false; } if (checkDllExist(processId, dllPath)) { qDebug() << "Process already have been injected"; return true; } // 在目标进程中分配内存并写入DLL路径 SIZE_T pathSize = (dllPath.toStdWString().size() + 1) * sizeof(wchar_t); LPVOID pDllPath = VirtualAllocEx(hProcess, NULL, pathSize, MEM_COMMIT, PAGE_READWRITE); if (!pDllPath) { qDebug() << "Failed to allocate memory: " << GetLastError(); CloseHandle(hProcess); return false; } if (!WriteProcessMemory(hProcess, pDllPath, dllPath.toStdWString().c_str(), pathSize, NULL)) { qDebug() << "Failed to write memory: " << GetLastError(); VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 获取LoadLibraryW的地址 HMODULE hKernel32 = GetModuleHandle(L"kernel32.dll"); if (!hKernel32) { qDebug() << "Failed to get kernel32 handle"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } FARPROC pLoadLibraryW = GetProcAddress(hKernel32, "LoadLibraryW"); if (!pLoadLibraryW) { qDebug() << "Failed to get LoadLibraryW address"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 获取进程中的所有线程 DWORD threadId = getProcessMainThread(processId); if (!threadId) { qDebug() << "No threads found in the process"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 向目标进程的所有线程队列中添加APC调用 bool success = false; // 打开线程 HANDLE hThread = OpenThread(THREAD_SET_CONTEXT, FALSE, threadId); if (hThread) { // 将LoadLibraryW作为APC函数加入队列 PostThreadMessageW(threadId, WM_PAINT, 0, 0); DWORD result = QueueUserAPC((PAPCFUNC)pLoadLibraryW, hThread, (ULONG_PTR)pDllPath); PostThreadMessageW(threadId, WM_PAINT, 0, 0); if (result != 0) { success = true; qDebug() << "APC queued to thread " << threadId; } CloseHandle(hThread); } if (!success) { qDebug() << "Failed to queue APC to any thread"; VirtualFreeEx(hProcess, pDllPath, 0, MEM_RELEASE); CloseHandle(hProcess); return false; } // 注意:我们不释放分配的内存,因为APC函数尚未执行 // 内存将在DLL加载后释放 CloseHandle(hProcess); return true; } bool winutils::injectDllViaWHKA(DWORD processId, const QString &dllPath) { if (checkProcessProtection(processId)) { qDebug() << "进程被保护 进程ID: " << processId; return false; } // 1. 加载DLL到当前进程 HMODULE hMod = LoadLibraryA(dllPath.toStdString().c_str()); if (!hMod) return false; // 2. 获取Hook过程的地址 HOOKPROC hookProc = (HOOKPROC)GetProcAddress(hMod, "HookProc"); if (!hookProc) return false; // 3. 获取目标线程ID DWORD threadId = getProcessMainThread(processId); if (threadId == 0) return false; // 4. 安装Hook HHOOK hHook = SetWindowsHookExA(WH_CBT, // Hook类型 hookProc, // Hook过程 hMod, // DLL模块句柄 threadId // 目标线程ID ); if (!hHook) return false; // 5. 触发Hook执行 PostThreadMessageA(threadId, WM_NULL, 0, 0); Sleep(5000); UnhookWindowsHookEx(hHook); return true; } bool winutils::injectDllViaWHKW(DWORD processId, const QString &dllPath) { if (checkProcessProtection(processId)) { qDebug() << "进程被保护 进程ID: " << processId; return false; } // 1. 加载DLL到当前进程 HMODULE hMod = LoadLibraryW(dllPath.toStdWString().c_str()); if (!hMod) return false; // 2. 获取Hook过程的地址 HOOKPROC hookProc = (HOOKPROC)GetProcAddress(hMod, "HookProc"); if (!hookProc) return false; // 3. 获取目标线程ID DWORD threadId = getProcessMainThread(processId); if (threadId == 0) return false; // 4. 安装Hook HHOOK hHook = SetWindowsHookExW(WH_CBT, // Hook类型 hookProc, // Hook过程 hMod, // DLL模块句柄 threadId // 目标线程ID ); if (!hHook) return false; // 5. 触发Hook执行 PostThreadMessageW(threadId, WM_NULL, 0, 0); Sleep(5000); UnhookWindowsHookEx(hHook); return true; } bool winutils::unhookDll(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId); if (!hProcess) { qDebug() << "Failed to open process:" << GetLastError(); return false; } HMODULE hModules[1024]; DWORD cbNeeded; if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded)) { for (unsigned int i = 0; i < (cbNeeded / sizeof(HMODULE)); i++) { TCHAR moduleName[MAX_PATH]; if (GetModuleFileNameEx(hProcess, hModules[i], moduleName, sizeof(moduleName) / sizeof(TCHAR))) { #ifdef UNICODE bool isDll = dllPath.toStdWString() == moduleName; #else bool isDll = dllPath.toStdString() == moduleName; #endif if (isDll) { FARPROC pFreeLibrary = GetProcAddress( GetModuleHandle(L"kernel32.dll"), "FreeLibrary"); if (!pFreeLibrary) { qDebug() << "Failed to get address of FreeLibrary:" << GetLastError(); CloseHandle(hProcess); return false; } HANDLE hThread = CreateRemoteThread(hProcess, nullptr, 0, (LPTHREAD_START_ROUTINE)pFreeLibrary, hModules[i], 0, nullptr); if (!hThread) { qDebug() << "Failed to create remote thread for " "FreeLibrary:" << GetLastError(); CloseHandle(hProcess); return false; } WaitForSingleObject(hThread, INFINITE); CloseHandle(hThread); CloseHandle(hProcess); return true; } } } } CloseHandle(hProcess); return false; } bool winutils::checkDllExist(DWORD processId, const QString &dllPath) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); if (!hProcess) { qDebug() << "打开进程失败:" << GetLastError(); return false; } bool dllFound = false; HMODULE hModules[1024]; DWORD cbNeeded; // 获取进程中所有已加载的模块 if (EnumProcessModules(hProcess, hModules, sizeof(hModules), &cbNeeded)) { DWORD moduleCount = cbNeeded / sizeof(HMODULE); for (DWORD i = 0; i < moduleCount; i++) { TCHAR moduleName[MAX_PATH] = {0}; // 获取模块的完整路径 if (GetModuleFileNameExW(hProcess, hModules[i], moduleName, sizeof(moduleName) / sizeof(TCHAR))) { #ifdef UNICODE bool isDll = dllPath.toStdWString() == moduleName; #else bool isDll = dllPath.toStdString() == moduleName; #endif if (isDll) { dllFound = true; break; } } } } else { qDebug() << "枚举进程模块失败:" << GetLastError(); } CloseHandle(hProcess); return dllFound; } bool winutils::checkProcessProtection(DWORD processId) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processId); if (!hProcess) { qDebug() << "Cannot open process - likely protected"; return true; // 可能被保护 } // 检查是否是受保护进程 PROCESS_PROTECTION_LEVEL_INFORMATION protectionInfo = {}; DWORD returnLength; if (GetProcessInformation(hProcess, ProcessProtectionLevelInfo, &protectionInfo, sizeof(protectionInfo))) { CloseHandle(hProcess); return protectionInfo.ProtectionLevel != PROTECTION_LEVEL_NONE; } CloseHandle(hProcess); return false; } void winutils::setAutoStart(bool enable, const QString &appName, const QString &execPath) { TaskScheduler scheduler; if (enable) { scheduler.createStartupShortcut(appName, execPath); } else { scheduler.deleteStartupShortcut(appName); } } bool winutils::isAutoStartEnabled(const QString &appName) { TaskScheduler scheduler; return scheduler.isStartupShortcutExists(appName); } typedef struct _OSVERSIONINFOEXW RTL_OSVERSIONINFOEXW, *PRTL_OSVERSIONINFOEXW; typedef LONG NTSTATUS; typedef NTSTATUS (WINAPI *fnRtlGetVersion)(PRTL_OSVERSIONINFOEXW); BOOL winutils::getWindowsVersion(DWORD *majorVersion, DWORD *minorVersion, DWORD *buildNumber) { HMODULE hNtdll = GetModuleHandleW(L"ntdll.dll"); if (!hNtdll) return FALSE; fnRtlGetVersion RtlGetVersion = (fnRtlGetVersion)GetProcAddress(hNtdll, "RtlGetVersion"); if (!RtlGetVersion) return FALSE; RTL_OSVERSIONINFOEXW osInfo; ZeroMemory(&osInfo, sizeof(RTL_OSVERSIONINFOEXW)); osInfo.dwOSVersionInfoSize = sizeof(RTL_OSVERSIONINFOEXW); NTSTATUS status = RtlGetVersion(&osInfo); if (status != 0) return FALSE; if (majorVersion) *majorVersion = osInfo.dwMajorVersion; if (minorVersion) *minorVersion = osInfo.dwMinorVersion; if (buildNumber) *buildNumber = osInfo.dwBuildNumber; return TRUE; } QString winutils::getWindowsVersion() { static char version[100] = {0}; DWORD major, minor, build; if (!getWindowsVersion(&major, &minor, &build)) return "Unknown Windows Version"; // 确定Windows版本 if (major == 10) { if (build >= 22000) { sprintf(version, "Windows 11 (Build %lu)", build); } else { sprintf(version, "Windows 10 (Build %lu)", build); } } else if (major == 6) { switch (minor) { case 3: sprintf(version, "Windows 8.1 (Build %lu)", build); break; case 2: sprintf(version, "Windows 8 (Build %lu)", build); break; case 1: sprintf(version, "Windows 7 (Build %lu)", build); break; case 0: sprintf(version, "Windows Vista (Build %lu)", build); break; default: sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor, build); } } else if (major == 5) { switch (minor) { case 2: sprintf(version, "Windows Server 2003 (Build %lu)", build); break; case 1: sprintf(version, "Windows XP (Build %lu)", build); break; case 0: sprintf(version, "Windows 2000 (Build %lu)", build); break; default: sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor, build); } } else { sprintf(version, "Windows NT %lu.%lu (Build %lu)", major, minor, build); } return version; } QList winutils::getProcessList() { QList processList; HANDLE hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hProcessSnap == INVALID_HANDLE_VALUE) { qDebug() << "创建进程快照失败: " << GetLastError(); return processList; } PROCESSENTRY32 pe32; pe32.dwSize = sizeof(PROCESSENTRY32); if (!Process32First(hProcessSnap, &pe32)) { qDebug() << "获取首个进程信息失败: " << GetLastError(); CloseHandle(hProcessSnap); return processList; } do { if (systemNames.contains(pe32.szExeFile)) { continue; } ProcessInfo info; info.pid = pe32.th32ProcessID; info.parentPid = pe32.th32ParentProcessID; info.name = QString::fromWCharArray(pe32.szExeFile); info.threadCount = pe32.cntThreads; // 获取内存使用和优先级信息 HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, info.pid); if (hProcess) { PROCESS_MEMORY_COUNTERS pmc; if (GetProcessMemoryInfo(hProcess, &pmc, sizeof(pmc))) { info.memoryUsage = pmc.WorkingSetSize; } else { info.memoryUsage = 0; } BOOL wow64Process = FALSE; IsWow64Process(hProcess, &wow64Process); info.is64Bit = !wow64Process; info.priorityClass = GetPriorityClass(hProcess); CloseHandle(hProcess); } else { info.memoryUsage = 0; info.priorityClass = 0; } processList.append(info); } while (Process32Next(hProcessSnap, &pe32)); CloseHandle(hProcessSnap); return processList; } QString winutils::getProcessPath(DWORD processId) { QString processPath; HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); if (hProcess != NULL) { wchar_t buffer[MAX_PATH]; if (GetModuleFileNameEx(hProcess, NULL, buffer, MAX_PATH) > 0) { processPath = QString::fromWCharArray(buffer); } CloseHandle(hProcess); } return processPath; } DWORD winutils::getProcessMainThread(DWORD processId) { HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, 0); if (hSnapshot == INVALID_HANDLE_VALUE) { qDebug() << "Failed to create thread snapshot:" << GetLastError(); return 0; } THREADENTRY32 te32; te32.dwSize = sizeof(THREADENTRY32); DWORD mainThreadId = 0; FILETIME earliestTime = {0xFFFFFFFF, 0xFFFFFFFF}; // 设为最大值 if (Thread32First(hSnapshot, &te32)) { do { if (te32.th32OwnerProcessID == processId) { // 打开线程获取创建时间 HANDLE hThread = OpenThread(THREAD_QUERY_INFORMATION, FALSE, te32.th32ThreadID); if (hThread) { FILETIME creationTime, exitTime, kernelTime, userTime; if (GetThreadTimes(hThread, &creationTime, &exitTime, &kernelTime, &userTime)) { // 比较创建时间,找最早的线程 if (CompareFileTime(&creationTime, &earliestTime) < 0) { earliestTime = creationTime; mainThreadId = te32.th32ThreadID; } } CloseHandle(hThread); } } } while (Thread32Next(hSnapshot, &te32)); } CloseHandle(hSnapshot); return mainThreadId; } QString winutils::getProcessNameById(DWORD processId) { HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processId); if (hProcess == NULL) { return QString(); } wchar_t processName[MAX_PATH]; if (GetModuleBaseName(hProcess, NULL, processName, MAX_PATH)) { CloseHandle(hProcess); QString name = QString::fromWCharArray(processName); return name; } CloseHandle(hProcess); return QString(); } bool winutils::enableAllPrivilege() { HANDLE hToken; // 获取进程token if (!OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken)) return false; const wchar_t *essentialPrivileges[] = { SE_DEBUG_NAME, // 最重要的调试权限 }; TOKEN_PRIVILEGES tkp; bool success = true; for (const auto &privilege : essentialPrivileges) { tkp.PrivilegeCount = 1; tkp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; if (LookupPrivilegeValue(NULL, privilege, &tkp.Privileges[0].Luid)) { AdjustTokenPrivileges(hToken, FALSE, &tkp, 0, NULL, NULL); } } CloseHandle(hToken); return success; } ================================================ FILE: winutils.h ================================================ /* * OpenSpeedy - Open Source Game Speed Controller * Copyright (C) 2025 Game1024 * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef WINUTILS_H #define WINUTILS_H #include #include "taskscheduler.h" #include #include #include #include struct ProcessInfo { DWORD pid; DWORD parentPid; QString name; DWORD threadCount; bool is64Bit; DWORD priorityClass; SIZE_T memoryUsage; }; class winutils { public: winutils(); public: // DLL 注入 static bool injectDll(DWORD processId, const QString& dllPath); // 远程 DLL 注入 static bool injectDllViaCRTA(DWORD processId, const QString& dllPath); static bool injectDllViaCRTW(DWORD processId, const QString& dllPath); // APC DLL 注入 static bool injectDllViaAPCA(DWORD processId, const QString& dllPath); static bool injectDllViaAPCW(DWORD processId, const QString& dllPath); // Windows Hooks 注入 static bool injectDllViaWHKA(DWORD processId, const QString& dllPath); static bool injectDllViaWHKW(DWORD processId, const QString& dllPath); // DLL 卸载 static bool unhookDll(DWORD processId, const QString& dllPath); // 检查DLL是否已挂载 static bool checkDllExist(DWORD processId, const QString& dllPath); static bool checkProcessProtection(DWORD processId); static void setAutoStart(bool enable, const QString& appName, const QString& execPath); static bool isAutoStartEnabled(const QString& appName); static BOOL getWindowsVersion(DWORD* majorVersion, DWORD* minorVersion, DWORD* buildNumber); static QString getWindowsVersion(); // 获取进程快照 static QList getProcessList(); // 获取进程路径 static QString getProcessPath(DWORD processId); // 获取进程中的主线程 static DWORD getProcessMainThread(DWORD processId); static QString getProcessNameById(DWORD processId); static bool enableAllPrivilege(); }; #endif // WINUTILS_H