Skip to content

Use C string literals and w! instead of allocs - #8474

Merged
youknowone merged 1 commit into
RustPython:mainfrom
joshuamegnauth54:use-c-w-literals
Aug 9, 2026
Merged

Use C string literals and w! instead of allocs#8474
youknowone merged 1 commit into
RustPython:mainfrom
joshuamegnauth54:use-c-w-literals

Conversation

@joshuamegnauth54

@joshuamegnauth54 joshuamegnauth54 commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Rust supports C string literals which automatically create a CStr with a trailing NUL. windows-sys provides an analogous macro for wide strings. Both of these avoid allocations which is nice for constants.

Summary

  • Use C string literals and w! more

Summary by CodeRabbit

  • Bug Fixes
    • Improved Windows string handling for file, registry, console, version, and WMI operations.
    • Invalid embedded null characters in WMI queries now return a clear validation error instead of being processed.
  • Performance & Reliability
    • Reduced unnecessary runtime string construction while preserving existing behavior and error handling.

Rust supports C string literals which automatically create a CStr with a
trailing NUL. `windows-sys` provides an analogous macro for wide
strings. Both of these avoid allocations which is nice for constants.
@coderabbitai

coderabbitai Bot commented Aug 9, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

Windows host environment code now uses compile-time wide strings for fixed Windows API arguments. Dynamic API lookup uses literal DLL and procedure names. WMI query conversion now validates embedded nulls and returns ERROR_INVALID_NAME on failure.

Changes

Windows string handling

Layer / File(s) Summary
Static Windows API strings
crates/host_env/src/nt.rs, crates/host_env/src/winapi.rs, crates/host_env/src/windows.rs
Windows imports use grouped windows_sys modules. Fixed API strings use the w! macro instead of runtime UTF-16 vectors.
Dynamic API lookup strings
crates/host_env/src/fileutils.rs
Dynamic DLL and procedure lookup uses wide and C string literals. CString is imported at module scope.
WMI query validation
crates/host_env/src/wmi.rs
Static WMI strings use w!. exec_query uses WideCString and returns ERROR_INVALID_NAME for embedded nulls.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Possibly related PRs

Suggested reviewers: youknowone

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: replacing allocated string construction with C string literals and the windows_sys w! macro.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@crates/host_env/src/wmi.rs`:
- Around line 558-560: Update the WQL query conversions in the affected query
path and the WQL BSTR construction to call WideCString::into_vec_with_nul()
rather than into_vec(), preserving the terminating u16 required by
SysAllocString through QueryThreadData.query.
🪄 Autofix

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro Plus

Run ID: c4f9810c-e162-4b9e-996a-4def34863457

📥 Commits

Reviewing files that changed from the base of the PR and between 1819677 and 125334d.

📒 Files selected for processing (5)
  • crates/host_env/src/fileutils.rs
  • crates/host_env/src/nt.rs
  • crates/host_env/src/winapi.rs
  • crates/host_env/src/windows.rs
  • crates/host_env/src/wmi.rs

Comment on lines +558 to +560
let query = WideCString::from_str(query_str)
.map_err(|_| ExecQueryError::Code(ERROR_INVALID_NAME))?
.into();

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.

🩺 Stability & Availability | 🔴 Critical | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

cargo tree -i widestring --edges normal
rg -n 'WideCString::from_str|into_vec(_with_nul)?|SysAllocString|struct QueryThreadData' \
  crates/host_env/src/wmi.rs Cargo.toml Cargo.lock

Repository: RustPython/RustPython

Length of output: 1110


🏁 Script executed:

#!/usr/bin/env bash
set -euo pipefail

sed -n '240,310p' crates/host_env/src/wmi.rs
printf '\n--- 540-590 ---\n'
sed -n '540,590p' crates/host_env/src/wmi.rs

printf '\n--- Widestring references in Cargo.lock ---\n'
rg -n 'name = "widestring"|version = "1\.' Cargo.lock || true

printf '\n--- Source docs from local wide string crate if present ---\n'
fd -a 'ucstring.rs|widestring' Cargo.lock .cargo registry 2>/dev/null | head -20

Repository: RustPython/RustPython

Length of output: 6019


🌐 Web query:

widestring 1.2.1 U16CString into_vec into_vec_with_nul documentation

💡 Result:

In the widestring crate, U16CString is an owned, mutable, nul-terminated 16-bit wide string designed for FFI [1][2][3]. The methods into_vec and into_vec_with_nul are used to consume the U16CString and convert it into a standard Rust Vec [1][4]. into_vec Converts the U16CString into a Vec without a nul terminator [1][4]. The resulting vector will contain no nul values [1]. into_vec_with_nul Converts the U16CString into a Vec including the terminating nul character [1][4]. The resulting vector will contain a nul-terminator at the end and no interior nul values [1][4]. Example usage: use widestring::U16CString; let wcstr = U16CString::from_str("example").unwrap; // Convert to Vec without nul terminator let v = wcstr.into_vec; assert_eq!(v, vec!); // Convert to Vec with nul terminator let wcvec = wcstr.into_vec_with_nul; assert_eq!(wcvec[wcvec.len-1], 0);

Citations:


Retain the WMI query NUL terminator before calling SysAllocString.

QueryThreadData.query: Vec<u16> is passed to SysAllocString(data.query.as_ptr()), so query_vec must include the terminating u16. WideCString::into() drops it via U16CString::<u16>::into_vec(); use into_vec_with_nul() when converting the WQL query string.

Also applies to the WQL Bstr construction at line 386.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@crates/host_env/src/wmi.rs` around lines 558 - 560, Update the WQL query
conversions in the affected query path and the WQL BSTR construction to call
WideCString::into_vec_with_nul() rather than into_vec(), preserving the
terminating u16 required by SysAllocString through QueryThreadData.query.

@youknowone youknowone left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

good point, thank you!

@youknowone
youknowone merged commit 3a1caa1 into RustPython:main Aug 9, 2026
27 checks passed
kyokuping pushed a commit to kyokuping/RustPython that referenced this pull request Aug 9, 2026
Rust supports C string literals which automatically create a CStr with a
trailing NUL. `windows-sys` provides an analogous macro for wide
strings. Both of these avoid allocations which is nice for constants.
@joshuamegnauth54
joshuamegnauth54 deleted the use-c-w-literals branch August 9, 2026 17:03
@coderabbitai coderabbitai Bot mentioned this pull request Aug 11, 2026
2 tasks
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.

2 participants