]> git.lizzy.rs Git - rust.git/blob - library/core/src/ffi/c_str.rs
Auto merge of #95454 - randomicon00:fix95444, r=wesleywiser
[rust.git] / library / core / src / ffi / c_str.rs
1 use crate::ascii;
2 use crate::cmp::Ordering;
3 use crate::ffi::c_char;
4 use crate::fmt::{self, Write};
5 use crate::ops;
6 use crate::slice;
7 use crate::slice::memchr;
8 use crate::str;
9
10 /// Representation of a borrowed C string.
11 ///
12 /// This type represents a borrowed reference to a nul-terminated
13 /// array of bytes. It can be constructed safely from a <code>&[[u8]]</code>
14 /// slice, or unsafely from a raw `*const c_char`. It can then be
15 /// converted to a Rust <code>&[str]</code> by performing UTF-8 validation, or
16 /// into an owned `CString`.
17 ///
18 /// `&CStr` is to `CString` as <code>&[str]</code> is to `String`: the former
19 /// in each pair are borrowed references; the latter are owned
20 /// strings.
21 ///
22 /// Note that this structure is **not** `repr(C)` and is not recommended to be
23 /// placed in the signatures of FFI functions. Instead, safe wrappers of FFI
24 /// functions may leverage the unsafe [`CStr::from_ptr`] constructor to provide
25 /// a safe interface to other consumers.
26 ///
27 /// # Examples
28 ///
29 /// Inspecting a foreign C string:
30 ///
31 /// ```ignore (extern-declaration)
32 /// use std::ffi::CStr;
33 /// use std::os::raw::c_char;
34 ///
35 /// extern "C" { fn my_string() -> *const c_char; }
36 ///
37 /// unsafe {
38 ///     let slice = CStr::from_ptr(my_string());
39 ///     println!("string buffer size without nul terminator: {}", slice.to_bytes().len());
40 /// }
41 /// ```
42 ///
43 /// Passing a Rust-originating C string:
44 ///
45 /// ```ignore (extern-declaration)
46 /// use std::ffi::{CString, CStr};
47 /// use std::os::raw::c_char;
48 ///
49 /// fn work(data: &CStr) {
50 ///     extern "C" { fn work_with(data: *const c_char); }
51 ///
52 ///     unsafe { work_with(data.as_ptr()) }
53 /// }
54 ///
55 /// let s = CString::new("data data data data").expect("CString::new failed");
56 /// work(&s);
57 /// ```
58 ///
59 /// Converting a foreign C string into a Rust `String`:
60 ///
61 /// ```ignore (extern-declaration)
62 /// use std::ffi::CStr;
63 /// use std::os::raw::c_char;
64 ///
65 /// extern "C" { fn my_string() -> *const c_char; }
66 ///
67 /// fn my_string_safe() -> String {
68 ///     unsafe {
69 ///         CStr::from_ptr(my_string()).to_string_lossy().into_owned()
70 ///     }
71 /// }
72 ///
73 /// println!("string: {}", my_string_safe());
74 /// ```
75 ///
76 /// [str]: prim@str "str"
77 #[derive(Hash)]
78 #[cfg_attr(not(test), rustc_diagnostic_item = "CStr")]
79 #[unstable(feature = "core_c_str", issue = "94079")]
80 #[cfg_attr(not(bootstrap), rustc_has_incoherent_inherent_impls)]
81 // FIXME:
82 // `fn from` in `impl From<&CStr> for Box<CStr>` current implementation relies
83 // on `CStr` being layout-compatible with `[u8]`.
84 // When attribute privacy is implemented, `CStr` should be annotated as `#[repr(transparent)]`.
85 // Anyway, `CStr` representation and layout are considered implementation detail, are
86 // not documented and must not be relied upon.
87 pub struct CStr {
88     // FIXME: this should not be represented with a DST slice but rather with
89     //        just a raw `c_char` along with some form of marker to make
90     //        this an unsized type. Essentially `sizeof(&CStr)` should be the
91     //        same as `sizeof(&c_char)` but `CStr` should be an unsized type.
92     inner: [c_char],
93 }
94
95 /// An error indicating that a nul byte was not in the expected position.
96 ///
97 /// The slice used to create a [`CStr`] must have one and only one nul byte,
98 /// positioned at the end.
99 ///
100 /// This error is created by the [`CStr::from_bytes_with_nul`] method.
101 /// See its documentation for more.
102 ///
103 /// # Examples
104 ///
105 /// ```
106 /// use std::ffi::{CStr, FromBytesWithNulError};
107 ///
108 /// let _: FromBytesWithNulError = CStr::from_bytes_with_nul(b"f\0oo").unwrap_err();
109 /// ```
110 #[derive(Clone, PartialEq, Eq, Debug)]
111 #[unstable(feature = "core_c_str", issue = "94079")]
112 pub struct FromBytesWithNulError {
113     kind: FromBytesWithNulErrorKind,
114 }
115
116 #[derive(Clone, PartialEq, Eq, Debug)]
117 enum FromBytesWithNulErrorKind {
118     InteriorNul(usize),
119     NotNulTerminated,
120 }
121
122 impl FromBytesWithNulError {
123     fn interior_nul(pos: usize) -> FromBytesWithNulError {
124         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::InteriorNul(pos) }
125     }
126     fn not_nul_terminated() -> FromBytesWithNulError {
127         FromBytesWithNulError { kind: FromBytesWithNulErrorKind::NotNulTerminated }
128     }
129
130     #[doc(hidden)]
131     #[unstable(feature = "cstr_internals", issue = "none")]
132     pub fn __description(&self) -> &str {
133         match self.kind {
134             FromBytesWithNulErrorKind::InteriorNul(..) => {
135                 "data provided contains an interior nul byte"
136             }
137             FromBytesWithNulErrorKind::NotNulTerminated => "data provided is not nul terminated",
138         }
139     }
140 }
141
142 /// An error indicating that no nul byte was present.
143 ///
144 /// A slice used to create a [`CStr`] must contain a nul byte somewhere
145 /// within the slice.
146 ///
147 /// This error is created by the [`CStr::from_bytes_until_nul`] method.
148 ///
149 #[derive(Clone, PartialEq, Eq, Debug)]
150 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
151 pub struct FromBytesUntilNulError(());
152
153 #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
154 impl fmt::Display for FromBytesUntilNulError {
155     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156         write!(f, "data provided does not contain a nul")
157     }
158 }
159
160 #[stable(feature = "cstr_debug", since = "1.3.0")]
161 impl fmt::Debug for CStr {
162     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163         write!(f, "\"")?;
164         for byte in self.to_bytes().iter().flat_map(|&b| ascii::escape_default(b)) {
165             f.write_char(byte as char)?;
166         }
167         write!(f, "\"")
168     }
169 }
170
171 #[stable(feature = "cstr_default", since = "1.10.0")]
172 impl Default for &CStr {
173     fn default() -> Self {
174         const SLICE: &[c_char] = &[0];
175         // SAFETY: `SLICE` is indeed pointing to a valid nul-terminated string.
176         unsafe { CStr::from_ptr(SLICE.as_ptr()) }
177     }
178 }
179
180 #[stable(feature = "frombyteswithnulerror_impls", since = "1.17.0")]
181 impl fmt::Display for FromBytesWithNulError {
182     #[allow(deprecated, deprecated_in_future)]
183     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184         f.write_str(self.__description())?;
185         if let FromBytesWithNulErrorKind::InteriorNul(pos) = self.kind {
186             write!(f, " at byte pos {pos}")?;
187         }
188         Ok(())
189     }
190 }
191
192 impl CStr {
193     /// Wraps a raw C string with a safe C string wrapper.
194     ///
195     /// This function will wrap the provided `ptr` with a `CStr` wrapper, which
196     /// allows inspection and interoperation of non-owned C strings. The total
197     /// size of the raw C string must be smaller than `isize::MAX` **bytes**
198     /// in memory due to calling the `slice::from_raw_parts` function.
199     /// This method is unsafe for a number of reasons:
200     ///
201     /// * There is no guarantee to the validity of `ptr`.
202     /// * The returned lifetime is not guaranteed to be the actual lifetime of
203     ///   `ptr`.
204     /// * There is no guarantee that the memory pointed to by `ptr` contains a
205     ///   valid nul terminator byte at the end of the string.
206     /// * It is not guaranteed that the memory pointed by `ptr` won't change
207     ///   before the `CStr` has been destroyed.
208     ///
209     /// > **Note**: This operation is intended to be a 0-cost cast but it is
210     /// > currently implemented with an up-front calculation of the length of
211     /// > the string. This is not guaranteed to always be the case.
212     ///
213     /// # Examples
214     ///
215     /// ```ignore (extern-declaration)
216     /// # fn main() {
217     /// use std::ffi::CStr;
218     /// use std::os::raw::c_char;
219     ///
220     /// extern "C" {
221     ///     fn my_string() -> *const c_char;
222     /// }
223     ///
224     /// unsafe {
225     ///     let slice = CStr::from_ptr(my_string());
226     ///     println!("string returned: {}", slice.to_str().unwrap());
227     /// }
228     /// # }
229     /// ```
230     #[inline]
231     #[must_use]
232     #[stable(feature = "rust1", since = "1.0.0")]
233     pub unsafe fn from_ptr<'a>(ptr: *const c_char) -> &'a CStr {
234         // SAFETY: The caller has provided a pointer that points to a valid C
235         // string with a NUL terminator of size less than `isize::MAX`, whose
236         // content remain valid and doesn't change for the lifetime of the
237         // returned `CStr`.
238         //
239         // Thus computing the length is fine (a NUL byte exists), the call to
240         // from_raw_parts is safe because we know the length is at most `isize::MAX`, meaning
241         // the call to `from_bytes_with_nul_unchecked` is correct.
242         //
243         // The cast from c_char to u8 is ok because a c_char is always one byte.
244         unsafe {
245             extern "C" {
246                 /// Provided by libc or compiler_builtins.
247                 fn strlen(s: *const c_char) -> usize;
248             }
249             let len = strlen(ptr);
250             let ptr = ptr as *const u8;
251             CStr::from_bytes_with_nul_unchecked(slice::from_raw_parts(ptr, len as usize + 1))
252         }
253     }
254
255     /// Creates a C string wrapper from a byte slice.
256     ///
257     /// This method will create a `CStr` from any byte slice that contains at
258     /// least one nul byte. The caller does not need to know or specify where
259     /// the nul byte is located.
260     ///
261     /// If the first byte is a nul character, this method will return an
262     /// empty `CStr`. If multiple nul characters are present, the `CStr` will
263     /// end at the first one.
264     ///
265     /// If the slice only has a single nul byte at the end, this method is
266     /// equivalent to [`CStr::from_bytes_with_nul`].
267     ///
268     /// # Examples
269     /// ```
270     /// #![feature(cstr_from_bytes_until_nul)]
271     ///
272     /// use std::ffi::CStr;
273     ///
274     /// let mut buffer = [0u8; 16];
275     /// unsafe {
276     ///     // Here we might call an unsafe C function that writes a string
277     ///     // into the buffer.
278     ///     let buf_ptr = buffer.as_mut_ptr();
279     ///     buf_ptr.write_bytes(b'A', 8);
280     /// }
281     /// // Attempt to extract a C nul-terminated string from the buffer.
282     /// let c_str = CStr::from_bytes_until_nul(&buffer[..]).unwrap();
283     /// assert_eq!(c_str.to_str().unwrap(), "AAAAAAAA");
284     /// ```
285     ///
286     #[unstable(feature = "cstr_from_bytes_until_nul", issue = "95027")]
287     pub fn from_bytes_until_nul(bytes: &[u8]) -> Result<&CStr, FromBytesUntilNulError> {
288         let nul_pos = memchr::memchr(0, bytes);
289         match nul_pos {
290             Some(nul_pos) => {
291                 let subslice = &bytes[..nul_pos + 1];
292                 // SAFETY: We know there is a nul byte at nul_pos, so this slice
293                 // (ending at the nul byte) is a well-formed C string.
294                 Ok(unsafe { CStr::from_bytes_with_nul_unchecked(subslice) })
295             }
296             None => Err(FromBytesUntilNulError(())),
297         }
298     }
299
300     /// Creates a C string wrapper from a byte slice.
301     ///
302     /// This function will cast the provided `bytes` to a `CStr`
303     /// wrapper after ensuring that the byte slice is nul-terminated
304     /// and does not contain any interior nul bytes.
305     ///
306     /// If the nul byte may not be at the end,
307     /// [`CStr::from_bytes_until_nul`] can be used instead.
308     ///
309     /// # Examples
310     ///
311     /// ```
312     /// use std::ffi::CStr;
313     ///
314     /// let cstr = CStr::from_bytes_with_nul(b"hello\0");
315     /// assert!(cstr.is_ok());
316     /// ```
317     ///
318     /// Creating a `CStr` without a trailing nul terminator is an error:
319     ///
320     /// ```
321     /// use std::ffi::CStr;
322     ///
323     /// let cstr = CStr::from_bytes_with_nul(b"hello");
324     /// assert!(cstr.is_err());
325     /// ```
326     ///
327     /// Creating a `CStr` with an interior nul byte is an error:
328     ///
329     /// ```
330     /// use std::ffi::CStr;
331     ///
332     /// let cstr = CStr::from_bytes_with_nul(b"he\0llo\0");
333     /// assert!(cstr.is_err());
334     /// ```
335     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
336     pub fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, FromBytesWithNulError> {
337         let nul_pos = memchr::memchr(0, bytes);
338         match nul_pos {
339             Some(nul_pos) if nul_pos + 1 == bytes.len() => {
340                 // SAFETY: We know there is only one nul byte, at the end
341                 // of the byte slice.
342                 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
343             }
344             Some(nul_pos) => Err(FromBytesWithNulError::interior_nul(nul_pos)),
345             None => Err(FromBytesWithNulError::not_nul_terminated()),
346         }
347     }
348
349     /// Unsafely creates a C string wrapper from a byte slice.
350     ///
351     /// This function will cast the provided `bytes` to a `CStr` wrapper without
352     /// performing any sanity checks. The provided slice **must** be nul-terminated
353     /// and not contain any interior nul bytes.
354     ///
355     /// # Examples
356     ///
357     /// ```
358     /// use std::ffi::{CStr, CString};
359     ///
360     /// unsafe {
361     ///     let cstring = CString::new("hello").expect("CString::new failed");
362     ///     let cstr = CStr::from_bytes_with_nul_unchecked(cstring.to_bytes_with_nul());
363     ///     assert_eq!(cstr, &*cstring);
364     /// }
365     /// ```
366     #[inline]
367     #[must_use]
368     #[stable(feature = "cstr_from_bytes", since = "1.10.0")]
369     #[rustc_const_stable(feature = "const_cstr_unchecked", since = "1.59.0")]
370     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
371         // We're in a const fn, so this is the best we can do
372         debug_assert!(!bytes.is_empty() && bytes[bytes.len() - 1] == 0);
373         // SAFETY: Calling an inner function with the same prerequisites.
374         unsafe { Self::_from_bytes_with_nul_unchecked(bytes) }
375     }
376
377     #[inline]
378     const unsafe fn _from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
379         // SAFETY: Casting to CStr is safe because its internal representation
380         // is a [u8] too (safe only inside std).
381         // Dereferencing the obtained pointer is safe because it comes from a
382         // reference. Making a reference is then safe because its lifetime
383         // is bound by the lifetime of the given `bytes`.
384         unsafe { &*(bytes as *const [u8] as *const CStr) }
385     }
386
387     /// Returns the inner pointer to this C string.
388     ///
389     /// The returned pointer will be valid for as long as `self` is, and points
390     /// to a contiguous region of memory terminated with a 0 byte to represent
391     /// the end of the string.
392     ///
393     /// **WARNING**
394     ///
395     /// The returned pointer is read-only; writing to it (including passing it
396     /// to C code that writes to it) causes undefined behavior.
397     ///
398     /// It is your responsibility to make sure that the underlying memory is not
399     /// freed too early. For example, the following code will cause undefined
400     /// behavior when `ptr` is used inside the `unsafe` block:
401     ///
402     /// ```no_run
403     /// # #![allow(unused_must_use)] #![allow(temporary_cstring_as_ptr)]
404     /// use std::ffi::CString;
405     ///
406     /// let ptr = CString::new("Hello").expect("CString::new failed").as_ptr();
407     /// unsafe {
408     ///     // `ptr` is dangling
409     ///     *ptr;
410     /// }
411     /// ```
412     ///
413     /// This happens because the pointer returned by `as_ptr` does not carry any
414     /// lifetime information and the `CString` is deallocated immediately after
415     /// the `CString::new("Hello").expect("CString::new failed").as_ptr()`
416     /// expression is evaluated.
417     /// To fix the problem, bind the `CString` to a local variable:
418     ///
419     /// ```no_run
420     /// # #![allow(unused_must_use)]
421     /// use std::ffi::CString;
422     ///
423     /// let hello = CString::new("Hello").expect("CString::new failed");
424     /// let ptr = hello.as_ptr();
425     /// unsafe {
426     ///     // `ptr` is valid because `hello` is in scope
427     ///     *ptr;
428     /// }
429     /// ```
430     ///
431     /// This way, the lifetime of the `CString` in `hello` encompasses
432     /// the lifetime of `ptr` and the `unsafe` block.
433     #[inline]
434     #[must_use]
435     #[stable(feature = "rust1", since = "1.0.0")]
436     #[rustc_const_stable(feature = "const_str_as_ptr", since = "1.32.0")]
437     pub const fn as_ptr(&self) -> *const c_char {
438         self.inner.as_ptr()
439     }
440
441     /// Converts this C string to a byte slice.
442     ///
443     /// The returned slice will **not** contain the trailing nul terminator that this C
444     /// string has.
445     ///
446     /// > **Note**: This method is currently implemented as a constant-time
447     /// > cast, but it is planned to alter its definition in the future to
448     /// > perform the length calculation whenever this method is called.
449     ///
450     /// # Examples
451     ///
452     /// ```
453     /// use std::ffi::CStr;
454     ///
455     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
456     /// assert_eq!(cstr.to_bytes(), b"foo");
457     /// ```
458     #[inline]
459     #[must_use = "this returns the result of the operation, \
460                   without modifying the original"]
461     #[stable(feature = "rust1", since = "1.0.0")]
462     pub fn to_bytes(&self) -> &[u8] {
463         let bytes = self.to_bytes_with_nul();
464         // SAFETY: to_bytes_with_nul returns slice with length at least 1
465         unsafe { bytes.get_unchecked(..bytes.len() - 1) }
466     }
467
468     /// Converts this C string to a byte slice containing the trailing 0 byte.
469     ///
470     /// This function is the equivalent of [`CStr::to_bytes`] except that it
471     /// will retain the trailing nul terminator instead of chopping it off.
472     ///
473     /// > **Note**: This method is currently implemented as a 0-cost cast, but
474     /// > it is planned to alter its definition in the future to perform the
475     /// > length calculation whenever this method is called.
476     ///
477     /// # Examples
478     ///
479     /// ```
480     /// use std::ffi::CStr;
481     ///
482     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
483     /// assert_eq!(cstr.to_bytes_with_nul(), b"foo\0");
484     /// ```
485     #[inline]
486     #[must_use = "this returns the result of the operation, \
487                   without modifying the original"]
488     #[stable(feature = "rust1", since = "1.0.0")]
489     pub fn to_bytes_with_nul(&self) -> &[u8] {
490         // SAFETY: Transmuting a slice of `c_char`s to a slice of `u8`s
491         // is safe on all supported targets.
492         unsafe { &*(&self.inner as *const [c_char] as *const [u8]) }
493     }
494
495     /// Yields a <code>&[str]</code> slice if the `CStr` contains valid UTF-8.
496     ///
497     /// If the contents of the `CStr` are valid UTF-8 data, this
498     /// function will return the corresponding <code>&[str]</code> slice. Otherwise,
499     /// it will return an error with details of where UTF-8 validation failed.
500     ///
501     /// [str]: prim@str "str"
502     ///
503     /// # Examples
504     ///
505     /// ```
506     /// use std::ffi::CStr;
507     ///
508     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").expect("CStr::from_bytes_with_nul failed");
509     /// assert_eq!(cstr.to_str(), Ok("foo"));
510     /// ```
511     #[stable(feature = "cstr_to_str", since = "1.4.0")]
512     pub fn to_str(&self) -> Result<&str, str::Utf8Error> {
513         // N.B., when `CStr` is changed to perform the length check in `.to_bytes()`
514         // instead of in `from_ptr()`, it may be worth considering if this should
515         // be rewritten to do the UTF-8 check inline with the length calculation
516         // instead of doing it afterwards.
517         str::from_utf8(self.to_bytes())
518     }
519 }
520
521 #[stable(feature = "rust1", since = "1.0.0")]
522 impl PartialEq for CStr {
523     fn eq(&self, other: &CStr) -> bool {
524         self.to_bytes().eq(other.to_bytes())
525     }
526 }
527 #[stable(feature = "rust1", since = "1.0.0")]
528 impl Eq for CStr {}
529 #[stable(feature = "rust1", since = "1.0.0")]
530 impl PartialOrd for CStr {
531     fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
532         self.to_bytes().partial_cmp(&other.to_bytes())
533     }
534 }
535 #[stable(feature = "rust1", since = "1.0.0")]
536 impl Ord for CStr {
537     fn cmp(&self, other: &CStr) -> Ordering {
538         self.to_bytes().cmp(&other.to_bytes())
539     }
540 }
541
542 #[stable(feature = "cstr_range_from", since = "1.47.0")]
543 impl ops::Index<ops::RangeFrom<usize>> for CStr {
544     type Output = CStr;
545
546     fn index(&self, index: ops::RangeFrom<usize>) -> &CStr {
547         let bytes = self.to_bytes_with_nul();
548         // we need to manually check the starting index to account for the null
549         // byte, since otherwise we could get an empty string that doesn't end
550         // in a null.
551         if index.start < bytes.len() {
552             // SAFETY: Non-empty tail of a valid `CStr` is still a valid `CStr`.
553             unsafe { CStr::from_bytes_with_nul_unchecked(&bytes[index.start..]) }
554         } else {
555             panic!(
556                 "index out of bounds: the len is {} but the index is {}",
557                 bytes.len(),
558                 index.start
559             );
560         }
561     }
562 }
563
564 #[stable(feature = "cstring_asref", since = "1.7.0")]
565 impl AsRef<CStr> for CStr {
566     #[inline]
567     fn as_ref(&self) -> &CStr {
568         self
569     }
570 }