Skip to content

Commit 82f2c60

Browse files
committed
Rust: Add qhelp + examples.
1 parent 88fc7be commit 82f2c60

File tree

3 files changed

+54
-0
lines changed

3 files changed

+54
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
<!DOCTYPE qhelp PUBLIC
2+
"-//Semmle//qhelp//EN"
3+
"qhelp.dtd">
4+
<qhelp>
5+
<overview>
6+
7+
<p>
8+
Calling functions and methods in the Rust <code>std</code> library from a <code>#[ctor]</code> or <code>#[dtor]<code> function is not safe. This is because the <code>std</code> library only guarantees stability and portability between the beginning and end of <code>main</code>, whereas <code>#[ctor]</code> functions are called before <code>main</code>, and <code>#[dtor]</code> functions are called after it.
9+
</p>
10+
11+
</overview>
12+
<recommendation>
13+
14+
<p>
15+
Do not call any part of the <code>std</code> library from a <code>#[ctor]</code> or <code>#[dtor]<code> function. Instead either:
16+
</p>
17+
<ul>
18+
<li>Move the code to a different location, such as inside your program's <code>main</code> function.</li>
19+
<li>Rewrite the code using an alternative library.</li>
20+
</ul>
21+
22+
</recommendation>
23+
<example>
24+
25+
<p>
26+
In the following example, a <code>#[ctor]</code> function uses the <code>println!</code> macro which calls <code>std</code> library functions. This may cause unexpected behaviour at runtime.
27+
</p>
28+
29+
<sample src="BadCtorInitializationBad.rs" />
30+
31+
<p>
32+
The issue can be fixed by replacing <code>println!</code> with something that does not rely on the <code>std</code> library. In the fixed code below we use the <code>libc_println!</code> macro from the <code>libc-print</code> library:
33+
</p>
34+
35+
<sample src="BadCtorInitializationGood.rs" />
36+
37+
</example>
38+
<references>
39+
40+
<li>GitHub: <a href="https://github.com/mmastrac/rust-ctor?tab=readme-ov-file#warnings">rust-ctor - Warnings</a>.</li>
41+
<li>Rust Programming Language: <a href="https://doc.rust-lang.org/std/#use-before-and-after-main">Crate std - Use before and after main()</a>.</li>
42+
43+
</references>
44+
</qhelp>
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
#[ctor::ctor]
3+
fn bad_example() {
4+
println!("Hello, world!"); // BAD: the println! macro calls std library functions
5+
}
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
2+
#[ctor::ctor]
3+
fn good_example() {
4+
libc_print::libc_println!("Hello, world!"); // GOOD: libc-print does not use the std library
5+
}

0 commit comments

Comments
 (0)