Skip to content

Commit c87ba3f

Browse files
authored
Auto merge of #36264 - matklad:zeroing-cstring, r=alexcrichton
Zero first byte of CString on drop Hi! This is one more attempt to ameliorate `CString::new("...").unwrap().as_ptr()` problem (related RFC: rust-lang/rfcs#1642). One of the biggest problems with this code is that it may actually work in practice, so the idea of this PR is to proactively break such invalid code. Looks like writing a `null` byte at the start of the CString should do the trick, and I think is an affordable cost: zeroing a single byte in `Drop` should be cheap enough compared to actual memory deallocation which would follow. I would actually prefer to do something like ```Rust impl Drop for CString { fn drop(&mut self) { let pattern = b"CTHULHU FHTAGN "; let bytes = self.inner[..self.inner.len() - 1]; for (d, s) in bytes.iter_mut().zip(pattern.iter().cycle()) { *d = *s; } } } ``` because Cthulhu error should be much easier to google, but unfortunately this would be too expensive in release builds, and we can't implement things `cfg(debug_assertions)` conditionally in stdlib. Not sure if the whole idea or my implementation (I've used ~~`transmute`~~ `mem::unitialized` to workaround move out of Drop thing) makes sense :)
2 parents 58450c0 + f9a3408 commit c87ba3f

File tree

2 files changed

+74
-3
lines changed

2 files changed

+74
-3
lines changed

src/libstd/ffi/c_str.rs

+25-3
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ use mem;
1919
use memchr;
2020
use ops;
2121
use os::raw::c_char;
22+
use ptr;
2223
use slice;
2324
use str::{self, Utf8Error};
2425

@@ -68,6 +69,9 @@ use str::{self, Utf8Error};
6869
#[derive(PartialEq, PartialOrd, Eq, Ord, Hash, Clone)]
6970
#[stable(feature = "rust1", since = "1.0.0")]
7071
pub struct CString {
72+
// Invariant 1: the slice ends with a zero byte and has a length of at least one.
73+
// Invariant 2: the slice contains only one zero byte.
74+
// Improper usage of unsafe function can break Invariant 2, but not Invariant 1.
7175
inner: Box<[u8]>,
7276
}
7377

@@ -244,7 +248,7 @@ impl CString {
244248
/// Failure to call `from_raw` will lead to a memory leak.
245249
#[stable(feature = "cstr_memory", since = "1.4.0")]
246250
pub fn into_raw(self) -> *mut c_char {
247-
Box::into_raw(self.inner) as *mut c_char
251+
Box::into_raw(self.into_inner()) as *mut c_char
248252
}
249253

250254
/// Converts the `CString` into a `String` if it contains valid Unicode data.
@@ -265,7 +269,7 @@ impl CString {
265269
/// it is guaranteed to not have any interior nul bytes.
266270
#[stable(feature = "cstring_into", since = "1.7.0")]
267271
pub fn into_bytes(self) -> Vec<u8> {
268-
let mut vec = self.inner.into_vec();
272+
let mut vec = self.into_inner().into_vec();
269273
let _nul = vec.pop();
270274
debug_assert_eq!(_nul, Some(0u8));
271275
vec
@@ -275,7 +279,7 @@ impl CString {
275279
/// includes the trailing nul byte.
276280
#[stable(feature = "cstring_into", since = "1.7.0")]
277281
pub fn into_bytes_with_nul(self) -> Vec<u8> {
278-
self.inner.into_vec()
282+
self.into_inner().into_vec()
279283
}
280284

281285
/// Returns the contents of this `CString` as a slice of bytes.
@@ -293,6 +297,24 @@ impl CString {
293297
pub fn as_bytes_with_nul(&self) -> &[u8] {
294298
&self.inner
295299
}
300+
301+
// Bypass "move out of struct which implements `Drop` trait" restriction.
302+
fn into_inner(self) -> Box<[u8]> {
303+
unsafe {
304+
let result = ptr::read(&self.inner);
305+
mem::forget(self);
306+
result
307+
}
308+
}
309+
}
310+
311+
// Turns this `CString` into an empty string to prevent
312+
// memory unsafe code from working by accident.
313+
#[stable(feature = "cstring_drop", since = "1.13.0")]
314+
impl Drop for CString {
315+
fn drop(&mut self) {
316+
unsafe { *self.inner.get_unchecked_mut(0) = 0; }
317+
}
296318
}
297319

298320
#[stable(feature = "rust1", since = "1.0.0")]

src/test/run-pass/cstring-drop.rs

+49
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2+
// file at the top-level directory of this distribution and at
3+
// http://rust-lang.org/COPYRIGHT.
4+
//
5+
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6+
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7+
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8+
// option. This file may not be copied, modified, or distributed
9+
// except according to those terms.
10+
11+
// ignore-emscripten
12+
13+
// Test that `CString::new("hello").unwrap().as_ptr()` pattern
14+
// leads to failure.
15+
16+
use std::env;
17+
use std::ffi::{CString, CStr};
18+
use std::os::raw::c_char;
19+
use std::process::{Command, Stdio};
20+
21+
fn main() {
22+
let args: Vec<String> = env::args().collect();
23+
if args.len() > 1 && args[1] == "child" {
24+
// Repeat several times to be more confident that
25+
// it is `Drop` for `CString` that does the cleanup,
26+
// and not just some lucky UB.
27+
let xs = vec![CString::new("Hello").unwrap(); 10];
28+
let ys = xs.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
29+
drop(xs);
30+
assert!(ys.into_iter().any(is_hello));
31+
return;
32+
}
33+
34+
let output = Command::new(&args[0]).arg("child").output().unwrap();
35+
assert!(!output.status.success());
36+
}
37+
38+
fn is_hello(s: *const c_char) -> bool {
39+
// `s` is a dangling pointer and reading it is technically
40+
// undefined behavior. But we want to prevent the most diabolical
41+
// kind of UB (apart from nasal demons): reading a value that was
42+
// previously written.
43+
//
44+
// Segfaulting or reading an empty string is Ok,
45+
// reading "Hello" is bad.
46+
let s = unsafe { CStr::from_ptr(s) };
47+
let hello = CString::new("Hello").unwrap();
48+
s == hello.as_ref()
49+
}

0 commit comments

Comments
 (0)