Skip to content

fix: improve XOrg display handling#1623

Merged
dengbo11 merged 1 commit intoOpenAtom-Linyaps:masterfrom
reddevillg:fix_xdisplay
Mar 21, 2026
Merged

fix: improve XOrg display handling#1623
dengbo11 merged 1 commit intoOpenAtom-Linyaps:masterfrom
reddevillg:fix_xdisplay

Conversation

@reddevillg
Copy link
Copy Markdown
Collaborator

  • Parse protocol/hostname/display/screen from DISPLAY environment variable
  • Add unit tests for display parsing edge cases

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the handling of XOrg display configurations by introducing a more robust and structured parsing mechanism for the DISPLAY environment variable. The changes improve the accuracy and flexibility of identifying XOrg display parameters, which is crucial for applications interacting with the X Window System. This refactoring also includes comprehensive unit tests to ensure the reliability of the new parsing logic.

Highlights

  • Refactored XOrg Display Parsing: The getXOrgDisplay function has been significantly refactored to return a structured XOrgDisplayConf object, providing detailed information about the XOrg display configuration including protocol, host, display number, and screen number. This replaces the previous approach of returning a simple filesystem path.
  • Enhanced DISPLAY Environment Variable Parsing: Implemented comprehensive parsing logic for the DISPLAY environment variable, supporting various formats such as unix:, absolute paths, and [protocol/][host]:display[.screen]. This improves the robustness and flexibility of XOrg display detection.
  • Comprehensive Unit Tests for Display Parsing: A new unit test file (display_test.cpp) has been added with extensive test cases to validate the parsing of XOrg display configurations, covering a wide range of valid and invalid scenarios to ensure reliability.
  • Updated Container Configuration Builder: The ContainerCfgBuilder has been updated to leverage the new XOrgDisplayConf structure for configuring XOrg display mounts. This includes special handling for abstract Unix sockets and remapping display numbers for container environments.
  • Streamlined Display Binding API: The bindXOrgSocket method and its corresponding member variable have been removed from ContainerCfgBuilder, streamlining the display configuration process by directly parsing the DISPLAY environment variable within the builder's logic.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request significantly refactors the handling of XOrg display configurations by introducing a structured XOrgDisplayConf object to parse the DISPLAY environment variable. The getXOrgDisplay function has been updated to provide a more detailed and robust parsing of display strings, including various protocols, hosts, display numbers, and screen numbers. Comprehensive unit tests have been added to cover a wide range of display string formats and edge cases, which greatly improves the reliability of display parsing. The ContainerCfgBuilder has been adapted to utilize this new structured information for setting up appropriate mounts and environment variables within the container, removing the previous bindXOrgSocket method. Overall, these changes enhance the flexibility and correctness of XOrg display integration.

} else {
displayNo = xOrgDisplayConf->displayNo;
source = fmt::format("/tmp/.X11-unix/X{}", displayNo);
environment["DISPLAY"] = display;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

high

The environment["DISPLAY"] = display; assignment here might lead to inconsistent behavior. If the original display string (e.g., tcp/localhost:0) was parsed by getXOrgDisplay and the else branch is taken, the code proceeds to bind a local Unix socket (/tmp/.X11-unix/X{displayNo}). However, the DISPLAY environment variable inside the container is then set back to the original tcp/localhost:0. This could cause applications within the container to attempt a TCP/IP connection instead of using the bound local Unix socket, potentially breaking XOrg functionality. The DISPLAY environment variable should reflect the actual connection method being used by the container.

                environment["DISPLAY"] = fmt::format(":{}", displayNo);

- Parse protocol/hostname/display/screen from DISPLAY environment variable
- Add unit tests for display parsing edge cases

Signed-off-by: reddevillg <reddevillg@gmail.com>
@deepin-ci-robot
Copy link
Copy Markdown
Collaborator

deepin pr auto review

Git Diff 代码审查报告

总体评价

这段代码主要对显示系统(X11)的配置解析和挂载逻辑进行了重构,将原来简单的路径解析改为更完善的配置解析,增加了对多种显示格式的支持。整体代码质量较好,但有一些可以改进的地方。

具体问题与建议

1. 语法与逻辑问题

display.cpp 中的字符串处理

// 第45行
if (common::strings::starts_with(display, unixPrefix)) {
    display = display.substr(unixPrefix.size());
}

问题: displaystd::string_view 类型,多次 substr 操作可能导致性能问题,且如果原始字符串生命周期较短,可能产生悬垂引用。

建议: 考虑使用 std::string 或确保原始字符串生命周期足够长。

display.cpp 中的异常处理

// 第67-73行
try {
    result.screenNo = std::stoi(std::string(display.substr(dot + 1)));
    if (result.screenNo < 0) {
        return LINGLONG_ERR(fmt::format("invalid screen No: {}", result.screenNo));
    }
} catch (const std::exception &e) {
    return LINGLONG_ERR(fmt::format("failed to get screen No: {}", e.what()));
}

问题: std::stoi 可能抛出 std::out_of_rangestd::invalid_argument,但这里只捕获了 std::exception,虽然这是基类,但最好明确捕获特定异常。

建议: 明确捕获 std::invalid_argumentstd::out_of_range

2. 代码质量问题

display.h 中的结构体设计

struct XOrgDisplayConf
{
    std::optional<std::string> protocol;
    std::optional<std::string> host;
    int displayNo;
    int screenNo;
};

问题:

  1. displayNoscreenNo 使用 int 类型,但没有明确其有效范围
  2. 结构体缺少构造函数,可能导致未初始化的成员

建议:

struct XOrgDisplayConf
{
    std::optional<std::string> protocol;
    std::optional<std::string> host;
    int displayNo = 0;  // 默认值
    int screenNo = 0;  // 默认值
    
    // 添加验证方法
    bool isValid() const noexcept {
        return displayNo >= 0 && screenNo >= 0;
    }
};

display.cpp 中的重复代码

// 第67-73行和第93-103行有类似的异常处理逻辑

建议: 提取公共的异常处理逻辑为辅助函数。

3. 代码性能问题

display.cpp 中的字符串转换

// 第93行
result.displayNo = std::stoi(std::string(display), &s);

问题: 每次调用 std::stoi 都需要将 string_view 转换为 string,可能影响性能。

建议: 考虑使用 std::from_chars (C++17) 直接处理 string_view,避免临时字符串创建:

int value;
auto [ptr, ec] = std::from_chars(display.data(), display.data() + display.size(), value);
if (ec != std::errc()) {
    return LINGLONG_ERR(fmt::format("failed to parse display number"));
}

4. 代码安全问题

display.cpp 中的路径处理

// 第48行
if (std::filesystem::exists(display, ec)) {
    result.host = display;
    return result;
}

问题: 直接使用用户提供的路径,没有进行路径规范化或验证,可能导致路径遍历攻击。

建议: 添加路径验证逻辑:

auto normalizedPath = std::filesystem::canonical(display, ec);
if (ec) {
    return LINGLONG_ERR(fmt::format("invalid path: {}", ec.message()));
}
// 检查路径是否在允许的目录内
if (!isPathAllowed(normalizedPath)) {
    return LINGLONG_ERR(fmt::format("path not allowed: {}", display));
}

container_cfg_builder.cpp 中的环境变量处理

// 第1028行
if (auto *display = ::getenv("DISPLAY"); display != nullptr) {
    auto xOrgDisplayConf = common::display::getXOrgDisplay(display);

问题: 直接使用环境变量,没有验证其格式或长度,可能导致缓冲区溢出或其他问题。

建议: 添加环境变量验证:

if (auto *display = ::getenv("DISPLAY"); display != nullptr) {
    // 验证环境变量长度
    if (std::strlen(display) > MAX_DISPLAY_LENGTH) {
        LogW("DISPLAY environment variable too long, ignoring");
        return false;
    }
    auto xOrgDisplayConf = common::display::getXOrgDisplay(display);

5. 测试覆盖问题

display_test.cpp 中的测试用例

TEST(DisplayTest, GetXOrgDisplay_IPv6Address)
{
    auto result = getXOrgDisplay("[2001:db8::1]:0");
    ASSERT_TRUE(result.has_value());
    EXPECT_EQ(result->host.value(), "[2001:db8::1]");
    // ...
}

问题: 测试用例中缺少对错误情况的充分测试,特别是边界条件和异常情况。

建议: 增加以下测试用例:

  1. 超长字符串输入
  2. 特殊字符输入
  3. 空格处理
  4. 大小写混合的协议名
  5. 无效的IPv6地址格式

其他建议

  1. 文档注释: 为 XOrgDisplayConf 结构体和 getXOrgDisplay 函数添加详细的文档注释,说明参数格式和返回值含义。

  2. 常量定义: 将魔法数字(如1000)定义为命名常量:

constexpr int ABSTRACT_SOCKET_DISPLAY_NUMBER = 1000;
  1. 日志记录: 在关键操作处添加更详细的日志记录,便于调试。

  2. 错误处理: 统一错误处理方式,确保所有错误路径都有适当的处理和日志记录。

总结

这段代码整体质量较好,重构了显示系统配置解析逻辑,增加了对多种显示格式的支持。主要需要改进的地方包括:

  1. 加强字符串处理的安全性和性能
  2. 完善错误处理和验证逻辑
  3. 增加测试覆盖率
  4. 改进代码结构和可维护性

建议在合并前进行更全面的测试,特别是针对边界条件和异常情况的测试。

@codecov
Copy link
Copy Markdown

codecov bot commented Mar 21, 2026

Codecov Report

❌ Patch coverage is 39.70588% with 41 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
...glong/oci-cfg-generators/container_cfg_builder.cpp 0.00% 22 Missing ⚠️
libs/common/src/linglong/common/display.cpp 58.69% 7 Missing and 12 partials ⚠️
Files with missing lines Coverage Δ
libs/linglong/src/linglong/runtime/run_context.cpp 4.03% <ø> (+0.09%) ⬆️
...inglong/oci-cfg-generators/container_cfg_builder.h 0.00% <ø> (ø)
libs/common/src/linglong/common/display.cpp 38.15% <58.69%> (+38.15%) ⬆️
...glong/oci-cfg-generators/container_cfg_builder.cpp 0.00% <0.00%> (ø)
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@reddevillg reddevillg requested a review from dengbo11 March 21, 2026 04:37
@deepin-ci-robot
Copy link
Copy Markdown
Collaborator

[APPROVALNOTIFIER] This PR is NOT APPROVED

This pull-request has been approved by: dengbo11, reddevillg

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

@dengbo11 dengbo11 merged commit 48d652b into OpenAtom-Linyaps:master Mar 21, 2026
17 checks passed
@reddevillg reddevillg deleted the fix_xdisplay branch March 21, 2026 08:05
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