CodeQL documentation

Bad ‘ctor’ initialization

ID: rust/ctor-initialization
Kind: path-problem
Security severity: 
Severity: error
Precision: high
Tags:
   - reliability
   - correctness
   - external/cwe/cwe-696
   - external/cwe/cwe-665
Query suites:
   - rust-security-and-quality.qls

Click to see the query in the CodeQL repository

Calling functions and methods in the Rust std library from a #[ctor] or #[dtor] function is not safe. This is because the std library only guarantees stability and portability between the beginning and the end of main, whereas #[ctor] functions are called before main, and #[dtor] functions are called after it.

Recommendation

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

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

  • Rewrite the code using an alternative library.

Example

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

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

The issue can be fixed by replacing println! with something that does not rely on the std library. In the fixed code below, we used the libc_println! macro from the libc-print library:

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

References

  • © GitHub, Inc.
  • Terms
  • Privacy
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy