Skip to content

fix: Destroy ncnn gpu instance before process exit - #104

Merged
deepin-bot[bot] merged 1 commit into
linuxdeepin:release/eaglefrom
tianming-1996:fix/WS-4159-ncnn-gpu-teardown
Nov 9, 2026
Merged

deepin-bot[bot] merged 1 commit into
linuxdeepin:release/eaglefrom
tianming-1996:fix/WS-4159-ncnn-gpu-teardown

Conversation

@tianming-1996

@tianming-1996 tianming-1996 commented Nov 9, 2026 •

Copy link
Copy Markdown

问题

关闭 OCR 窗口后 deepin-ocr 进程退出阶段 SIGSEGV(PMS 382595 / WS-4159)。

coredump 调用栈(3 份 core 完全一致):

#0 vkDestroyImageView (libvulkan.so.1)
#1 ncnn::VkBlobAllocator::fastFree(ncnn::VkImageMemory*)
#2 ncnn::VulkanDevice::~VulkanDevice()
#3 ncnn::destroy_gpu_instance()
#4 __cxa_finalize
#5 libncnn.so.1
#6 _dl_fini
#7 __run_exit_handlers

崩溃时传入的 VkDevice 句柄已不可访问(gdb 读取报 Cannot access memory)。ncnn 全局 Vulkan GPU 实例直到 __cxa_finalize 阶段才析构,此时 Vulkan ICD 可能已先卸载,vkDestroyImageView() 使用失效句柄导致崩溃。

修改

  • OCREngine 新增 shutdown():先释放 OCR 驱动(其内部 ncnn Net/Mat 持有 GPU 资源),再显式调用 ncnn::destroy_gpu_instance()。
  • main() 在 app->exec() 返回后调用 OCREngine::shutdown(),保证 GPU 实例在 ICD 卸载前销毁。
  • 通过 QLibrary 解析 ncnn 导出符号,不新增 libncnn 的编译/链接依赖。

验证

  • 崩溃数据:GPU 加速开启 3/3 复现(core 312264 / 316144 / 319986);关闭 GPU 后 2/2 正常。
  • 本修复待构建后在 FlemingZ 设备上验证:GPU 开启时反复 OCR 并关闭窗口,确认不再产生 core。

Bug: https://pms.uniontech.com/bug-view-382595.html

Summary by Sourcery

Ensure ncnn GPU resources are destroyed safely before application shutdown to prevent Vulkan handle use after the driver is unloaded.

Bug Fixes:

  • Prevent process-exit SIGSEGVs by explicitly releasing OCR resources and destroying the ncnn GPU instance before Vulkan components are unloaded.

Enhancements:

  • Manage the OCR engine as an explicitly shutdown-capable singleton and resolve ncnn GPU cleanup dynamically without adding a link-time dependency.

Chores:

  • Add SPDX licensing metadata updates to modified source and installation files.

@github-actions

github-actions Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

CLA Assistant Lite bot All contributors have signed the CLA ✍️ ✅

@sourcery-ai

sourcery-ai Bot commented Nov 9, 2026 •

Copy link
Copy Markdown

Reviewer's Guide

Data structures

Add static storage for the OCREngine singleton so shutdown can access and release the instance created by instance().

  • src/engine/OCREngine.cpp L19-20
  • src/engine/OCREngine.h L46-47

API

Expose shutdown() as the lifecycle API for releasing OCR and ncnn GPU resources before process exit.

  • src/engine/OCREngine.h L1, L24-26

Uses of the API

Call OCREngine::shutdown() after each application event loop returns, before main() exits.

  • src/main.cpp L1-90 (4 small edits)

Implementation

Resolve and invoke ncnn's GPU teardown symbol dynamically, releasing the OCR driver first, and update singleton creation to use the shared instance pointer.

  • src/engine/OCREngine.cpp L10-18, L23-47 (+2 small edits)

Configuration

Add the missing SPDX copyright and license header to the dconfig installation CMake file.

  • install_dconfig.cmake L1-3

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 1 issue

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/engine/OCREngine.cpp" line_range="35" />
<code_context>
+        return;
+
+    // 先释放 OCR 驱动,其内部 ncnn Net/Mat 持有 GPU 资源,必须在 GPU 实例销毁前释放
+    delete s_instance->ocrDriver;
+    s_instance->ocrDriver = nullptr;
+
</code_context>
<issue_to_address>
**OCR cleanup races with recognition**

When the window closes while OCR is still running after the three-second wait expires, `shutdown()` deletes `s_instance->ocrDriver` and destroys ncnn GPU state while the worker is still in `getRecogitionResult()` or `analyze()`, causing use-after-free and a crash during close.

Wait for the OCR worker to finish before deleting the driver and destroying the GPU instance.

Also at `src/main.cpp:89`.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread src/engine/OCREngine.cpp
return;

// 先释放 OCR 驱动,其内部 ncnn Net/Mat 持有 GPU 资源,必须在 GPU 实例销毁前释放
delete s_instance->ocrDriver;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · OCR cleanup races with recognition

When the window closes while OCR is still running after the three-second wait expires, shutdown() deletes s_instance->ocrDriver and destroys ncnn GPU state while the worker is still in getRecogitionResult() or analyze(), causing use-after-free and a crash during close.

Wait for the OCR worker to finish before deleting the driver and destroying the GPU instance.

Also at src/main.cpp:89.

Prompt for AI agents
In `src/engine/OCREngine.cpp` at line 35:

**OCR cleanup races with recognition**

When the window closes while OCR is still running after the three-second wait expires, `shutdown()` deletes `s_instance->ocrDriver` and destroys ncnn GPU state while the worker is still in `getRecogitionResult()` or `analyze()`, causing use-after-free and a crash during close.

Wait for the OCR worker to finish before deleting the driver and destroying the GPU instance.

Also at `src/main.cpp:89`.

@tianming-1996
tianming-1996 force-pushed the fix/WS-4159-ncnn-gpu-teardown branch from 6208b88 to 19697f3 Compare November 9, 2026 06:05
Explicitly release the OCR driver and destroy the ncnn global Vulkan GPU
instance before main() returns. Leaving it to libncnn's __cxa_finalize
handler may run after the Vulkan ICD has been unloaded, so
vkDestroyImageView() operates on an invalid VkDevice and crashes.

fix: 进程退出时销毁 ncnn GPU 实例,修复关闭 OCR 窗口后的崩溃
在 main() 返回前先释放 OCR 驱动,再显式调用 ncnn::destroy_gpu_instance(),
避免 libncnn 在 __cxa_finalize 阶段使用已失效的 VkDevice 析构 GPU 资源。

chore: 补齐 install_dconfig.cmake 的 SPDX 版权头,修复 license-check。

Bug: https://pms.uniontech.com/bug-view-382595.html
@tianming-1996
tianming-1996 force-pushed the fix/WS-4159-ncnn-gpu-teardown branch from 19697f3 to e6c3519 Compare November 9, 2026 06:49
@deepin-ci-robot

Copy link
Copy Markdown

deepin pr auto review

🤖 AI 代码审查报告

总体评分: 95 分 (通过阈值: 70分)

Pass


📊 总体评价

项目 结果
审查结论 代码审查通过
评分详情 本次提交在进程退出前显式销毁 ncnn Vulkan GPU 实例,修复了 Vulkan ICD 先卸载导致 vkDestroyImageView() 使用失效 VkDevice 崩溃的问题。核心逻辑正确,通过 QLibrary 动态解析符号避免维护分支新增编译依赖,注释完整。存在 s_instance 未在 shutdown 后重置的轻微边界问题和 main.cpp 中少量代码重复,但不影响整体质量。无安全漏洞。

🔍 详细分析

1. 语法逻辑 ✅

评价: 语法正确,逻辑清晰 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['在 shutdown() 末尾添加 delete s_instance; s_instance = nullptr;,确保彻底清理并避免僵尸对象']


2. 代码质量 ✅

评价: 代码结构清晰,注释完整 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: ['可将 app->exec() + shutdown() + return 模式抽取为辅助函数,减少 main.cpp 中的代码重复']


3. 代码性能 ✅

评价: 性能良好,资源使用合理 ✅ 通过

潜在问题:
✅ 未发现明显问题

建议: []


4. 代码安全 🔒

评价: 存在0个安全漏洞 ✅ 通过

🔐 发现 0 个安全漏洞

安全漏洞详情:
✅ 未发现安全漏洞

建议: []


💡 改进建议代码示例

// 建议在 OCREngine::shutdown() 末尾添加 s_instance 清理: // // void OCREngine::shutdown() // { //     if (s_instance == nullptr) //         return; // //     delete s_instance->ocrDriver; //     s_instance->ocrDriver = nullptr; // //     QLibrary ncnnLib(QStringLiteral("libncnn.so.1")); //     using DestroyGpuInstance = void (*)(); //     auto destroyGpuInstance = reinterpret_cast<DestroyGpuInstance>( //                 ncnnLib.resolve(kNcnnDestroyGpuInstance)); //     if (destroyGpuInstance != nullptr) { //         destroyGpuInstance(); //     } else { //         qWarning() << "Failed to resolve ncnn::destroy_gpu_instance"; //     } // //     // 新增:彻底清理单例对象 //     delete s_instance; //     s_instance = nullptr; // }

本报告由 AI 代码审查工具自动生成

@deepin-ci-robot

Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: max-lvs, tianming-1996

The full list of commands accepted by this bot can be found here.

Details Needs approval from an approver in each of these files:

Approvers can indicate their approval by writing /approve in a comment
Approvers can cancel approval by writing /approve cancel in a comment

@tianming-1996

Copy link
Copy Markdown
Author

/merge

@deepin-bot
deepin-bot Bot merged commit 7d0e664 into linuxdeepin:release/eagle Nov 9, 2026
16 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants