Skip to content

Fix(battery): get battery info error.#660

Closed
GongHeng2017 wants to merge 1 commit into
linuxdeepin:masterfrom
GongHeng2017:202605141138-master-fix
Closed

Fix(battery): get battery info error.#660
GongHeng2017 wants to merge 1 commit into
linuxdeepin:masterfrom
GongHeng2017:202605141138-master-fix

Conversation

@GongHeng2017
Copy link
Copy Markdown
Contributor

@GongHeng2017 GongHeng2017 commented May 14, 2026

-- In Qt 6, when using QProcess::start(), you must separate the program name from the argument list for the command to execute correctly.

Log: fix issue
Bug: https://pms.uniontech.com/bug-view-361071.html

Summary by Sourcery

Bug Fixes:

  • Resolve failure to obtain battery information by correctly separating the upower program name and its arguments when starting the QProcess in Qt 6.

-- In Qt 6, when using QProcess::start(), you must separate the program name from the argument list for the command to execute correctly.

Log: fix issue
Bug: https://pms.uniontech.com/bug-view-361071.html
@deepin-ci-robot
Copy link
Copy Markdown

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: GongHeng2017

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

@sourcery-ai
Copy link
Copy Markdown

sourcery-ai Bot commented May 14, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Updates the battery info retrieval to use QProcess::start() with a separate program and argument list, ensuring the upower --dump command executes correctly under Qt 6.

Sequence diagram for updated battery info retrieval using QProcess

sequenceDiagram
    participant CmdTool
    participant QProcess
    participant upower

    CmdTool->>QProcess: start("upower", QStringList() << "--dump")
    QProcess->>upower: execute upower --dump
    QProcess-->>CmdTool: waitForFinished(-1)
    QProcess-->>CmdTool: readAllStandardOutput()
Loading

File-Level Changes

Change Details Files
Fix QProcess invocation so upower --dump runs correctly under Qt 6 when fetching current power information.
  • Move QProcess instantiation closer to its use in getCurPowerInfo().
  • Replace single-string process.start(cmd) call with process.start("upower", QStringList() << "--dump") to pass program and arguments separately.
  • Remove the intermediate QString cmd = "upower --dump"; variable as it is no longer needed.
deepin-devicemanager/src/GenerateDevice/CmdTool.cpp

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

Copy link
Copy Markdown

@sourcery-ai sourcery-ai Bot left a comment

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, and left some high level feedback:

  • Consider using a finite timeout in waitForFinished() and checking its return value to avoid potential hangs if upower blocks or never completes.
  • It may be helpful to log or handle process.error() and stderr output when upower fails, so battery info failures can be diagnosed more easily.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- Consider using a finite timeout in `waitForFinished()` and checking its return value to avoid potential hangs if `upower` blocks or never completes.
- It may be helpful to log or handle `process.error()` and stderr output when `upower` fails, so battery info failures can be diagnosed more easily.

## Individual Comments

### Comment 1
<location path="deepin-devicemanager/src/GenerateDevice/CmdTool.cpp" line_range="1322" />
<code_context>
-    process.start(cmd);
-
+    QProcess process;
+    process.start("upower", QStringList() << "--dump");
     // 获取命令执行结果
     process.waitForFinished(-1);
</code_context>
<issue_to_address>
**issue:** Consider handling QProcess start/finish failures and exit codes.

`start()` and `waitForFinished(-1)` are used without checking whether the process actually started or exited successfully. Since this drives system power information, please verify `process.error() == QProcess::UnknownError` after `start()` and check `process.exitStatus()` / `process.exitCode()` after `waitForFinished()` so you don’t proceed with invalid `powerInfo` when `upower` is missing or fails.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

process.start(cmd);

QProcess process;
process.start("upower", QStringList() << "--dump");
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

issue: Consider handling QProcess start/finish failures and exit codes.

start() and waitForFinished(-1) are used without checking whether the process actually started or exited successfully. Since this drives system power information, please verify process.error() == QProcess::UnknownError after start() and check process.exitStatus() / process.exitCode() after waitForFinished() so you don’t proceed with invalid powerInfo when upower is missing or fails.

@deepin-ci-robot
Copy link
Copy Markdown

deepin pr auto review

你好!我是CodeGeeX。我已仔细审查了你提供的Git Diff代码。本次修改主要是对 QProcess 的启动方式进行了重构,将带参数的完整字符串改为了程序名与参数列表分离的方式。

总体来说,这次修改的方向是非常正确的,显著提升了代码的安全性和健壮性。以下是针对各个维度的详细审查意见和改进建议:

1. 代码安全 - ⭐⭐⭐⭐⭐ (提升显著)

  • 原代码问题process.start("upower --dump") 将命令和参数混在一个字符串中,如果参数中包含用户输入或不可信的数据,极易引发命令注入风险。同时,这种形式依赖于底层操作系统的 Shell 解析(QProcess 会隐式启动 /bin/sh -c),存在 Shell 特殊字符(如 ;, |, $())被恶意利用的漏洞。
  • 新代码改进process.start("upower", QStringList() << "--dump") 采用了参数分离的方式。此时 QProcess直接启动目标程序,绕过了 Shell 解析,从根本上杜绝了命令注入的可能性。
  • 建议:保持当前的修改,这是处理外部进程启动的最佳安全实践。

2. 语法逻辑 - ⭐⭐⭐⭐ (良好,但有改进空间)

  • 新代码逻辑:使用 QStringList() << "--dump" 传递参数,逻辑清晰,符合 Qt 的 API 规范。
  • 潜在问题process.waitForFinished(-1) 会无限期阻塞当前线程。如果 upower 命令因为某种原因挂起(例如等待 I/O 或系统死锁),会导致当前线程(很可能是 UI 线程)永久卡死,引发应用“未响应”。
  • 改进建议:设置一个合理的超时时间(例如 5000 毫秒),并检查执行结果。

3. 代码性能 - ⭐⭐⭐ (需优化)

  • 问题 1:阻塞调用:如上所述,waitForFinished(-1) 是同步阻塞的,这在图形界面应用程序中是极其忌讳的,会严重影响用户体验和事件循环的处理。
  • 问题 2:缺少错误处理:如果系统没有安装 upower,或者执行失败,当前代码依然会读取输出(空字符串)并继续后续逻辑,可能引发下游逻辑错误。
  • 改进建议
    1. 短期优化:为 waitForFinished 添加超时时间,并判断进程退出码。
    2. 长期优化:如果此函数在主线程调用,强烈建议重构为异步方式(使用 QProcess::start 不带 waitForFinished,连接 finished 信号到槽函数处理结果)。

4. 代码质量 - ⭐⭐⭐⭐ (优秀,细节可微调)

  • 优点:将 QProcess process; 的声明移至使用前,缩小了变量的作用域,符合最小作用域原则,代码更整洁。
  • 可读性微调QStringList() << "--dump" 是 Qt4/早期Qt5 的写法。在现代 C++ (C++11及以上) 中,使用初始化列表 {"--dump"} 更加简洁直观。
  • 资源管理:虽然 QProcess 作为局部变量在函数结束时会自动析构,但在某些极端情况(如进程启动但未正常退出)下,建议显式确保进程被关闭。

💡 综合改进后的代码建议

结合以上分析,我为你提供一版改进后的代码,修复了潜在的阻塞问题,增加了错误处理,并提升了代码的现代感:

QMap<QString, QMap<QString, QString>> CmdTool::getCurPowerInfo()
{
    qCDebug(appLog) << "Getting current power info from upower.";
    QString powerInfo;
    QMap<QString, QMap<QString, QString>> map;

    QProcess process;
    // 改进1:使用现代 C++ 初始化列表,更简洁
    process.start("upower", {"--dump"});

    // 改进2:设置合理的超时时间(例如 5 秒),避免无限期阻塞主线程
    if (!process.waitForFinished(5000)) {
        qCWarning(appLog) << "Failed to execute upower or timeout:" << process.errorString();
        process.kill(); // 确保进程被终止
        process.waitForFinished(); // 等待清理完成
        return map; // 返回空 map 或根据业务逻辑处理错误
    }

    // 改进3:检查进程退出码,确保命令执行成功
    if (process.exitStatus() != QProcess::NormalExit || process.exitCode() != 0) {
        qCWarning(appLog) << "upower command exited with error, code:" << process.exitCode();
        return map;
    }

    // 获取命令执行结果
    powerInfo = process.readAllStandardOutput();

    // ... 后续解析逻辑 ...
    return map;
}

总结:你的原始 Diff 修改已经解决了一个核心的安全隐患(命令注入),是非常棒的改进。在此基础上,通过增加超时控制和退出状态检查,可以让代码在生产环境中更加健壮和可靠。

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