Movatterモバイル変換


[0]ホーム

URL:


CodeQL documentation
CodeQL resources

Bad ‘ctor’ initialization

ID: rust/ctor-initializationKind: path-problemSecurity severity: Severity: errorPrecision: highTags:   - reliability   - correctness   - external/cwe/cwe-696   - external/cwe/cwe-665Query suites:   - rust-security-and-quality.qls

Click to see the query in the CodeQL repository

Calling functions and methods in the Ruststd library from a#[ctor] or#[dtor] function is not safe. This is because thestd library only guarantees stability and portability between the beginning and the end ofmain, whereas#[ctor] functions are called beforemain, and#[dtor] functions are called after it.

Recommendation

Do not call any part of thestd library from a#[ctor] or#[dtor] function. Instead either:

  • Move the code to a different location, such as inside your program’smain function.

  • Rewrite the code using an alternative library.

Example

In the following example, a#[ctor] function uses theprintln! macro which callsstd library functions. This may cause unexpected behavior at runtime.

#[ctor::ctor]fnbad_example(){println!("Hello, world!");// BAD: the println! macro calls std library functions}

The issue can be fixed by replacingprintln! with something that does not rely on thestd library. In the fixed code below, we used thelibc_println! macro from thelibc-print library:

#[ctor::ctor]fngood_example(){libc_print::libc_println!("Hello, world!");// GOOD: libc-print does not use the std library}

References


[8]ページ先頭

©2009-2025 Movatter.jp