mirror of
https://github.com/allankoechke/rust.git
synced 2026-11-30 11:05:36 +00:00
Auto merge of #161196 - JonathanBrouwer:rollup-JHCyFaw, r=JonathanBrouwer
Rollup of 17 pull requests Successful merges: - rust-lang/rust#161017 (Library: enforce clippy deref lints in CI) - rust-lang/rust#160416 (std: fix unix socket address truncation without a trailing NUL) - rust-lang/rust#161006 ([CI] Build newer `binutils` before building `gcc`) - rust-lang/rust#161141 (Add documentation for BPF targets) - rust-lang/rust#161157 (bootstrap: Move several items out of the crate root) - rust-lang/rust#161185 (std: guard against unwinds in queue-based `Once`) - rust-lang/rust#161186 (miri subtree update) - rust-lang/rust#159855 (std: retry waitid on EINTR in the pidfd wait path) - rust-lang/rust#160478 (diagnostics: Suggest fn binding type for unstable closure for<> binders) - rust-lang/rust#161053 (Add regression test for borrow of array drop type in const) - rust-lang/rust#161073 (Add regression test for path printing with infinitely many visible names) - rust-lang/rust#161099 (Add regression test for unstable def_ident_span fingerprint with incremental recompilation) - rust-lang/rust#161103 (cleanup: rip out unnecessary `iter().last()` and `iter().next()`) - rust-lang/rust#161136 (Add BPF test for Rust ABI stack arguments) - rust-lang/rust#161146 (Switch to c8a EC2 runner for auto merges) - rust-lang/rust#161148 ([rustdoc] Put back one removed flaky GUI test (which hopefully isn't flaky anymore)) - rust-lang/rust#161181 (Add back flaky gui rustdoc test `tests/rustdoc-gui/headers-color.goml`)
This commit is contained in:
@@ -1180,7 +1180,7 @@ impl<'a> AstValidator<'a> {
|
||||
self.dcx().emit_err(diagnostics::ArgsBeforeConstraint {
|
||||
arg_spans: arg_spans.clone(),
|
||||
constraints: constraint_spans[0],
|
||||
args: *arg_spans.iter().last().unwrap(),
|
||||
args: *arg_spans.last().unwrap(),
|
||||
data: data.span,
|
||||
constraint_spans: diagnostics::EmptyLabelManySpans(constraint_spans),
|
||||
arg_spans2: diagnostics::EmptyLabelManySpans(arg_spans),
|
||||
|
||||
@@ -505,7 +505,8 @@ pub fn check_crate(krate: &ast::Crate, sess: &Session, features: &Features) {
|
||||
gate_all!(
|
||||
closure_lifetime_binder,
|
||||
"`for<...>` binders for closures are experimental",
|
||||
"consider removing `for<...>`"
|
||||
"consider using a type annotation instead: \
|
||||
`let closure: for<...> fn(...) -> ... = /* closure */;`"
|
||||
);
|
||||
gate_all!(
|
||||
half_open_range_patterns_in_slices,
|
||||
|
||||
@@ -324,7 +324,7 @@ fn extend_err_with_const_context(
|
||||
{
|
||||
// `foo<N>()`, point at the const parameter in the definition of `foo`.
|
||||
if let Some(i) =
|
||||
path.segments.iter().last().and_then(|segment| segment.args).and_then(|args| {
|
||||
path.segments.last().and_then(|segment| segment.args).and_then(|args| {
|
||||
args.args.iter().position(|arg| {
|
||||
matches!(arg, hir::GenericArg::Const(arg) if arg.hir_id == parent.hir_id)
|
||||
})
|
||||
|
||||
@@ -1688,7 +1688,7 @@ impl<'a> Parser<'a> {
|
||||
/// If the user writes `S { ref field: name }` instead of `S { field: ref name }`, we suggest
|
||||
/// the correct code.
|
||||
fn recover_misplaced_pattern_modifiers(&self, fields: &ThinVec<PatField>, err: &mut Diag<'a>) {
|
||||
if let Some(last) = fields.iter().last()
|
||||
if let Some(last) = fields.last()
|
||||
&& last.is_shorthand
|
||||
&& let PatKind::Ident(binding, ident, None) = last.pat.kind
|
||||
&& binding != BindingMode::NONE
|
||||
|
||||
@@ -256,9 +256,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
|
||||
for note in notes {
|
||||
diag.note(note);
|
||||
}
|
||||
} else if let Some((_, UnresolvedImportError { note: Some(note), .. })) =
|
||||
errors.iter().last()
|
||||
{
|
||||
} else if let Some((_, UnresolvedImportError { note: Some(note), .. })) = errors.last() {
|
||||
diag.note(note.clone());
|
||||
}
|
||||
|
||||
@@ -2876,7 +2874,7 @@ impl<'ra, 'tcx> Resolver<'ra, 'tcx> {
|
||||
if struct_expr.fields.is_empty() {
|
||||
return;
|
||||
}
|
||||
let last_span = struct_expr.fields.iter().last().unwrap().span;
|
||||
let last_span = struct_expr.fields.last().unwrap().span;
|
||||
let mut iter = struct_expr.fields.iter().peekable();
|
||||
let mut prev: Option<Span> = None;
|
||||
while let Some(field) = iter.next() {
|
||||
|
||||
@@ -4092,7 +4092,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
|
||||
v.could_be_path = false;
|
||||
}
|
||||
self.report_error(
|
||||
v.origin.iter().next().unwrap().0,
|
||||
v.origin.first().unwrap().0,
|
||||
ResolutionError::VariableNotBoundInPattern(v, self.parent_scope),
|
||||
);
|
||||
}
|
||||
@@ -4757,8 +4757,7 @@ impl<'a, 'ast, 'ra, 'tcx> LateResolutionVisitor<'a, 'ast, 'ra, 'tcx> {
|
||||
self.resolve_path(&std_path, Some(ns), None, source)
|
||||
{
|
||||
// Check if we wrote `str::from_utf8` instead of `std::str::from_utf8`
|
||||
let item_span =
|
||||
path.iter().last().map_or(path_span, |segment| segment.ident.span);
|
||||
let item_span = path.last().map_or(path_span, |segment| segment.ident.span);
|
||||
|
||||
self.r.confused_type_with_std_module.insert(item_span, path_span);
|
||||
self.r.confused_type_with_std_module.insert(path_span, path_span);
|
||||
|
||||
@@ -188,7 +188,7 @@ impl<'a, B: ?Sized + ToOwned> Borrow<B> for Cow<'a, B>
|
||||
// B::Owned: [const] Borrow<B>,
|
||||
{
|
||||
fn borrow(&self) -> &B {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -2144,7 +2144,7 @@ impl<T: Clone, A: Allocator + Clone> Clone for Box<[T], A> {
|
||||
/// ```
|
||||
fn clone_from(&mut self, source: &Self) {
|
||||
if self.len() == source.len() {
|
||||
self.clone_from_slice(&source);
|
||||
self.clone_from_slice(source);
|
||||
} else {
|
||||
*self = source.clone();
|
||||
}
|
||||
@@ -2295,14 +2295,14 @@ impl<T: ?Sized, A: Allocator> Deref for Box<T, A> {
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<T: ?Sized, A: Allocator> DerefMut for Box<T, A> {
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2398,28 +2398,28 @@ impl<T: ?Sized + Unsize<U>, U: ?Sized> DispatchFromDyn<Box<U>> for Box<T, Global
|
||||
#[stable(feature = "box_borrow", since = "1.1.0")]
|
||||
impl<T: ?Sized, A: Allocator> Borrow<T> for Box<T, A> {
|
||||
fn borrow(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(feature = "box_borrow", since = "1.1.0")]
|
||||
impl<T: ?Sized, A: Allocator> BorrowMut<T> for Box<T, A> {
|
||||
fn borrow_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
|
||||
impl<T: ?Sized, A: Allocator> AsRef<T> for Box<T, A> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
|
||||
impl<T: ?Sized, A: Allocator> AsMut<T> for Box<T, A> {
|
||||
fn as_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1572,7 +1572,7 @@ impl<K, V, A: Allocator + Clone> BTreeMap<K, V, A> {
|
||||
|
||||
let right_root = left_root.split_off(key, (*self.alloc).clone());
|
||||
|
||||
let (new_left_len, right_len) = Root::calc_split_length(total_num, &left_root, &right_root);
|
||||
let (new_left_len, right_len) = Root::calc_split_length(total_num, left_root, &right_root);
|
||||
self.length = new_left_len;
|
||||
|
||||
BTreeMap {
|
||||
@@ -2208,8 +2208,8 @@ impl<'a, K, V, R> ExtractIfInner<'a, K, V, R> {
|
||||
// On creation, we navigated directly to the left bound, so we need only check the
|
||||
// right bound here to decide whether to stop.
|
||||
match self.range.end_bound() {
|
||||
Bound::Included(ref end) if (*k).le(end) => (),
|
||||
Bound::Excluded(ref end) if (*k).lt(end) => (),
|
||||
Bound::Included(end) if (*k).le(end) => (),
|
||||
Bound::Excluded(end) if (*k).lt(end) => (),
|
||||
Bound::Unbounded => (),
|
||||
_ => return None,
|
||||
}
|
||||
|
||||
@@ -1430,7 +1430,7 @@ impl<'a, K: 'a, V: 'a> BalancingContext<'a, K, V> {
|
||||
left_node.val_area_mut(old_left_len + 1..new_left_len),
|
||||
);
|
||||
|
||||
slice_remove(&mut parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1);
|
||||
slice_remove(parent_node.edge_area_mut(..old_parent_len + 1), parent_idx + 1);
|
||||
parent_node.correct_childrens_parent_links(parent_idx + 1..old_parent_len);
|
||||
*parent_node.len_mut() -= 1;
|
||||
|
||||
|
||||
@@ -1971,7 +1971,7 @@ impl<'a, T: Ord, A: Allocator + Clone> Iterator for Difference<'a, T, A> {
|
||||
}
|
||||
DifferenceInner::Search { self_iter, other_set } => loop {
|
||||
let self_next = self_iter.next()?;
|
||||
if !other_set.contains(&self_next) {
|
||||
if !other_set.contains(self_next) {
|
||||
return Some(self_next);
|
||||
}
|
||||
},
|
||||
@@ -2068,7 +2068,7 @@ impl<'a, T: Ord, A: Allocator + Clone> Iterator for Intersection<'a, T, A> {
|
||||
}
|
||||
IntersectionInner::Search { small_iter, large_set } => loop {
|
||||
let small_next = small_iter.next()?;
|
||||
if large_set.contains(&small_next) {
|
||||
if large_set.contains(small_next) {
|
||||
return Some(small_next);
|
||||
}
|
||||
},
|
||||
|
||||
@@ -327,7 +327,7 @@ impl Read for &[u8] {
|
||||
fn read_buf_exact(&mut self, mut cursor: BorrowedCursor<'_, u8>) -> io::Result<()> {
|
||||
if cursor.capacity() > self.len() {
|
||||
// Append everything we can to the cursor.
|
||||
cursor.append(*self);
|
||||
cursor.append(self);
|
||||
*self = &self[self.len()..];
|
||||
return Err(io::Error::READ_EXACT_EOF);
|
||||
}
|
||||
@@ -349,7 +349,7 @@ impl Read for &[u8] {
|
||||
buf.try_extend_from_slice_of_bytes(*self)?;
|
||||
}
|
||||
_ => {
|
||||
buf.extend_from_slice(*self);
|
||||
buf.extend_from_slice(self);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -625,7 +625,7 @@ where
|
||||
|
||||
#[inline]
|
||||
fn is_read_vectored(&self) -> bool {
|
||||
(&**self).is_read_vectored()
|
||||
(**self).is_read_vectored()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
@@ -667,7 +667,7 @@ where
|
||||
|
||||
#[inline]
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
(&**self).is_write_vectored()
|
||||
(**self).is_write_vectored()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -3858,14 +3858,14 @@ impl<'a> RcInnerPtr for WeakInner<'a> {
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Rc<T, A> {
|
||||
fn borrow(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
|
||||
impl<T: ?Sized, A: Allocator> AsRef<T> for Rc<T, A> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3990,28 +3990,28 @@ impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueRc<T, A> {
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueRc<T, A> {
|
||||
fn borrow(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueRc<T, A> {
|
||||
fn borrow_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueRc<T, A> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueRc<T, A> {
|
||||
fn as_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3836,7 +3836,7 @@ impl Default for Arc<str> {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
let arc: Arc<[u8]> = Default::default();
|
||||
debug_assert!(core::str::from_utf8(&*arc).is_ok());
|
||||
debug_assert!(core::str::from_utf8(&arc).is_ok());
|
||||
let (ptr, alloc) = Arc::into_inner_with_allocator(arc);
|
||||
unsafe { Arc::from_ptr_in(ptr.as_ptr() as *mut ArcInner<str>, alloc) }
|
||||
}
|
||||
@@ -4246,14 +4246,14 @@ impl<T, I: iter::TrustedLen<Item = T>> ToArcSlice<T> for I {
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for Arc<T, A> {
|
||||
fn borrow(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[stable(since = "1.5.0", feature = "smart_ptr_as_ref")]
|
||||
impl<T: ?Sized, A: Allocator> AsRef<T> for Arc<T, A> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4463,28 +4463,28 @@ impl<T: ?Sized, A: Allocator> fmt::Pointer for UniqueArc<T, A> {
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::Borrow<T> for UniqueArc<T, A> {
|
||||
fn borrow(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> borrow::BorrowMut<T> for UniqueArc<T, A> {
|
||||
fn borrow_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> AsRef<T> for UniqueArc<T, A> {
|
||||
fn as_ref(&self) -> &T {
|
||||
&**self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
#[unstable(feature = "unique_rc_arc", issue = "112566")]
|
||||
impl<T: ?Sized, A: Allocator> AsMut<T> for UniqueArc<T, A> {
|
||||
fn as_mut(&mut self) -> &mut T {
|
||||
&mut **self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3878,7 +3878,7 @@ impl<T: Clone, A: Allocator + Clone> Clone for Vec<T, A> {
|
||||
/// capacity of the original.
|
||||
fn clone(&self) -> Self {
|
||||
let alloc = self.allocator().clone();
|
||||
<[T]>::to_vec_in(&**self, alloc)
|
||||
<[T]>::to_vec_in(self, alloc)
|
||||
}
|
||||
|
||||
/// Overwrites the contents of `self` with a clone of the contents of `source`.
|
||||
|
||||
@@ -59,7 +59,7 @@ impl<I: Iterator, A: Allocator> Drop for Splice<'_, I, A> {
|
||||
// Which means we can replace the slice::Iter with pointers that won't point to deallocated
|
||||
// memory, so that Drain::drop is still allowed to call iter.len(), otherwise it would break
|
||||
// the ptr.offset_from_unsigned contract.
|
||||
self.drain.iter = (&[]).iter();
|
||||
self.drain.iter = [].iter();
|
||||
|
||||
unsafe {
|
||||
if self.drain.tail_len == 0 {
|
||||
|
||||
@@ -284,7 +284,7 @@ impl Wtf8Buf {
|
||||
/// like concatenating ill-formed UTF-16 strings effectively would.
|
||||
#[inline]
|
||||
pub fn push_wtf8(&mut self, other: &Wtf8) {
|
||||
match ((&*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
|
||||
match ((*self).final_lead_surrogate(), other.initial_trail_surrogate()) {
|
||||
// Replace newly paired surrogates by a supplementary code point.
|
||||
(Some(lead), Some(trail)) => {
|
||||
let len_without_lead_surrogate = self.len() - 3;
|
||||
@@ -322,7 +322,7 @@ impl Wtf8Buf {
|
||||
#[inline]
|
||||
pub fn push(&mut self, code_point: CodePoint) {
|
||||
if let Some(trail) = code_point.to_trail_surrogate() {
|
||||
if let Some(lead) = (&*self).final_lead_surrogate() {
|
||||
if let Some(lead) = (*self).final_lead_surrogate() {
|
||||
let len_without_lead_surrogate = self.len() - 3;
|
||||
self.bytes.truncate(len_without_lead_surrogate);
|
||||
self.push_char(decode_surrogate_pair(lead, trail));
|
||||
|
||||
@@ -25,7 +25,7 @@ impl PartialOrd for ByteStr {
|
||||
impl PartialEq<ByteStr> for ByteStr {
|
||||
#[inline]
|
||||
fn eq(&self, other: &ByteStr) -> bool {
|
||||
&self.0 == &other.0
|
||||
self.0 == other.0
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -704,7 +704,7 @@ impl<T, const N: usize> AsRef<[Cell<T>; N]> for Cell<[T; N]> {
|
||||
impl<T, const N: usize> AsRef<[Cell<T>]> for Cell<[T; N]> {
|
||||
#[inline]
|
||||
fn as_ref(&self) -> &[Cell<T>] {
|
||||
&*self.as_array_of_cells()
|
||||
self.as_array_of_cells()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -781,7 +781,7 @@ mod impls {
|
||||
#[inline(always)]
|
||||
#[rustc_diagnostic_item = "noop_method_clone"]
|
||||
fn clone(&self) -> Self {
|
||||
*self
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -687,7 +687,7 @@ impl PartialEq<&Self> for CStr {
|
||||
impl PartialOrd for CStr {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &CStr) -> Option<Ordering> {
|
||||
self.to_bytes().partial_cmp(&other.to_bytes())
|
||||
self.to_bytes().partial_cmp(other.to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -695,7 +695,7 @@ impl PartialOrd for CStr {
|
||||
impl Ord for CStr {
|
||||
#[inline]
|
||||
fn cmp(&self, other: &CStr) -> Ordering {
|
||||
self.to_bytes().cmp(&other.to_bytes())
|
||||
self.to_bytes().cmp(other.to_bytes())
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3189,7 +3189,7 @@ impl<T: ?Sized + Debug> Debug for Ref<'_, T> {
|
||||
#[stable(feature = "rust1", since = "1.0.0")]
|
||||
impl<T: ?Sized + Debug> Debug for RefMut<'_, T> {
|
||||
fn fmt(&self, f: &mut Formatter<'_>) -> Result {
|
||||
Debug::fmt(&*(self.deref()), f)
|
||||
Debug::fmt(self.deref(), f)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4080,7 +4080,7 @@ pub const trait Iterator {
|
||||
mut compare: impl FnMut(&T, &T) -> bool + 'a,
|
||||
) -> impl FnMut(T) -> bool + 'a {
|
||||
move |curr| {
|
||||
if !compare(&last, &curr) {
|
||||
if !compare(last, &curr) {
|
||||
return false;
|
||||
}
|
||||
*last = curr;
|
||||
|
||||
@@ -116,7 +116,7 @@ where
|
||||
type Target = T;
|
||||
|
||||
fn deref(&self) -> &T {
|
||||
&*self.inner
|
||||
&self.inner
|
||||
}
|
||||
}
|
||||
|
||||
@@ -127,7 +127,7 @@ where
|
||||
F: FnOnce(T),
|
||||
{
|
||||
fn deref_mut(&mut self) -> &mut T {
|
||||
&mut *self.inner
|
||||
&mut self.inner
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1639,7 +1639,7 @@ impl<T, const N: usize> AsRef<[MaybeUninit<T>; N]> for MaybeUninit<[T; N]> {
|
||||
impl<T, const N: usize> AsRef<[MaybeUninit<T>]> for MaybeUninit<[T; N]> {
|
||||
#[inline]
|
||||
fn as_ref(&self) -> &[MaybeUninit<T>] {
|
||||
&*AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
|
||||
AsRef::<[MaybeUninit<T>; N]>::as_ref(self)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1540,7 +1540,7 @@ impl<'a, T: ?Sized> Pin<&'a T> {
|
||||
U: ?Sized,
|
||||
F: FnOnce(&T) -> &U,
|
||||
{
|
||||
let pointer = &*self.pointer;
|
||||
let pointer = self.pointer;
|
||||
let new_pointer = func(pointer);
|
||||
|
||||
// SAFETY: the safety contract for `new_unchecked` must be
|
||||
|
||||
@@ -91,7 +91,7 @@ impl [u8] {
|
||||
let mut b = other;
|
||||
|
||||
while let ([first_a, rest_a @ ..], [first_b, rest_b @ ..]) = (a, b) {
|
||||
if first_a.eq_ignore_ascii_case(&first_b) {
|
||||
if first_a.eq_ignore_ascii_case(first_b) {
|
||||
a = rest_a;
|
||||
b = rest_b;
|
||||
} else {
|
||||
|
||||
@@ -424,7 +424,7 @@ impl<'a, T: 'a, P: FnMut(&T) -> bool> Split<'a, T, P> {
|
||||
/// ```
|
||||
#[unstable(feature = "split_as_slice", issue = "96137")]
|
||||
pub fn as_slice(&self) -> &'a [T] {
|
||||
if self.finished { &[] } else { &self.v }
|
||||
if self.finished { &[] } else { self.v }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1410,7 +1410,7 @@ impl<'a> SplitAsciiWhitespace<'a> {
|
||||
}
|
||||
|
||||
// SAFETY: Slice is created from str.
|
||||
Some(unsafe { crate::str::from_utf8_unchecked(&self.inner.iter.iter.v) })
|
||||
Some(unsafe { crate::str::from_utf8_unchecked(self.inner.iter.iter.v) })
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1051,7 +1051,7 @@ impl<'b> Pattern for &'b str {
|
||||
|
||||
#[inline]
|
||||
fn as_utf8_pattern(&self) -> Option<Utf8Pattern<'_>> {
|
||||
Some(Utf8Pattern::StringPattern(*self))
|
||||
Some(Utf8Pattern::StringPattern(self))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -245,14 +245,14 @@ impl<'a> Context<'a> {
|
||||
#[stable(feature = "futures_api", since = "1.36.0")]
|
||||
#[rustc_const_stable(feature = "const_waker", since = "1.82.0")]
|
||||
pub const fn waker(&self) -> &'a Waker {
|
||||
&self.waker
|
||||
self.waker
|
||||
}
|
||||
|
||||
/// Returns a reference to the [`LocalWaker`] for the current task.
|
||||
#[inline]
|
||||
#[unstable(feature = "local_waker", issue = "118959")]
|
||||
pub const fn local_waker(&self) -> &'a LocalWaker {
|
||||
&self.local_waker
|
||||
self.local_waker
|
||||
}
|
||||
|
||||
/// Returns a reference to the extension data for the current task.
|
||||
|
||||
@@ -719,7 +719,7 @@ impl fmt::Debug for OsString {
|
||||
impl PartialEq for OsString {
|
||||
#[inline]
|
||||
fn eq(&self, other: &OsString) -> bool {
|
||||
&**self == &**other
|
||||
**self == **other
|
||||
}
|
||||
}
|
||||
|
||||
@@ -762,23 +762,23 @@ impl Eq for OsString {}
|
||||
impl PartialOrd for OsString {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &OsString) -> Option<cmp::Ordering> {
|
||||
(&**self).partial_cmp(&**other)
|
||||
(**self).partial_cmp(&**other)
|
||||
}
|
||||
#[inline]
|
||||
fn lt(&self, other: &OsString) -> bool {
|
||||
&**self < &**other
|
||||
**self < **other
|
||||
}
|
||||
#[inline]
|
||||
fn le(&self, other: &OsString) -> bool {
|
||||
&**self <= &**other
|
||||
**self <= **other
|
||||
}
|
||||
#[inline]
|
||||
fn gt(&self, other: &OsString) -> bool {
|
||||
&**self > &**other
|
||||
**self > **other
|
||||
}
|
||||
#[inline]
|
||||
fn ge(&self, other: &OsString) -> bool {
|
||||
&**self >= &**other
|
||||
**self >= **other
|
||||
}
|
||||
}
|
||||
|
||||
@@ -786,7 +786,7 @@ impl PartialOrd for OsString {
|
||||
impl PartialOrd<str> for OsString {
|
||||
#[inline]
|
||||
fn partial_cmp(&self, other: &str) -> Option<cmp::Ordering> {
|
||||
(&**self).partial_cmp(other)
|
||||
(**self).partial_cmp(other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -794,7 +794,7 @@ impl PartialOrd<str> for OsString {
|
||||
impl Ord for OsString {
|
||||
#[inline]
|
||||
fn cmp(&self, other: &OsString) -> cmp::Ordering {
|
||||
(&**self).cmp(&**other)
|
||||
(**self).cmp(&**other)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -802,7 +802,7 @@ impl Ord for OsString {
|
||||
impl Hash for OsString {
|
||||
#[inline]
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
(&**self).hash(state)
|
||||
(**self).hash(state)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1777,7 +1777,7 @@ impl AsRef<OsStr> for str {
|
||||
impl AsRef<OsStr> for String {
|
||||
#[inline]
|
||||
fn as_ref(&self) -> &OsStr {
|
||||
(&**self).as_ref()
|
||||
(**self).as_ref()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1497,7 +1497,7 @@ impl Read for File {
|
||||
}
|
||||
#[inline]
|
||||
fn is_read_vectored(&self) -> bool {
|
||||
(&&*self).is_read_vectored()
|
||||
(&self).is_read_vectored()
|
||||
}
|
||||
fn read_to_end(&mut self, buf: &mut Vec<u8>) -> io::Result<usize> {
|
||||
(&*self).read_to_end(buf)
|
||||
@@ -1516,7 +1516,7 @@ impl Write for File {
|
||||
}
|
||||
#[inline]
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
(&&*self).is_write_vectored()
|
||||
(&self).is_write_vectored()
|
||||
}
|
||||
#[inline]
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
|
||||
@@ -796,7 +796,7 @@ impl Write for Stdout {
|
||||
}
|
||||
#[inline]
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
io::Write::is_write_vectored(&&*self)
|
||||
io::Write::is_write_vectored(&self)
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
(&*self).flush()
|
||||
@@ -1028,7 +1028,7 @@ impl Write for Stderr {
|
||||
}
|
||||
#[inline]
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
io::Write::is_write_vectored(&&*self)
|
||||
io::Write::is_write_vectored(&self)
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
(&*self).flush()
|
||||
|
||||
@@ -740,7 +740,7 @@ mod panicking;
|
||||
|
||||
#[path = "../../backtrace/src/lib.rs"]
|
||||
#[allow(dead_code, unused_attributes, implicit_provenance_casts, unsafe_op_in_unsafe_fn)]
|
||||
#[allow(clippy::len_zero)] // FIXME
|
||||
#[allow(clippy::len_zero, clippy::needless_borrow)] // FIXME
|
||||
mod backtrace_rs;
|
||||
|
||||
#[stable(feature = "cfg_select", since = "1.95.0")]
|
||||
|
||||
@@ -257,6 +257,6 @@ impl<T: ToSocketAddrs + ?Sized> ToSocketAddrs for &T {
|
||||
impl ToSocketAddrs for String {
|
||||
type Iter = vec::IntoIter<SocketAddr>;
|
||||
fn to_socket_addrs(&self) -> io::Result<vec::IntoIter<SocketAddr>> {
|
||||
(&**self).to_socket_addrs()
|
||||
(**self).to_socket_addrs()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -262,12 +262,10 @@ impl SocketAddr {
|
||||
} else if self.addr.sun_path[0] == 0 {
|
||||
AddressKind::Abstract(ByteStr::from_bytes(&path[1..len]))
|
||||
} else {
|
||||
// the value returned by getsockname(2) and similar on QNX7.1 and
|
||||
// QNX8 does not count the NUL byte terminator of the path string,
|
||||
// which matches the behavior of the SUN_LEN macro in libc, but
|
||||
// other OSes do count the NUL byte so adjust accordingly
|
||||
let end =
|
||||
if cfg!(any(target_os = "qnx", target_env = "nto71")) { len } else { len - 1 };
|
||||
// linux adds a trailing NUL and counts it in the length, freebsd, netbsd
|
||||
// and qnx do not, and a caller may bind(2) without one either. unix(7)
|
||||
// gives the portable rule: strnlen(sun_path, len - offsetof(sun_path))
|
||||
let end = core::slice::memchr::memchr(0, &path[..len]).unwrap_or(len);
|
||||
AddressKind::Pathname(OsStr::from_bytes(&path[..end]).as_ref())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -506,12 +506,12 @@ impl<'a> AncillaryData<'a> {
|
||||
fn try_from_cmsghdr(cmsg: &'a libc::cmsghdr) -> Result<Self, AncillaryError> {
|
||||
unsafe {
|
||||
let cmsg_len_zero = libc::CMSG_LEN(0) as usize;
|
||||
let data_len = (*cmsg).cmsg_len as usize - cmsg_len_zero;
|
||||
let data_len = cmsg.cmsg_len as usize - cmsg_len_zero;
|
||||
let data = libc::CMSG_DATA(cmsg).cast();
|
||||
let data = from_raw_parts(data, data_len);
|
||||
|
||||
match (*cmsg).cmsg_level {
|
||||
libc::SOL_SOCKET => match (*cmsg).cmsg_type {
|
||||
match cmsg.cmsg_level {
|
||||
libc::SOL_SOCKET => match cmsg.cmsg_type {
|
||||
libc::SCM_RIGHTS => Ok(AncillaryData::as_rights(data)),
|
||||
#[cfg(any(target_os = "android", target_os = "linux", target_os = "cygwin"))]
|
||||
libc::SCM_CREDENTIALS => Ok(AncillaryData::as_credentials(data)),
|
||||
@@ -524,7 +524,7 @@ impl<'a> AncillaryData<'a> {
|
||||
}
|
||||
},
|
||||
cmsg_level => {
|
||||
Err(AncillaryError::Unknown { cmsg_level, cmsg_type: (*cmsg).cmsg_type })
|
||||
Err(AncillaryError::Unknown { cmsg_level, cmsg_type: cmsg.cmsg_type })
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -744,7 +744,7 @@ impl<'a> SocketAncillary<'a> {
|
||||
pub fn add_fds(&mut self, fds: &[RawFd]) -> bool {
|
||||
self.truncated = false;
|
||||
add_to_ancillary_data(
|
||||
&mut self.buffer,
|
||||
self.buffer,
|
||||
&mut self.length,
|
||||
fds,
|
||||
libc::SOL_SOCKET,
|
||||
@@ -771,7 +771,7 @@ impl<'a> SocketAncillary<'a> {
|
||||
pub fn add_creds(&mut self, creds: &[SocketCred]) -> bool {
|
||||
self.truncated = false;
|
||||
add_to_ancillary_data(
|
||||
&mut self.buffer,
|
||||
self.buffer,
|
||||
&mut self.length,
|
||||
creds,
|
||||
libc::SOL_SOCKET,
|
||||
|
||||
@@ -642,7 +642,7 @@ impl io::Read for UnixStream {
|
||||
|
||||
#[inline]
|
||||
fn is_read_vectored(&self) -> bool {
|
||||
io::Read::is_read_vectored(&&*self)
|
||||
io::Read::is_read_vectored(&self)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -678,7 +678,7 @@ impl io::Write for UnixStream {
|
||||
|
||||
#[inline]
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
io::Write::is_write_vectored(&&*self)
|
||||
io::Write::is_write_vectored(&self)
|
||||
}
|
||||
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
|
||||
@@ -29,6 +29,29 @@ fn sock_addr_from_pathname() {
|
||||
assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
|
||||
}
|
||||
|
||||
// the trailing NUL is not counted in the reported length on freebsd, netbsd
|
||||
// and qnx, and a caller may bind(2) without one anywhere
|
||||
#[test]
|
||||
fn sock_addr_without_trailing_nul() {
|
||||
const PATH: &[u8] = b"/path/to/socket";
|
||||
|
||||
// SAFETY: all zeros is a valid representation for `sockaddr_un`.
|
||||
let mut addr: libc::sockaddr_un = unsafe { crate::mem::zeroed() };
|
||||
addr.sun_family = libc::AF_UNIX as libc::sa_family_t;
|
||||
for (dst, &src) in addr.sun_path.iter_mut().zip(PATH) {
|
||||
*dst = src as _;
|
||||
}
|
||||
let offset = crate::mem::offset_of!(libc::sockaddr_un, sun_path);
|
||||
|
||||
// length excluding the NUL, as reported by freebsd, netbsd and qnx
|
||||
let address = or_panic!(SocketAddr::from_parts(addr, (offset + PATH.len()) as _));
|
||||
assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
|
||||
|
||||
// length including the NUL, as reported by linux
|
||||
let address = or_panic!(SocketAddr::from_parts(addr, (offset + PATH.len() + 1) as _));
|
||||
assert_eq!(address.as_pathname(), Some(Path::new("/path/to/socket")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[cfg_attr(target_os = "android", ignore)] // Android SELinux rules prevent creating Unix sockets
|
||||
#[cfg_attr(target_os = "vxworks", ignore = "Unix sockets are not implemented in VxWorks")]
|
||||
|
||||
@@ -2673,7 +2673,7 @@ impl Path {
|
||||
#[stable(feature = "path_ancestors", since = "1.28.0")]
|
||||
#[inline]
|
||||
pub fn ancestors(&self) -> Ancestors<'_> {
|
||||
Ancestors { next: Some(&self) }
|
||||
Ancestors { next: Some(self) }
|
||||
}
|
||||
|
||||
/// Returns the final component of the `Path`, if there is one.
|
||||
|
||||
@@ -333,7 +333,7 @@ impl Write for ChildStdin {
|
||||
}
|
||||
|
||||
fn is_write_vectored(&self) -> bool {
|
||||
io::Write::is_write_vectored(&&*self)
|
||||
io::Write::is_write_vectored(&self)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -258,7 +258,7 @@ impl<T, F: FnOnce() -> T> LazyLock<T, F> {
|
||||
// * the closure was not called, but a previous call initialized `value`.
|
||||
// * the closure was not called because the Once is poisoned, which we handled above.
|
||||
// So `value` has definitely been initialized and will not be modified again.
|
||||
unsafe { &*(*this.data.get()).value }
|
||||
unsafe { &(*this.data.get()).value }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -636,7 +636,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
|
||||
// reference passed to it. If the closure panics, the guard will be dropped.
|
||||
let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
|
||||
MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
|
||||
}
|
||||
|
||||
/// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data. The
|
||||
@@ -668,7 +668,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
|
||||
Some(data) => {
|
||||
let data = NonNull::from(data);
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
|
||||
}
|
||||
None => Err(orig),
|
||||
}
|
||||
@@ -861,7 +861,7 @@ impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
|
||||
// reference passed to it. If the closure panics, the guard will be dropped.
|
||||
let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
|
||||
MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
|
||||
}
|
||||
|
||||
/// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data.
|
||||
@@ -893,7 +893,7 @@ impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
|
||||
Some(data) => {
|
||||
let data = NonNull::from(data);
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
|
||||
}
|
||||
None => Err(orig),
|
||||
}
|
||||
|
||||
@@ -770,7 +770,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
|
||||
// reference passed to it. If the closure panics, the guard will be dropped.
|
||||
let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
|
||||
MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
|
||||
}
|
||||
|
||||
/// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data. The
|
||||
@@ -802,7 +802,7 @@ impl<'rwlock, T: ?Sized> RwLockReadGuard<'rwlock, T> {
|
||||
Some(data) => {
|
||||
let data = NonNull::from(data);
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
|
||||
}
|
||||
None => Err(orig),
|
||||
}
|
||||
@@ -996,7 +996,7 @@ impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
|
||||
// reference passed to it. If the closure panics, the guard will be dropped.
|
||||
let data = NonNull::from(f(unsafe { orig.data.as_ref() }));
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock }
|
||||
MappedRwLockReadGuard { data, inner_lock: orig.inner_lock }
|
||||
}
|
||||
|
||||
/// Makes a [`MappedRwLockReadGuard`] for a component of the borrowed data.
|
||||
@@ -1028,7 +1028,7 @@ impl<'rwlock, T: ?Sized> MappedRwLockReadGuard<'rwlock, T> {
|
||||
Some(data) => {
|
||||
let data = NonNull::from(data);
|
||||
let orig = ManuallyDrop::new(orig);
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: &orig.inner_lock })
|
||||
Ok(MappedRwLockReadGuard { data, inner_lock: orig.inner_lock })
|
||||
}
|
||||
None => Err(orig),
|
||||
}
|
||||
|
||||
@@ -72,7 +72,7 @@ impl Dir {
|
||||
}
|
||||
|
||||
pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
|
||||
File::open(&self.path.join(path), &opts)
|
||||
File::open(&self.path.join(path), opts)
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> io::Result<FileAttr> {
|
||||
|
||||
@@ -2415,7 +2415,7 @@ mod remove_dir_impl {
|
||||
|
||||
fn remove_dir_all_recursive(parent_fd: Option<RawFd>, path: &CStr) -> io::Result<()> {
|
||||
// try opening as directory
|
||||
let fd = match openat_nofollow_dironly(parent_fd, &path) {
|
||||
let fd = match openat_nofollow_dironly(parent_fd, path) {
|
||||
Err(err) if matches!(err.raw_os_error(), Some(libc::ENOTDIR | libc::ELOOP)) => {
|
||||
// not a directory - don't traverse further
|
||||
// (for symlinks, older Linux kernels may return ELOOP instead of ENOTDIR)
|
||||
@@ -2485,7 +2485,7 @@ mod remove_dir_impl {
|
||||
if attr.file_type().is_symlink() {
|
||||
super::unlink(p)
|
||||
} else {
|
||||
remove_dir_all_recursive(None, &p)
|
||||
remove_dir_all_recursive(None, p)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ impl Dir {
|
||||
}
|
||||
|
||||
pub fn open_file(&self, path: &Path, opts: &OpenOptions) -> io::Result<File> {
|
||||
run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, &opts))
|
||||
run_path_with_cstr(path.as_ref(), &|path| self.open_file_c(path, opts))
|
||||
}
|
||||
|
||||
pub fn metadata(&self) -> io::Result<FileAttr> {
|
||||
|
||||
@@ -339,7 +339,7 @@ impl File {
|
||||
let path = maybe_verbatim(path)?;
|
||||
// SAFETY: maybe_verbatim returns null-terminated strings
|
||||
let path = unsafe { WCStr::from_wchars_with_null_unchecked(&path) };
|
||||
Self::open_native(&path, opts)
|
||||
Self::open_native(path, opts)
|
||||
}
|
||||
|
||||
fn open_native(path: &WCStr, opts: &OpenOptions) -> io::Result<File> {
|
||||
@@ -1305,7 +1305,7 @@ pub fn unlink(path: &WCStr) -> io::Result<()> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.access_mode(c::DELETE);
|
||||
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT);
|
||||
if let Ok(f) = File::open_native(&path, &opts) {
|
||||
if let Ok(f) = File::open_native(path, &opts) {
|
||||
if f.posix_delete().is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -1328,7 +1328,7 @@ pub fn rename(old: &WCStr, new: &WCStr) -> io::Result<()> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.access_mode(c::DELETE);
|
||||
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
|
||||
let Ok(f) = File::open_native(&old, &opts) else { return Err(err).io_result() };
|
||||
let Ok(f) = File::open_native(old, &opts) else { return Err(err).io_result() };
|
||||
|
||||
// Calculate the layout of the `FILE_RENAME_INFO` we pass to `SetFileInformation`
|
||||
// This is a dynamically sized struct so we need to get the position of the last field to calculate the actual size.
|
||||
@@ -1419,7 +1419,7 @@ pub fn readlink(path: &WCStr) -> io::Result<PathBuf> {
|
||||
let mut opts = OpenOptions::new();
|
||||
opts.access_mode(0);
|
||||
opts.custom_flags(c::FILE_FLAG_OPEN_REPARSE_POINT | c::FILE_FLAG_BACKUP_SEMANTICS);
|
||||
let file = File::open_native(&path, &opts)?;
|
||||
let file = File::open_native(path, &opts)?;
|
||||
file.readlink()
|
||||
}
|
||||
|
||||
@@ -1506,7 +1506,7 @@ fn metadata(path: &WCStr, reparse: ReparsePoint) -> io::Result<FileAttr> {
|
||||
// Attempt to open the file normally.
|
||||
// If that fails with `ERROR_SHARING_VIOLATION` then retry using `FindFirstFileExW`.
|
||||
// If the fallback fails for any reason we return the original error.
|
||||
match File::open_native(&path, &opts) {
|
||||
match File::open_native(path, &opts) {
|
||||
Ok(file) => file.file_attr(),
|
||||
Err(e)
|
||||
if [Some(c::ERROR_SHARING_VIOLATION as _), Some(c::ERROR_ACCESS_DENIED as _)]
|
||||
|
||||
@@ -251,6 +251,6 @@ pub(crate) fn is_absolute_exact(path: &[u16]) -> bool {
|
||||
unsafe {
|
||||
new_path.set_len((result as usize) + 1);
|
||||
}
|
||||
path == &new_path
|
||||
path == new_path
|
||||
}
|
||||
}
|
||||
|
||||
@@ -218,7 +218,7 @@ impl Command {
|
||||
pub fn chroot(&mut self, dir: &Path) {
|
||||
self.chroot = Some(os2c(dir.as_os_str(), &mut self.saw_nul));
|
||||
if self.cwd.is_none() {
|
||||
self.cwd(&OsStr::new("/"));
|
||||
self.cwd(OsStr::new("/"));
|
||||
}
|
||||
}
|
||||
pub fn setsid(&mut self, setsid: bool) {
|
||||
|
||||
@@ -2,7 +2,7 @@ use super::ExitStatus;
|
||||
use crate::io;
|
||||
use crate::os::fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd};
|
||||
use crate::sys::fd::FileDesc;
|
||||
use crate::sys::{AsInner, FromInner, IntoInner, cvt};
|
||||
use crate::sys::{AsInner, FromInner, IntoInner, cvt, cvt_r};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -61,7 +61,7 @@ impl PidFd {
|
||||
|
||||
fn waitid(&self, options: libc::c_int) -> io::Result<Option<ExitStatus>> {
|
||||
let mut siginfo: libc::siginfo_t = unsafe { crate::mem::zeroed() };
|
||||
let r = cvt(unsafe {
|
||||
let r = cvt_r(|| unsafe {
|
||||
libc::waitid(libc::P_PIDFD, self.0.as_raw_fd() as u32, &mut siginfo, options)
|
||||
});
|
||||
match r {
|
||||
|
||||
@@ -60,7 +60,7 @@ use crate::sync::atomic::Ordering::{AcqRel, Acquire, Release};
|
||||
use crate::sync::atomic::{Atomic, AtomicBool, AtomicPtr};
|
||||
use crate::sync::once::OnceExclusiveState;
|
||||
use crate::thread::{self, Thread};
|
||||
use crate::{fmt, ptr, sync as public};
|
||||
use crate::{fmt, mem, ptr, sync as public};
|
||||
|
||||
type StateAndQueue = *mut ();
|
||||
|
||||
@@ -237,6 +237,15 @@ impl Once {
|
||||
}
|
||||
}
|
||||
|
||||
/// A type to guard against the unwinds of stacks that nodes are located on due to panics.
|
||||
struct PanicGuard;
|
||||
|
||||
impl Drop for PanicGuard {
|
||||
fn drop(&mut self) {
|
||||
rtabort!("tried to drop node in intrusive list.");
|
||||
}
|
||||
}
|
||||
|
||||
fn wait(
|
||||
state_and_queue: &Atomic<*mut ()>,
|
||||
mut current: StateAndQueue,
|
||||
@@ -272,6 +281,9 @@ fn wait(
|
||||
continue;
|
||||
}
|
||||
|
||||
// Guard against unwinds using a `PanicGuard` that aborts when dropped.
|
||||
let guard = PanicGuard;
|
||||
|
||||
// We have enqueued ourselves, now lets wait.
|
||||
// It is important not to return before being signaled, otherwise we
|
||||
// would drop our `Waiter` node and leave a hole in the linked list
|
||||
@@ -288,6 +300,9 @@ fn wait(
|
||||
unsafe { node.thread.park() }
|
||||
}
|
||||
|
||||
// The node was removed from the queue, disarm the guard.
|
||||
mem::forget(guard);
|
||||
|
||||
return state_and_queue.load(Acquire);
|
||||
}
|
||||
}
|
||||
|
||||
48
src/bootstrap/src/core/backend.rs
Normal file
48
src/bootstrap/src/core/backend.rs
Normal file
@@ -0,0 +1,48 @@
|
||||
use std::str::FromStr;
|
||||
|
||||
/// Represents a codegen backend.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
pub enum CodegenBackendKind {
|
||||
#[default]
|
||||
Llvm,
|
||||
Cranelift,
|
||||
Gcc,
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
impl CodegenBackendKind {
|
||||
/// Name of the codegen backend, as identified in the `compiler` directory
|
||||
/// (`rustc_codegen_<name>`).
|
||||
pub(crate) fn name(&self) -> &str {
|
||||
match self {
|
||||
CodegenBackendKind::Llvm => "llvm",
|
||||
CodegenBackendKind::Cranelift => "cranelift",
|
||||
CodegenBackendKind::Gcc => "gcc",
|
||||
CodegenBackendKind::Custom(name) => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Name of the codegen backend's crate, e.g. `rustc_codegen_cranelift`.
|
||||
pub(crate) fn crate_name(&self) -> String {
|
||||
format!("rustc_codegen_{}", self.name())
|
||||
}
|
||||
|
||||
pub(crate) fn is_llvm(&self) -> bool {
|
||||
matches!(self, Self::Llvm)
|
||||
}
|
||||
}
|
||||
|
||||
/// FIXME(Zalathar): This is partly redundant with the parsing code in `parse_codegen_backends`.
|
||||
impl FromStr for CodegenBackendKind {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"" => Err("Invalid empty backend name"),
|
||||
"gcc" => Ok(Self::Gcc),
|
||||
"llvm" => Ok(Self::Llvm),
|
||||
"cranelift" => Ok(Self::Cranelift),
|
||||
_ => Ok(Self::Custom(s.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
use std::fs;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use crate::Mode;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::compile::{
|
||||
ArtifactKeepMode, add_to_sysroot, run_cargo, rustc_cargo, rustc_cargo_env, std_cargo,
|
||||
std_crates_for_make_run,
|
||||
@@ -16,11 +18,11 @@ use crate::core::builder::{
|
||||
self, Alias, Builder, Cargo, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
|
||||
crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
use crate::core::config::flags::Subcommand;
|
||||
use crate::utils::build_stamp::{self, BuildStamp};
|
||||
use crate::utils::helpers::t;
|
||||
use crate::{CodegenBackendKind, Compiler, Mode};
|
||||
|
||||
/// Allows individual check-step instances to keep track of whether they
|
||||
/// represent `cargo check` or `cargo fix`, independently of [`Builder::kind`].
|
||||
|
||||
@@ -12,10 +12,11 @@ use std::path::Path;
|
||||
use crate::core::builder::{
|
||||
Builder, CommandLineStep, Kind, RunConfig, ShouldRun, crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::flags::Subcommand;
|
||||
use crate::utils::build_stamp::BuildStamp;
|
||||
use crate::utils::helpers::t;
|
||||
use crate::{Build, Compiler, Mode};
|
||||
use crate::{Build, Mode};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct CleanAll {}
|
||||
|
||||
@@ -14,6 +14,7 @@
|
||||
//! (as usual) a massive undertaking/refactoring.
|
||||
|
||||
use super::tool::{SourceType, prepare_tool_cargo};
|
||||
use crate::Mode;
|
||||
use crate::core::build_steps::check::{CompilerForCheck, prepare_compiler_for_check};
|
||||
use crate::core::build_steps::compile::{
|
||||
ArtifactKeepMode, run_cargo, rustc_cargo, std_cargo, std_crates_for_make_run,
|
||||
@@ -22,11 +23,11 @@ use crate::core::builder::{
|
||||
self, Alias, Builder, CommandLineStep, Kind, RunConfig, ShouldRun, StepMetadata,
|
||||
crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
use crate::core::config::flags::Subcommand;
|
||||
use crate::utils::build_stamp::{self, BuildStamp};
|
||||
use crate::utils::helpers;
|
||||
use crate::{Compiler, Mode};
|
||||
|
||||
/// Disable the most spammy clippy lints
|
||||
const IGNORED_RULES_FOR_STD_AND_RUSTC: &[&str] = &[
|
||||
@@ -590,6 +591,10 @@ impl CommandLineStep for CI {
|
||||
"clippy::ptr_offset_with_cast".into(),
|
||||
"clippy::let_and_return".into(),
|
||||
"clippy::needless_return".into(),
|
||||
"clippy::needless_borrow".into(),
|
||||
"clippy::op_ref".into(),
|
||||
"clippy::borrow_deref_ref".into(),
|
||||
"clippy::explicit_auto_deref".into(),
|
||||
],
|
||||
forbid: vec![],
|
||||
};
|
||||
|
||||
@@ -19,6 +19,7 @@ use serde_derive::Deserialize;
|
||||
#[cfg(feature = "tracing")]
|
||||
use tracing::span;
|
||||
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::gcc::{Gcc, GccOutput, GccTargetPair};
|
||||
use crate::core::build_steps::llvm::{LlvmFromCi, prebuilt_llvm_output};
|
||||
use crate::core::build_steps::tool::{RustcPrivateCompilers, SourceType, copy_lld_artifacts};
|
||||
@@ -27,6 +28,7 @@ use crate::core::builder::{
|
||||
self, Builder, Cargo, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
|
||||
apply_pgo, crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::toml::target::DefaultLinuxLinkerOverride;
|
||||
use crate::core::config::{
|
||||
Allocator, CompilerBuiltins, DebuginfoLevel, LlvmLibunwind, RustcLto, TargetSelection,
|
||||
@@ -37,10 +39,7 @@ use crate::utils::exec::command;
|
||||
use crate::utils::helpers::{
|
||||
self, exe, get_clang_cl_resource_dir, is_debug_info, is_dylib, symlink_dir, t, up_to_date,
|
||||
};
|
||||
use crate::{
|
||||
CLang, CodegenBackendKind, Compiler, DependencyType, FileType, GitRepo, LLVM_TOOLS, Mode,
|
||||
debug, trace,
|
||||
};
|
||||
use crate::{CLang, DependencyType, FileType, GitRepo, Mode, debug, trace};
|
||||
|
||||
/// Build a standard library for the given `target` using the given `build_compiler`.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -2180,7 +2179,7 @@ impl CommandLineStep for Assemble {
|
||||
let _llvm_tools_span =
|
||||
span!(tracing::Level::TRACE, "installing llvm tools to sysroot", ?libdir_bin)
|
||||
.entered();
|
||||
for tool in LLVM_TOOLS {
|
||||
for tool in dist::LLVM_TOOLS {
|
||||
trace!("installing `{tool}`");
|
||||
let tool_exe = exe(tool, target_compiler.host);
|
||||
let src_path = llvm_bin_dir.join(&tool_exe);
|
||||
|
||||
@@ -19,6 +19,7 @@ use object::read::archive::ArchiveFile;
|
||||
#[cfg(feature = "tracing")]
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::compile::{
|
||||
get_codegen_backend_file, libgccjit_path_relative_to_cg_dir, normalize_codegen_backend_name,
|
||||
};
|
||||
@@ -35,6 +36,7 @@ use crate::core::build_steps::{compile, llvm};
|
||||
use crate::core::builder::{
|
||||
Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::{GccCiMode, TargetSelection};
|
||||
use crate::utils::build_stamp::{self, BuildStamp};
|
||||
use crate::utils::channel::{self, Info};
|
||||
@@ -43,7 +45,27 @@ use crate::utils::helpers::{
|
||||
exe, is_dylib, move_file, t, target_supports_cranelift_backend, timeit,
|
||||
};
|
||||
use crate::utils::tarball::{GeneratedTarball, OverlayKind, Tarball};
|
||||
use crate::{CodegenBackendKind, Compiler, DependencyType, FileType, LLVM_TOOLS, Mode, trace};
|
||||
use crate::{DependencyType, FileType, Mode, trace};
|
||||
|
||||
pub(crate) const LLVM_TOOLS: &[&str] = &[
|
||||
"llvm-cov", // used to generate coverage report
|
||||
"llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
|
||||
"llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
|
||||
"llvm-objdump", // used to disassemble programs
|
||||
"llvm-profdata", // used to inspect and merge files generated by profiles
|
||||
"llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
|
||||
"llvm-size", // used to prints the size of the linker sections of a program
|
||||
"llvm-strip", // used to discard symbols from binary files to reduce their size
|
||||
"llvm-ar", // used for creating and modifying archive files
|
||||
"llvm-as", // used to convert LLVM assembly to LLVM bitcode
|
||||
"llvm-dis", // used to disassemble LLVM bitcode
|
||||
"llvm-link", // Used to link LLVM bitcode
|
||||
"llc", // used to compile LLVM bytecode
|
||||
"opt", // used to optimize LLVM bytecode
|
||||
];
|
||||
|
||||
/// LLD file names for all flavors.
|
||||
pub(crate) const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
|
||||
|
||||
pub fn pkgname(builder: &Builder<'_>, component: &str) -> String {
|
||||
format!("{}-{}", component, builder.rust_package_vers())
|
||||
@@ -601,7 +623,7 @@ impl CommandLineStep for Rustc {
|
||||
let self_contained_lld_src_dir = src_dir.join("gcc-ld");
|
||||
let self_contained_lld_dst_dir = dst_dir.join("gcc-ld");
|
||||
t!(fs::create_dir(&self_contained_lld_dst_dir));
|
||||
for name in crate::LLD_FILE_NAMES {
|
||||
for name in LLD_FILE_NAMES {
|
||||
let exe_name = exe(name, target_compiler.host);
|
||||
builder.copy_link(
|
||||
&self_contained_lld_src_dir.join(&exe_name),
|
||||
|
||||
@@ -19,9 +19,10 @@ use crate::core::builder::{
|
||||
self, Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
|
||||
crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::{Config, TargetSelection};
|
||||
use crate::utils::helpers::{submodule_path_of, symlink_dir, t, up_to_date};
|
||||
use crate::{Compiler, FileType, Mode};
|
||||
use crate::{FileType, Mode};
|
||||
|
||||
macro_rules! book {
|
||||
($($name:ident, $path:expr, $book_name:expr, $lang:expr ;)+) => {
|
||||
|
||||
@@ -6,10 +6,10 @@
|
||||
use std::path::{Component, Path, PathBuf};
|
||||
use std::{env, fs};
|
||||
|
||||
use crate::Compiler;
|
||||
use crate::core::build_steps::dist;
|
||||
use crate::core::build_steps::tool::RustcPrivateCompilers;
|
||||
use crate::core::builder::{Builder, CommandLineStep, Kind, RunConfig, ShouldRun};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::{Config, TargetSelection};
|
||||
use crate::utils::exec::command;
|
||||
use crate::utils::helpers::t;
|
||||
|
||||
@@ -7,8 +7,8 @@
|
||||
//! one of the target specs already defined in this module, or create new ones by adding a new step
|
||||
//! that calls create_synthetic_target.
|
||||
|
||||
use crate::Compiler;
|
||||
use crate::core::builder::{Builder, Step};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
|
||||
@@ -15,6 +15,7 @@ use std::{env, fs, iter};
|
||||
|
||||
use build_helper::git::get_closest_upstream_commit;
|
||||
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::compile::{ArtifactKeepMode, Std, run_cargo};
|
||||
use crate::core::build_steps::doc::{DocumentationFormat, prepare_doc_compiler};
|
||||
use crate::core::build_steps::format::InternalRustfmt;
|
||||
@@ -34,6 +35,7 @@ use crate::core::builder::{
|
||||
self, Alias, Builder, CommandLineStep, Kind, RunConfig, ShouldRun, Step, StepMetadata,
|
||||
crate_description,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
use crate::core::config::flags::{Subcommand, get_completion, top_level_help};
|
||||
use crate::core::{android, debuggers};
|
||||
@@ -41,15 +43,33 @@ use crate::utils::build_stamp::{self, BuildStamp};
|
||||
use crate::utils::exec::{BootstrapCommand, command};
|
||||
use crate::utils::helpers::{
|
||||
self, LldThreads, TestFilterCategory, add_dylib_path, add_rustdoc_cargo_linker_args,
|
||||
dylib_path, dylib_path_var, linker_args, linker_flags, t, target_supports_cranelift_backend,
|
||||
up_to_date,
|
||||
dylib_path, dylib_path_var, envify, linker_args, linker_flags, t,
|
||||
target_supports_cranelift_backend, up_to_date,
|
||||
};
|
||||
use crate::utils::render_tests::{add_flags_and_try_run_tests, try_run_tests};
|
||||
use crate::{CLang, CodegenBackendKind, Compiler, GitRepo, Mode, TestTarget, envify};
|
||||
use crate::{CLang, GitRepo, Mode};
|
||||
|
||||
mod compiletest;
|
||||
pub mod failed_tests;
|
||||
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
pub enum TestTarget {
|
||||
/// Run unit, integration and doc tests (default).
|
||||
Default,
|
||||
/// Run unit, integration, doc tests, examples, bins, benchmarks (no doc tests).
|
||||
AllTargets,
|
||||
/// Only run doc tests.
|
||||
DocOnly,
|
||||
/// Only run unit and integration tests.
|
||||
Tests,
|
||||
}
|
||||
|
||||
impl TestTarget {
|
||||
pub(crate) fn runs_doctests(&self) -> bool {
|
||||
matches!(self, TestTarget::DocOnly | TestTarget::Default)
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs `cargo test` on various internal tools used by bootstrap.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
pub struct CrateBootstrap {
|
||||
|
||||
@@ -14,16 +14,18 @@ use std::path::{Path, PathBuf};
|
||||
use std::{env, fs};
|
||||
|
||||
use crate::core::build_steps::compile::{CargoMessage, is_lto_stage};
|
||||
use crate::core::build_steps::dist::LLD_FILE_NAMES;
|
||||
use crate::core::build_steps::toolstate::ToolState;
|
||||
use crate::core::build_steps::{compile, llvm};
|
||||
use crate::core::builder::{
|
||||
self, Builder, Cargo as CargoCommand, CommandLineStep, Kind, RunConfig, ShouldRun, Step,
|
||||
StepMetadata, apply_pgo, cargo_profile_var,
|
||||
};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::{Allocator, DebuginfoLevel, RustcLto, TargetSelection};
|
||||
use crate::utils::exec::{BootstrapCommand, command};
|
||||
use crate::utils::helpers::{self, add_dylib_path, exe, t};
|
||||
use crate::{Compiler, FileType, Mode};
|
||||
use crate::{FileType, Mode};
|
||||
|
||||
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
|
||||
pub enum SourceType {
|
||||
@@ -978,7 +980,7 @@ pub(crate) fn copy_lld_artifacts(
|
||||
let self_contained_lld_dir = libdir_bin.join("gcc-ld");
|
||||
t!(fs::create_dir_all(&self_contained_lld_dir));
|
||||
|
||||
for name in crate::LLD_FILE_NAMES {
|
||||
for name in LLD_FILE_NAMES {
|
||||
builder.copy_link(
|
||||
&lld_wrapper.tool.tool_path,
|
||||
&self_contained_lld_dir.join(exe(name, target)),
|
||||
|
||||
@@ -1,21 +1,35 @@
|
||||
use std::env;
|
||||
use std::ffi::{OsStr, OsString};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::OnceLock;
|
||||
use std::{env, fs};
|
||||
|
||||
use super::{Builder, Kind};
|
||||
use crate::core::build_steps::llvm::prebuilt_llvm_output;
|
||||
use crate::core::build_steps::test;
|
||||
use crate::core::build_steps::tool::SourceType;
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::flags::Color;
|
||||
use crate::core::config::toml::pgo::PgoConfig;
|
||||
use crate::core::config::{CompressDebuginfo, Config, DryRun, SplitDebuginfo, TargetSelection};
|
||||
use crate::utils::build_stamp;
|
||||
use crate::utils::exec::{BootstrapCommand, command};
|
||||
use crate::utils::helpers::{self, LldThreads, check_cfg_arg, linker_flags, t};
|
||||
use crate::{
|
||||
CLang, Compiler, EXTRA_CHECK_CFGS, GitRepo, Mode, RemapScheme, envify,
|
||||
prepare_behaviour_dump_dir,
|
||||
};
|
||||
use crate::utils::helpers::{self, LldThreads, check_cfg_arg, envify, linker_flags, t};
|
||||
use crate::{CLang, GitRepo, Mode, RemapScheme};
|
||||
|
||||
/// Extra `--check-cfg` to add when building the compiler or tools
|
||||
/// (Mode restriction, config name, config values (if any))
|
||||
#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
|
||||
const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
|
||||
(Some(Mode::Rustc), "bootstrap", None),
|
||||
(Some(Mode::Codegen), "bootstrap", None),
|
||||
(Some(Mode::ToolRustcPrivate), "bootstrap", None),
|
||||
(Some(Mode::ToolStd), "bootstrap", None),
|
||||
(Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
|
||||
(Some(Mode::ToolStd), "rust_analyzer", None),
|
||||
// Any library specific cfgs like `target_os`, `target_arch` should be put in
|
||||
// priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
|
||||
// in the appropriate `library/{std,alloc,core}/Cargo.toml`
|
||||
];
|
||||
|
||||
/// Represents flag values in `String` form with a `\x1f` delimiter to pass to the compiler later.
|
||||
///
|
||||
@@ -44,7 +58,7 @@ impl Rustflags {
|
||||
self.env(prefix);
|
||||
|
||||
// ... and also handle target-specific env RUSTFLAGS if they're configured.
|
||||
let target_specific = format!("CARGO_TARGET_{}_{}", crate::envify(&self.1.triple), prefix);
|
||||
let target_specific = format!("CARGO_TARGET_{}_{}", envify(&self.1.triple), prefix);
|
||||
self.env(&target_specific);
|
||||
}
|
||||
|
||||
@@ -1206,7 +1220,7 @@ impl Builder<'_> {
|
||||
}
|
||||
|
||||
if self.config.dump_bootstrap_shims {
|
||||
prepare_behaviour_dump_dir(self.build);
|
||||
prepare_shims_dump_dir(self);
|
||||
|
||||
cargo
|
||||
.env("DUMP_BOOTSTRAP_SHIMS", self.build.out.join("bootstrap-shims-dump"))
|
||||
@@ -1574,3 +1588,22 @@ pub fn apply_pgo(
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/// Ensures that the behavior dump directory is properly initialized.
|
||||
fn prepare_shims_dump_dir(builder: &Builder<'_>) {
|
||||
static INITIALIZED: OnceLock<bool> = OnceLock::new();
|
||||
|
||||
let dump_path = builder.out.join("bootstrap-shims-dump");
|
||||
|
||||
let initialized = INITIALIZED.get().unwrap_or(&false);
|
||||
if !initialized {
|
||||
// clear old dumps
|
||||
if dump_path.exists() {
|
||||
t!(fs::remove_dir_all(&dump_path));
|
||||
}
|
||||
|
||||
t!(fs::create_dir_all(&dump_path));
|
||||
|
||||
t!(INITIALIZED.set(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,14 +21,16 @@ use crate::core::build_steps::{
|
||||
};
|
||||
use crate::core::builder::step_stack::StepRecord;
|
||||
pub use crate::core::builder::step_stack::StepStack;
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::flags::Subcommand;
|
||||
use crate::core::config::{DryRun, TargetSelection};
|
||||
use crate::core::metadata::Crate;
|
||||
use crate::utils::build_stamp::BuildStamp;
|
||||
use crate::utils::cache::Cache;
|
||||
use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
|
||||
use crate::utils::helpers::{self, LldThreads, add_dylib_path, exe, libdir, linker_args, t};
|
||||
use crate::utils::tracing::format_location;
|
||||
use crate::{Build, Compiler, Crate, trace};
|
||||
use crate::{Build, trace};
|
||||
|
||||
mod cargo;
|
||||
mod cli_paths;
|
||||
|
||||
@@ -359,10 +359,10 @@ fn any_debug() {
|
||||
/// These tests use insta for snapshot testing.
|
||||
/// See bootstrap's README on how to bless the snapshots.
|
||||
mod snapshot {
|
||||
use crate::Compiler;
|
||||
use crate::core::build_steps::test;
|
||||
use crate::core::builder::tests::{RenderConfig, TEST_TRIPLE_1, TEST_TRIPLE_2, host_target};
|
||||
use crate::core::builder::{Kind, StepMetadata};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
use crate::core::config::toml::target::{
|
||||
DefaultLinuxLinkerOverride, with_default_linux_linker_overrides,
|
||||
|
||||
51
src/bootstrap/src/core/compiler.rs
Normal file
51
src/bootstrap/src/core/compiler.rs
Normal file
@@ -0,0 +1,51 @@
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
use crate::Build;
|
||||
use crate::core::config::TargetSelection;
|
||||
|
||||
/// A structure representing a Rust compiler.
|
||||
///
|
||||
/// Each compiler has a `stage` that it is associated with and a `host` that
|
||||
/// corresponds to the platform the compiler runs on.
|
||||
#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
|
||||
pub struct Compiler {
|
||||
pub(crate) stage: u32,
|
||||
pub(crate) host: TargetSelection,
|
||||
/// Indicates whether the compiler was forced to use a specific stage.
|
||||
/// This field is ignored in `Hash` and `PartialEq` implementations as only the `stage`
|
||||
/// and `host` fields are relevant for those.
|
||||
pub(crate) forced_compiler: bool,
|
||||
}
|
||||
|
||||
impl Hash for Compiler {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.stage.hash(state);
|
||||
self.host.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Compiler {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.stage == other.stage && self.host == other.host
|
||||
}
|
||||
}
|
||||
|
||||
impl Compiler {
|
||||
pub(crate) fn new(stage: u32, host: TargetSelection) -> Self {
|
||||
Self { stage, host, forced_compiler: false }
|
||||
}
|
||||
|
||||
pub(crate) fn forced_compiler(&mut self, forced_compiler: bool) {
|
||||
self.forced_compiler = forced_compiler;
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a snapshot compiler for `build`'s configuration
|
||||
pub(crate) fn is_snapshot(&self, build: &Build) -> bool {
|
||||
self.stage == 0 && self.host == build.host_target
|
||||
}
|
||||
|
||||
/// Indicates whether the compiler was forced to use a specific stage.
|
||||
pub(crate) fn is_forced_compiler(&self) -> bool {
|
||||
self.forced_compiler
|
||||
}
|
||||
}
|
||||
@@ -26,7 +26,7 @@ use serde::Deserialize;
|
||||
#[cfg(feature = "tracing")]
|
||||
use tracing::{instrument, span};
|
||||
|
||||
use crate::CodegenBackendKind;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::llvm;
|
||||
use crate::core::build_steps::llvm::{LLVM_INVALIDATION_PATHS, LlvmKind, LlvmOutput};
|
||||
use crate::core::build_steps::test::failed_tests::collect_previously_failed_tests;
|
||||
|
||||
@@ -10,13 +10,15 @@ use clap_complete::Generator;
|
||||
#[cfg(feature = "tracing")]
|
||||
use tracing::instrument;
|
||||
|
||||
use crate::Build;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::build_steps::perf::PerfArgs;
|
||||
use crate::core::build_steps::setup::Profile;
|
||||
use crate::core::build_steps::test::TestTarget;
|
||||
use crate::core::builder::{Builder, Kind};
|
||||
use crate::core::config::Config;
|
||||
use crate::core::config::target_selection::{TargetSelectionList, target_selection_list};
|
||||
use crate::utils::helpers;
|
||||
use crate::{Build, CodegenBackendKind, TestTarget};
|
||||
|
||||
#[derive(Copy, Clone, Default, Debug, ValueEnum)]
|
||||
pub enum Color {
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::path::PathBuf;
|
||||
use build_helper::ci::CiEnv;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::CodegenBackendKind;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::config::macros::define_config;
|
||||
use crate::core::config::toml::TomlConfig;
|
||||
use crate::core::config::{CompressDebuginfo, DebuginfoLevel, StringOrBool, TargetSelection};
|
||||
@@ -430,6 +430,7 @@ pub fn check_incompatible_options_for_ci_rustc(
|
||||
|
||||
pub(crate) const BUILTIN_CODEGEN_BACKENDS: &[&str] = &["llvm", "cranelift", "gcc"];
|
||||
|
||||
/// FIXME(Zalathar): This is partly redundant with the parsing code in [`CodegenBackendKind`].
|
||||
pub(crate) fn parse_codegen_backends(
|
||||
backends: Vec<String>,
|
||||
section: &str,
|
||||
|
||||
@@ -15,7 +15,7 @@ use std::path::PathBuf;
|
||||
use serde::de::Error;
|
||||
use serde::{Deserialize, Deserializer};
|
||||
|
||||
use crate::CodegenBackendKind;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::config::macros::define_config;
|
||||
use crate::core::config::{
|
||||
Allocator, CompilerBuiltins, CompressDebuginfo, LlvmLibunwind, SplitDebuginfo, StringOrBool,
|
||||
|
||||
@@ -5,14 +5,29 @@
|
||||
//! source, dependencies, targets, and available features. The collected metadata is then
|
||||
//! used to update the `Build` structure, ensuring proper dependency resolution and
|
||||
//! compilation flow.
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use std::path::PathBuf;
|
||||
|
||||
use serde_derive::Deserialize;
|
||||
|
||||
use crate::Build;
|
||||
use crate::utils::exec::command;
|
||||
use crate::utils::helpers::t;
|
||||
use crate::{Build, Crate};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub(crate) struct Crate {
|
||||
pub(crate) name: String,
|
||||
pub(crate) deps: HashSet<String>,
|
||||
pub(crate) path: PathBuf,
|
||||
pub(crate) features: Vec<String>,
|
||||
}
|
||||
|
||||
impl Crate {
|
||||
pub(crate) fn local_path(&self, build: &Build) -> PathBuf {
|
||||
self.path.strip_prefix(&build.config.src).unwrap().into()
|
||||
}
|
||||
}
|
||||
|
||||
/// For more information, see the output of
|
||||
/// <https://doc.rust-lang.org/nightly/cargo/commands/cargo-metadata.html>
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
pub(crate) mod android;
|
||||
pub(crate) mod backend;
|
||||
pub(crate) mod build_steps;
|
||||
pub(crate) mod builder;
|
||||
pub(crate) mod compiler;
|
||||
pub(crate) mod config;
|
||||
pub(crate) mod debuggers;
|
||||
pub(crate) mod download;
|
||||
|
||||
@@ -35,10 +35,13 @@ use termcolor::{ColorChoice, StandardStream, WriteColor};
|
||||
use tracing::{instrument, span};
|
||||
|
||||
use crate::core::build_steps::format::InternalRustfmt;
|
||||
use crate::core::build_steps::test::TestTarget;
|
||||
use crate::core::build_steps::vendor::VENDOR_DIR;
|
||||
use crate::core::builder::{Builder, Kind};
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::flags::{self, Subcommand};
|
||||
use crate::core::config::{BootstrapOverrideLld, Config, DryRun, LlvmLibunwind, TargetSelection};
|
||||
use crate::core::metadata::Crate;
|
||||
use crate::utils::build_stamp::BuildStamp;
|
||||
use crate::utils::channel::GitInfo;
|
||||
use crate::utils::exec::{BootstrapCommand, ExecutionContext, command};
|
||||
@@ -50,141 +53,6 @@ pub mod cli_main;
|
||||
mod core;
|
||||
mod utils;
|
||||
|
||||
const LLVM_TOOLS: &[&str] = &[
|
||||
"llvm-cov", // used to generate coverage report
|
||||
"llvm-nm", // used to inspect binaries; it shows symbol names, their sizes and visibility
|
||||
"llvm-objcopy", // used to transform ELFs into binary format which flashing tools consume
|
||||
"llvm-objdump", // used to disassemble programs
|
||||
"llvm-profdata", // used to inspect and merge files generated by profiles
|
||||
"llvm-readobj", // used to get information from ELFs/objects that the other tools don't provide
|
||||
"llvm-size", // used to prints the size of the linker sections of a program
|
||||
"llvm-strip", // used to discard symbols from binary files to reduce their size
|
||||
"llvm-ar", // used for creating and modifying archive files
|
||||
"llvm-as", // used to convert LLVM assembly to LLVM bitcode
|
||||
"llvm-dis", // used to disassemble LLVM bitcode
|
||||
"llvm-link", // Used to link LLVM bitcode
|
||||
"llc", // used to compile LLVM bytecode
|
||||
"opt", // used to optimize LLVM bytecode
|
||||
];
|
||||
|
||||
/// LLD file names for all flavors.
|
||||
const LLD_FILE_NAMES: &[&str] = &["ld.lld", "ld64.lld", "lld-link", "wasm-ld"];
|
||||
|
||||
/// Extra `--check-cfg` to add when building the compiler or tools
|
||||
/// (Mode restriction, config name, config values (if any))
|
||||
#[expect(clippy::type_complexity)] // It's fine for hard-coded list and type is explained above.
|
||||
const EXTRA_CHECK_CFGS: &[(Option<Mode>, &str, Option<&[&'static str]>)] = &[
|
||||
(Some(Mode::Rustc), "bootstrap", None),
|
||||
(Some(Mode::Codegen), "bootstrap", None),
|
||||
(Some(Mode::ToolRustcPrivate), "bootstrap", None),
|
||||
(Some(Mode::ToolStd), "bootstrap", None),
|
||||
(Some(Mode::ToolRustcPrivate), "rust_analyzer", None),
|
||||
(Some(Mode::ToolStd), "rust_analyzer", None),
|
||||
// Any library specific cfgs like `target_os`, `target_arch` should be put in
|
||||
// priority the `[lints.rust.unexpected_cfgs.check-cfg]` table
|
||||
// in the appropriate `library/{std,alloc,core}/Cargo.toml`
|
||||
];
|
||||
|
||||
/// A structure representing a Rust compiler.
|
||||
///
|
||||
/// Each compiler has a `stage` that it is associated with and a `host` that
|
||||
/// corresponds to the platform the compiler runs on. This structure is used as
|
||||
/// a parameter to many methods below.
|
||||
#[derive(Eq, PartialOrd, Ord, Clone, Copy, Debug)]
|
||||
pub struct Compiler {
|
||||
stage: u32,
|
||||
host: TargetSelection,
|
||||
/// Indicates whether the compiler was forced to use a specific stage.
|
||||
/// This field is ignored in `Hash` and `PartialEq` implementations as only the `stage`
|
||||
/// and `host` fields are relevant for those.
|
||||
forced_compiler: bool,
|
||||
}
|
||||
|
||||
impl std::hash::Hash for Compiler {
|
||||
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
|
||||
self.stage.hash(state);
|
||||
self.host.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Compiler {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.stage == other.stage && self.host == other.host
|
||||
}
|
||||
}
|
||||
|
||||
/// Represents a codegen backend.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
|
||||
pub enum CodegenBackendKind {
|
||||
#[default]
|
||||
Llvm,
|
||||
Cranelift,
|
||||
Gcc,
|
||||
Custom(String),
|
||||
}
|
||||
|
||||
impl CodegenBackendKind {
|
||||
/// Name of the codegen backend, as identified in the `compiler` directory
|
||||
/// (`rustc_codegen_<name>`).
|
||||
pub fn name(&self) -> &str {
|
||||
match self {
|
||||
CodegenBackendKind::Llvm => "llvm",
|
||||
CodegenBackendKind::Cranelift => "cranelift",
|
||||
CodegenBackendKind::Gcc => "gcc",
|
||||
CodegenBackendKind::Custom(name) => name,
|
||||
}
|
||||
}
|
||||
|
||||
/// Name of the codegen backend's crate, e.g. `rustc_codegen_cranelift`.
|
||||
pub fn crate_name(&self) -> String {
|
||||
format!("rustc_codegen_{}", self.name())
|
||||
}
|
||||
|
||||
pub fn is_llvm(&self) -> bool {
|
||||
matches!(self, Self::Llvm)
|
||||
}
|
||||
|
||||
pub fn is_cranelift(&self) -> bool {
|
||||
matches!(self, Self::Cranelift)
|
||||
}
|
||||
|
||||
pub fn is_gcc(&self) -> bool {
|
||||
matches!(self, Self::Gcc)
|
||||
}
|
||||
}
|
||||
|
||||
impl std::str::FromStr for CodegenBackendKind {
|
||||
type Err = &'static str;
|
||||
|
||||
fn from_str(s: &str) -> Result<Self, Self::Err> {
|
||||
match s.to_lowercase().as_str() {
|
||||
"" => Err("Invalid empty backend name"),
|
||||
"gcc" => Ok(Self::Gcc),
|
||||
"llvm" => Ok(Self::Llvm),
|
||||
"cranelift" => Ok(Self::Cranelift),
|
||||
_ => Ok(Self::Custom(s.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(PartialEq, Eq, Copy, Clone, Debug)]
|
||||
pub enum TestTarget {
|
||||
/// Run unit, integration and doc tests (default).
|
||||
Default,
|
||||
/// Run unit, integration, doc tests, examples, bins, benchmarks (no doc tests).
|
||||
AllTargets,
|
||||
/// Only run doc tests.
|
||||
DocOnly,
|
||||
/// Only run unit and integration tests.
|
||||
Tests,
|
||||
}
|
||||
|
||||
impl TestTarget {
|
||||
fn runs_doctests(&self) -> bool {
|
||||
matches!(self, TestTarget::DocOnly | TestTarget::Default)
|
||||
}
|
||||
}
|
||||
|
||||
pub enum GitRepo {
|
||||
Rustc,
|
||||
Llvm,
|
||||
@@ -260,20 +128,6 @@ pub struct Build {
|
||||
step_graph: std::cell::RefCell<crate::utils::step_graph::StepGraph>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Crate {
|
||||
name: String,
|
||||
deps: HashSet<String>,
|
||||
path: PathBuf,
|
||||
features: Vec<String>,
|
||||
}
|
||||
|
||||
impl Crate {
|
||||
fn local_path(&self, build: &Build) -> PathBuf {
|
||||
self.path.strip_prefix(&build.config.src).unwrap().into()
|
||||
}
|
||||
}
|
||||
|
||||
/// When building Rust various objects are handled differently.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum DependencyType {
|
||||
@@ -2024,54 +1878,3 @@ fn chmod(path: &Path, perms: u32) {
|
||||
}
|
||||
#[cfg(windows)]
|
||||
fn chmod(_path: &Path, _perms: u32) {}
|
||||
|
||||
impl Compiler {
|
||||
pub fn new(stage: u32, host: TargetSelection) -> Self {
|
||||
Self { stage, host, forced_compiler: false }
|
||||
}
|
||||
|
||||
pub fn forced_compiler(&mut self, forced_compiler: bool) {
|
||||
self.forced_compiler = forced_compiler;
|
||||
}
|
||||
|
||||
/// Returns `true` if this is a snapshot compiler for `build`'s configuration
|
||||
pub fn is_snapshot(&self, build: &Build) -> bool {
|
||||
self.stage == 0 && self.host == build.host_target
|
||||
}
|
||||
|
||||
/// Indicates whether the compiler was forced to use a specific stage.
|
||||
pub fn is_forced_compiler(&self) -> bool {
|
||||
self.forced_compiler
|
||||
}
|
||||
}
|
||||
|
||||
fn envify(s: &str) -> String {
|
||||
// Converting foo-bar to FOO_BAR is a fairly idomatic mapping to an environment variable name.
|
||||
// We also convert '.' to '_' to fix https://github.com/rust-lang/rust/issues/158090
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
'-' | '.' => '_',
|
||||
c => c,
|
||||
})
|
||||
.flat_map(|c| c.to_uppercase())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Ensures that the behavior dump directory is properly initialized.
|
||||
pub fn prepare_behaviour_dump_dir(build: &Build) {
|
||||
static INITIALIZED: OnceLock<bool> = OnceLock::new();
|
||||
|
||||
let dump_path = build.out.join("bootstrap-shims-dump");
|
||||
|
||||
let initialized = INITIALIZED.get().unwrap_or(&false);
|
||||
if !initialized {
|
||||
// clear old dumps
|
||||
if dump_path.exists() {
|
||||
t!(fs::remove_dir_all(&dump_path));
|
||||
}
|
||||
|
||||
t!(fs::create_dir_all(&dump_path));
|
||||
|
||||
t!(INITIALIZED.set(true));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,10 +7,12 @@ use std::{fs, io};
|
||||
|
||||
use sha2::digest::Digest;
|
||||
|
||||
use crate::Mode;
|
||||
use crate::core::backend::CodegenBackendKind;
|
||||
use crate::core::builder::Builder;
|
||||
use crate::core::compiler::Compiler;
|
||||
use crate::core::config::TargetSelection;
|
||||
use crate::utils::helpers::{self, hex_encode, mtime, t};
|
||||
use crate::{CodegenBackendKind, Compiler, Mode};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
@@ -571,6 +571,25 @@ pub fn set_file_times<P: AsRef<Path>>(path: P, times: fs::FileTimes) -> io::Resu
|
||||
f.set_times(times)
|
||||
}
|
||||
|
||||
/// Converts a target-tuple or other string into
|
||||
/// [the form expected by cargo environment variable names][cargo-env].
|
||||
///
|
||||
/// For example:
|
||||
/// - `x86_64-unknown-linux-gnu` => `X86_64_UNKNOWN_LINUX_GNU`.
|
||||
///
|
||||
/// [cargo-env]: https://doc.rust-lang.org/cargo/reference/config.html#environment-variables
|
||||
pub(crate) fn envify(s: &str) -> String {
|
||||
// Converting foo-bar to FOO_BAR is a fairly idomatic mapping to an environment variable name.
|
||||
// We also convert '.' to '_' to fix https://github.com/rust-lang/rust/issues/158090
|
||||
s.chars()
|
||||
.map(|c| match c {
|
||||
'-' | '.' => '_',
|
||||
c => c,
|
||||
})
|
||||
.flat_map(|c| c.to_uppercase())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Exits the process by calling [`std::process::exit`].
|
||||
///
|
||||
/// In CI, extra information will be printed to make failures easier to investigate.
|
||||
|
||||
@@ -3,8 +3,8 @@ use std::io::Write;
|
||||
use std::path::PathBuf;
|
||||
|
||||
use crate::utils::helpers::{
|
||||
check_cfg_arg, extract_beta_rev, hex_encode, make, set_file_times, submodule_path_of_paths,
|
||||
symlink_dir,
|
||||
check_cfg_arg, envify, extract_beta_rev, hex_encode, make, set_file_times,
|
||||
submodule_path_of_paths, symlink_dir,
|
||||
};
|
||||
use crate::utils::tests::TestCtx;
|
||||
|
||||
@@ -119,3 +119,21 @@ fn test_submodule_path_of() {
|
||||
// Make sure paths that only share a string prefix with a submodule are not matched.
|
||||
assert_eq!(submodule_path_of_paths(&submodules, "src/tools/cargo-vendor"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_envify() {
|
||||
struct Case {
|
||||
input: &'static str,
|
||||
expected: &'static str,
|
||||
}
|
||||
let cases = &[
|
||||
Case { input: "x86_64-unknown-linux-gnu", expected: "X86_64_UNKNOWN_LINUX_GNU" },
|
||||
// Arbitrary target containing `.` from the tier-3 target list.
|
||||
Case { input: "thumbv8m.base-none-eabi", expected: "THUMBV8M_BASE_NONE_EABI" },
|
||||
];
|
||||
|
||||
for &Case { input, expected } in cases {
|
||||
let actual = envify(input);
|
||||
assert_eq!(actual, expected, "input = {input:?}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,4 +19,16 @@ if [ "${DIST_TRY_BUILD:-0}" == "0" ]; then
|
||||
CC=/rustroot/bin/cc CXX=/rustroot/bin/c++ python3 ../x.py dist \
|
||||
gcc-dev \
|
||||
gcc
|
||||
# We confirm that the built GCC has support for the `retain` attribute.
|
||||
# FIXME: Maybe get the path from `.x.py` instead?
|
||||
gcc_path="./build/$HOSTS/gcc/$HOSTS/install/bin/gcc"
|
||||
c_code='int x __attribute__((used, retain));'
|
||||
if echo "$c_code" | "$gcc_path" -S -x c -o - - | grep -i '"a.*R"'; then
|
||||
echo "retain attribute is supported"
|
||||
else
|
||||
echo "retain attribute is not supported"
|
||||
# We display the generated asm just in case...
|
||||
echo "$c_code" | "$gcc_path" -S -x c -o - -
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
@@ -4,6 +4,27 @@ set -eux
|
||||
|
||||
source shared.sh
|
||||
|
||||
# We have to build our own binutils for the GCC build, because the default CentOS 7 binutils are
|
||||
# too old, and they do not support `SHF_GNU_RETAIN`.
|
||||
BINUTILS="2.47"
|
||||
curl https://ci-mirrors.rust-lang.org/rustc/gcc/binutils-$BINUTILS.tar.xz | xzcat | tar xf -
|
||||
mkdir binutils-build
|
||||
cd binutils-build
|
||||
hide_output ../binutils-$BINUTILS/configure --prefix=/rustroot
|
||||
hide_output make -j$(nproc)
|
||||
hide_output make install
|
||||
|
||||
cd ..
|
||||
rm -rf binutils-build binutils-$BINUTILS
|
||||
|
||||
if echo '.section .test,"awR",@progbits' | as - -o /dev/null 2>/dev/null; then
|
||||
echo "binutils assembler supports SHF_GNU_RETAIN"
|
||||
else
|
||||
echo "binutils assembler DOES NOT support SHF_GNU_RETAIN"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
|
||||
# Note: in the future when bumping to version 10.1.0, also take care of the sed block below.
|
||||
# This version is specified in the Dockerfile
|
||||
GCC=$GCC_VERSION
|
||||
@@ -36,6 +57,7 @@ sed -i'' 's|ftp://gcc\.gnu\.org/pub/gcc/infrastructure|https://ci-mirrors.rust-l
|
||||
mkdir ../gcc-build
|
||||
cd ../gcc-build
|
||||
|
||||
export PATH=/rustroot/bin:$PATH
|
||||
# '-fno-reorder-blocks-and-partition' is required to
|
||||
# enable BOLT optimization of the C++ standard library,
|
||||
# which is included in librustc_driver.so
|
||||
|
||||
@@ -312,7 +312,7 @@ auto:
|
||||
- name: dist-x86_64-illumos
|
||||
<<: *job-linux-4c
|
||||
|
||||
- <<: [*job-dist-x86_64-linux, *job-linux-36c-codebuild]
|
||||
- <<: [*job-dist-x86_64-linux, *job-linux-32c-ec2]
|
||||
|
||||
- name: dist-x86_64-linux-alt
|
||||
env:
|
||||
|
||||
@@ -87,6 +87,7 @@
|
||||
- [\*-unknown-l4re](platform-support/l4re.md)
|
||||
- [\*-unknown-trusty](platform-support/trusty.md)
|
||||
- [\*-kmc-solid_\*](platform-support/kmc-solid.md)
|
||||
- [bpf\*-unknown-none](platform-support/bpf-unknown-none.md)
|
||||
- [csky-unknown-linux-gnuabiv2\*](platform-support/csky-unknown-linux-gnuabiv2.md)
|
||||
- [hexagon-unknown-linux-musl](platform-support/hexagon-unknown-linux-musl.md)
|
||||
- [hexagon-unknown-none-elf](platform-support/hexagon-unknown-none-elf.md)
|
||||
|
||||
@@ -330,8 +330,8 @@ target | std | host | notes
|
||||
[`armv7a-nuttx-eabi`](platform-support/nuttx.md) | ✓ | | ARMv7-A with NuttX
|
||||
[`armv7a-nuttx-eabihf`](platform-support/nuttx.md) | ✓ | | ARMv7-A with NuttX, hardfloat
|
||||
[`avr-none`](platform-support/avr-none.md) | * | | AVR; requires `-Zbuild-std=core` and `-Ctarget-cpu=...`
|
||||
`bpfeb-unknown-none` | * | | BPF (big endian)
|
||||
`bpfel-unknown-none` | * | | BPF (little endian)
|
||||
[`bpfeb-unknown-none`](platform-support/bpf-unknown-none.md) | * | | BPF (big endian)
|
||||
[`bpfel-unknown-none`](platform-support/bpf-unknown-none.md) | * | | BPF (little endian)
|
||||
[`csky-unknown-linux-gnuabiv2`](platform-support/csky-unknown-linux-gnuabiv2.md) | ✓ | | C-SKY abiv2 Linux (little endian)
|
||||
[`csky-unknown-linux-gnuabiv2hf`](platform-support/csky-unknown-linux-gnuabiv2.md) | ✓ | | C-SKY abiv2 Linux, hardfloat (little endian)
|
||||
[`hexagon-unknown-linux-musl`](platform-support/hexagon-unknown-linux-musl.md) | ✓ | | Hexagon Linux with musl 1.2.5
|
||||
|
||||
171
src/doc/rustc/src/platform-support/bpf-unknown-none.md
Normal file
171
src/doc/rustc/src/platform-support/bpf-unknown-none.md
Normal file
@@ -0,0 +1,171 @@
|
||||
# `bpf*-unknown-none`
|
||||
|
||||
**Tier: 3**
|
||||
|
||||
* `bpfeb-unknown-none` (big endian)
|
||||
* `bpfel-unknown-none` (little endian)
|
||||
|
||||
Targets for the 64-bit [BPF virtual machine][ebpf].
|
||||
|
||||
## Target maintainers
|
||||
|
||||
[@nagisa](https://github.com/nagisa) [@vadorovsky](https://github.com/vadorovsky)
|
||||
|
||||
## Requirements
|
||||
|
||||
BPF targets require a Rust toolchain with the `rust-src` component. In
|
||||
addition, you must install the [bpf-linker].
|
||||
|
||||
They don't support std and alloc and are meant for a `no_std` environment.
|
||||
|
||||
`extern "C"` uses the [BPF ABI calling convention][bpf-abi].
|
||||
|
||||
Produced binaries use the ELF format.
|
||||
|
||||
BPF virtual machines provide a [JIT compiler][jit] that compiles the BPF
|
||||
bytecode into the native host architecture.
|
||||
|
||||
Running BPF programs on most host architectures requires Linux kernel 4.18,
|
||||
[that introduced BTF][linux-commit-btf], or newer. On RISC-V hosts that
|
||||
requirement goes up to [5.7][linux-commit-riscv], on PowerPC32 - to [5.13]
|
||||
[linux-commit-ppc32], and on LoongArch - to [6.1][linux-commit-loongarch].
|
||||
|
||||
## Building the target
|
||||
|
||||
You can build Rust with support for BPF targets by adding them to the `target`
|
||||
list in `config.toml`:
|
||||
|
||||
```toml
|
||||
[build]
|
||||
target = ["bpfeb-unknown-none", "bpfel-unknown-none"]
|
||||
```
|
||||
|
||||
## Building Rust programs
|
||||
|
||||
Rust does not yet ship pre-compiled artifacts for this target. To compile for
|
||||
this target, you will either need to build Rust with the target enabled (see
|
||||
"Building the target" above), or build your own copy of `core` by using
|
||||
`build-std` or similar.
|
||||
|
||||
Building the BPF target requires specifying it explicitly. Users can either
|
||||
add it to the `target` list in `config.toml`:
|
||||
|
||||
```toml
|
||||
[build]
|
||||
target = ["bpfel-unknown-none"]
|
||||
```
|
||||
|
||||
Or specify it directly in the `cargo build` invocation:
|
||||
|
||||
```console
|
||||
cargo +nightly build -Z build-std=core --target bpfel-unknown-none
|
||||
```
|
||||
|
||||
BPF has its own debug info format called [BTF][btf].
|
||||
|
||||
BPF targets use [bpf-linker], an LLVM bitcode linker. In future, they may
|
||||
migrate to the GNU flavor of linker, see the details in the [following issue]
|
||||
[bpf-object-linking].
|
||||
|
||||
## Error handling
|
||||
|
||||
There is no concept of stack unwinding in BPF, therefore BPF programs are
|
||||
expected to handle errors in a recoverable manner. Therefore most BPF programs
|
||||
written in Rust use the following panic handler implementation:
|
||||
|
||||
```rust,ignore (a panic handler implementation specific to BPF targets)
|
||||
#[cfg(not(test))]
|
||||
#[panic_handler]
|
||||
fn panic(_info: &core::panic::PanicInfo) -> ! {
|
||||
loop {}
|
||||
}
|
||||
```
|
||||
|
||||
Infinite loops are forbidden by the BPF verifier. Therefore, if the program
|
||||
contains any code which can panic, the BPF VM refuses to load it.
|
||||
|
||||
## Testing
|
||||
|
||||
BPF bytecode needs to be executed on a BPF virtual machine, like the one
|
||||
provided by the Linux kernel or one of the user-space implementations like
|
||||
[rbpf][rbpf]. None of them support running Rust `#[test]` functions. One of the
|
||||
reasons is the lack of support for panicking.
|
||||
|
||||
Therefore, unit tests need to run on the host system. That requirement can be
|
||||
enforced by the following conditional check:
|
||||
|
||||
```rust
|
||||
#[cfg(all(not(target_arch = "bpf"), test))]
|
||||
mod test {}
|
||||
```
|
||||
|
||||
## Cross-compilation toolchains
|
||||
|
||||
BPF programs are always cross-compiled from a host (e.g.
|
||||
`x86_64-unknown-linux-*`) for a BPF target (e.g. `bpfel-unknown-none`).
|
||||
|
||||
The endianness of a chosen BPF target needs to match the endianness of the BPF
|
||||
VM host on which the program is supposed to run.
|
||||
|
||||
The architecture of the BPF VM host often has an impact on types that the BPF
|
||||
programs should use. For example [kprobes][kprobe], [fprobes][fprobe] and
|
||||
[uprobes][uprobe] allow dynamic function tracing and lookup into host registers
|
||||
through the [`pt_regs`][pt-regs] struct, which differs across architectures.
|
||||
|
||||
That difference is still not a concern of the compiler. Instead, it should be
|
||||
handled by the developers. [Aya][aya] (the library for writing Linux BPF
|
||||
programs and the main consumer of BPF targets in Rust) handles that by
|
||||
providing the [`aya-ebpf-cty`][aya-ebpf-cty] crate, with type aliases similar
|
||||
to those provided by [`core:ffi`][core-ffi]. [`aya-ebpf-cty`][aya-ebpf-cty]
|
||||
allows to specify the VM target through the `CARGO_CFG_BPF_TARGET_ARCH`
|
||||
environment variable (e.g. `CARGO_CFG_BPF_TARGET_ARCH=aarch64`).
|
||||
|
||||
## C code
|
||||
|
||||
It's possible to link a Rust BPF project to bitcode or object files which are
|
||||
built from C code with [clang][clang]. It can be done using a `rustc-link-lib`
|
||||
instruction in `build.rs`. Example:
|
||||
|
||||
```rust,no_run
|
||||
use std::{env, process::Command};
|
||||
|
||||
let out_dir = env::var("OUT_DIR").unwrap();
|
||||
let c_module = "my_module.bpf.c";
|
||||
let s = Command::new("clang")
|
||||
.arg("-I")
|
||||
.arg("src/")
|
||||
.arg("-O2")
|
||||
.arg("-emit-llvm")
|
||||
.arg("-target")
|
||||
.arg("bpf")
|
||||
.arg("-c")
|
||||
.arg("-g")
|
||||
.arg(c_module)
|
||||
.arg("-o")
|
||||
.arg(format!("{out_dir}/my_module.bpf.o"))
|
||||
.status()
|
||||
.unwrap();
|
||||
assert!(s.success());
|
||||
println!("cargo:rustc-link-search=native={out_dir}");
|
||||
println!("cargo:rustc-link-lib=link-arg={out_dir}/my_module.bpf.o");
|
||||
```
|
||||
|
||||
[ebpf]: https://ebpf.io/
|
||||
[bpf-linker]: https://github.com/aya-rs/bpf-linker
|
||||
[bpf-abi]: https://www.kernel.org/doc/html/v6.13/bpf/standardization/abi.html
|
||||
[jit]: https://www.kernel.org/doc/html/v6.13/networking/filter.html#jit-compiler
|
||||
[linux-commit-btf]: https://github.com/torvalds/linux/commit/69b693f0a
|
||||
[linux-commit-riscv]: https://github.com/torvalds/linux/commit/5f316b65e
|
||||
[linux-commit-ppc32]: https://github.com/torvalds/linux/commit/51c66ad84
|
||||
[linux-commit-loongarch]: https://github.com/torvalds/linux/commit/5dc615520
|
||||
[btf]: https://www.kernel.org/doc/html/v6.13/bpf/btf.html
|
||||
[bpf-object-linking]: https://github.com/rust-lang/rust/issues/135175
|
||||
[rbpf]: https://github.com/qmonnet/rbpf
|
||||
[kprobe]: https://www.kernel.org/doc/html/v6.13/trace/kprobes.html
|
||||
[fprobe]: https://www.kernel.org/doc/html/v6.13/trace/fprobe.html
|
||||
[uprobe]: https://www.kernel.org/doc/html/v6.13/trace/uprobetracer.html
|
||||
[pt-regs]: https://elixir.bootlin.com/linux/v6.12.6/source/arch/x86/include/uapi/asm/ptrace.h#L44
|
||||
[aya]: https://aya-rs.dev
|
||||
[aya-ebpf-cty]: https://github.com/aya-rs/aya/tree/main/ebpf/aya-ebpf-cty
|
||||
[core-ffi]: https://doc.rust-lang.org/stable/core/ffi/index.html
|
||||
[clang]: https://clang.llvm.org/
|
||||
@@ -5301,7 +5301,7 @@ async function showResults(docSearch, results, goToFirst, filterCrates) {
|
||||
}
|
||||
const crateSearch = document.getElementById("crate-search");
|
||||
if (crateSearch) {
|
||||
// #crate-search is an input element
|
||||
// #crate-search is a `<select>` element.
|
||||
// @ts-expect-error
|
||||
crateSearch.addEventListener("input", updateCrate);
|
||||
}
|
||||
|
||||
@@ -40,8 +40,9 @@ cargo run -- ../tests/pass/empty_main.rs
|
||||
|
||||
## DAP Prototype
|
||||
|
||||
Priroda's `--dap` mode speaks a bounded Debug Adapter Protocol prototype over
|
||||
stdio. It currently supports the startup handshake, stops at the first
|
||||
Priroda speaks a bounded Debug Adapter Protocol prototype over stdio with
|
||||
`--dap`, or over TCP with `--port N`. It currently supports the startup
|
||||
handshake, stops at the first
|
||||
user-relevant source location after `configurationDone`, reports one current
|
||||
stack frame, exposes one flat Locals scope, and maps `list_locals()` into DAP
|
||||
variables with no child expansion.
|
||||
@@ -50,6 +51,82 @@ The `next` and `stepIn` requests are wired to Priroda's existing source-line
|
||||
step so VS Code can drive one visible step. They are not true DAP step-over or
|
||||
step-in semantics yet.
|
||||
|
||||
### VS Code
|
||||
|
||||
VS Code can start Priroda as a TCP DAP server and then attach to that server
|
||||
when you run the debugger configuration. The launch configuration does not spawn
|
||||
Priroda directly; it starts a background task and then connects through
|
||||
`debugServer`.
|
||||
|
||||
`debugServer` tells VS Code to connect to an already-running adapter, but VS Code
|
||||
still requires the launch configuration's `type` to be one it knows. Priroda has
|
||||
no installed extension, so the configuration uses VS Code's built-in `node`
|
||||
debug type as the registered editor-side type. `debugServer` redirects the DAP
|
||||
transport to Priroda before the Node adapter is spawned, so no custom Priroda
|
||||
extension is needed. The configuration uses `request: "attach"`, which makes VS
|
||||
Code send the DAP `attach` request; Priroda accepts `attach` as the same startup
|
||||
transition as `launch`. A richer custom Priroda extension is deferred to future
|
||||
graphical features.
|
||||
|
||||
The templates assume `${workspaceFolder}` is the `miri/priroda` directory that
|
||||
contains them. Copy them into that directory's `.vscode/`, or edit
|
||||
`--manifest-path` and the final `args` entry when using them from elsewhere:
|
||||
|
||||
```sh
|
||||
mkdir -p /path/to/miri/priroda/.vscode
|
||||
cp vscode_launch.json /path/to/miri/priroda/.vscode/launch.json
|
||||
cp vscode_tasks.json /path/to/miri/priroda/.vscode/tasks.json
|
||||
```
|
||||
|
||||
Before running the debugger configuration, make sure:
|
||||
|
||||
- The Rust file path at the end of `args` is the file you want Priroda to run.
|
||||
- Port `4711` is free, or both `--port` and `debugServer` use the same different
|
||||
port.
|
||||
- `MIRI_SYSROOT` points at a Miri sysroot, for example from
|
||||
`cargo +miri miri setup --print-sysroot`. VS Code resolves `${env:MIRI_SYSROOT}`
|
||||
from the environment it was started with, not from the task's `env`, so export
|
||||
it in your shell before launching VS Code, or replace the argument with the
|
||||
absolute sysroot path.
|
||||
- The `cargo` in `command` resolves to the `miri` toolchain's cargo, so the task
|
||||
builds Priroda with `rustc_private`. That is automatic when the workspace is
|
||||
`miri/priroda`; when using the templates from another project, pass `+miri` as
|
||||
the first `cargo` argument.
|
||||
|
||||
The task runs Priroda through `cargo run` against the Priroda crate:
|
||||
|
||||
```sh
|
||||
cargo run --manifest-path /path/to/miri/priroda/Cargo.toml -- \
|
||||
--dap --port 4711 --sysroot "$MIRI_SYSROOT" /path/to/project/src/main.rs
|
||||
```
|
||||
|
||||
Edit the final argument in `args` to point at the Rust file you want Priroda to
|
||||
run (the checked-in default is `../tests/pass/empty_main.rs`). This task
|
||||
argument, not `launch.json`, selects the interpreted program.
|
||||
|
||||
Running through `cargo run` sets the dynamic library path automatically. The
|
||||
`priroda` binary links rustc's shared libraries, so running it directly, or via
|
||||
`cargo install`, still needs `LD_LIBRARY_PATH` to point at the pinned `miri`
|
||||
toolchain's `lib` directory; a future packaging step (an rpath, or shipping
|
||||
Priroda next to Miri) will remove that requirement.
|
||||
|
||||
Once Priroda prints `priroda dap listening on 127.0.0.1:4711`, VS Code treats
|
||||
the background task as ready and connects with:
|
||||
|
||||
```json
|
||||
{
|
||||
"type": "node",
|
||||
"request": "attach",
|
||||
"preLaunchTask": "Priroda: Start DAP Server",
|
||||
"debugServer": 4711
|
||||
}
|
||||
```
|
||||
|
||||
Priroda accepts one TCP connection and waits for VS Code before running the DAP
|
||||
handshake. VS Code's built-in JavaScript debugger may also send extension
|
||||
requests of its own, such as `enableNetworking` for its network preview; Priroda
|
||||
skips unrecognized requests rather than failing, so those are ignored.
|
||||
|
||||
## Test
|
||||
|
||||
Priroda's CLI tests also need `MIRI_SYSROOT`. Run them from `miri/priroda/`:
|
||||
|
||||
@@ -505,17 +505,14 @@ impl<'tcx> PrirodaContext<'tcx> {
|
||||
// view before fields can be projected. Structs use their sole
|
||||
// variant directly. Keep the display name tied to the same choice.
|
||||
let (variant_idx, down, name) = if def.is_enum() {
|
||||
let Some(variant_idx) =
|
||||
self.ecx.read_discriminant(&op).discard_err()
|
||||
else {
|
||||
let Some(variant_idx) = self.ecx.read_discriminant(&op).discard_err() else {
|
||||
// FIXME: expose this as an explicit render error when
|
||||
// Priroda grows structured value states. Falling back to
|
||||
// bytes keeps today's UI usable but hides why the enum
|
||||
// could not be source-shaped.
|
||||
return self.render_op(op);
|
||||
};
|
||||
let Some(down) =
|
||||
self.ecx.project_downcast(&op, variant_idx).discard_err()
|
||||
let Some(down) = self.ecx.project_downcast(&op, variant_idx).discard_err()
|
||||
else {
|
||||
// FIXME: distinguish invalid/uninitialized discriminants
|
||||
// from projection bugs in the rendered output once locals
|
||||
@@ -541,8 +538,7 @@ impl<'tcx> PrirodaContext<'tcx> {
|
||||
let field_idx = FieldIdx::from_usize(i);
|
||||
// `project_field` avoids manual offset math and works for both
|
||||
// immediate and memory-backed operands through `Projectable`.
|
||||
let Some(field_op) =
|
||||
self.ecx.project_field(&down, field_idx).discard_err()
|
||||
let Some(field_op) = self.ecx.project_field(&down, field_idx).discard_err()
|
||||
else {
|
||||
// FIXME: preserve the successfully rendered fields and
|
||||
// mark only this field as unavailable once the value model
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
use std::io::{self, BufReader, BufWriter};
|
||||
use std::io::{self, BufReader, BufWriter, Read, Write};
|
||||
use std::net::{TcpListener, TcpStream};
|
||||
|
||||
use emmy_dap_types::errors::ServerError;
|
||||
use emmy_dap_types::prelude::events::{ExitedEventBody, StoppedEventBody};
|
||||
@@ -56,15 +57,23 @@ enum ExecutionOutcome {
|
||||
}
|
||||
|
||||
/// Debug Adapter Protocol frontend.
|
||||
pub(crate) struct Dap;
|
||||
pub(crate) struct Dap {
|
||||
pub(crate) port: Option<u16>,
|
||||
}
|
||||
|
||||
impl Dap {
|
||||
/// Serve DAP requests on stdin/stdout.
|
||||
/// Serve DAP requests on stdin/stdout, or on a TCP socket if `port` is set.
|
||||
pub(crate) fn run_dap_loop<'tcx>(
|
||||
&self,
|
||||
session: &mut PrirodaContext<'tcx>,
|
||||
) -> InterpResult<'tcx> {
|
||||
if let Err(err) = DapSession::stdio().run_requests(session) {
|
||||
let result = if let Some(port) = self.port {
|
||||
DapSession::tcp(port).run_requests(session)
|
||||
} else {
|
||||
DapSession::stdio().run_requests(session)
|
||||
};
|
||||
|
||||
if let Err(err) = result {
|
||||
eprintln!("priroda dap error: {err:?}");
|
||||
}
|
||||
|
||||
@@ -72,15 +81,13 @@ impl Dap {
|
||||
}
|
||||
}
|
||||
|
||||
type DapServer = Server<io::StdinLock<'static>, io::StdoutLock<'static>>;
|
||||
|
||||
/// Owns the DAP stdio transport and dispatches requests into Priroda handlers.
|
||||
struct DapSession {
|
||||
server: DapServer,
|
||||
/// Owns a DAP transport and dispatches requests into Priroda handlers.
|
||||
struct DapSession<R: Read, W: Write> {
|
||||
server: Server<R, W>,
|
||||
state: DapState,
|
||||
}
|
||||
|
||||
impl DapSession {
|
||||
impl DapSession<io::StdinLock<'static>, io::StdoutLock<'static>> {
|
||||
fn stdio() -> Self {
|
||||
Self {
|
||||
server: Server::new(
|
||||
@@ -90,7 +97,37 @@ impl DapSession {
|
||||
state: DapState::Fresh,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl DapSession<TcpStream, TcpStream> {
|
||||
fn tcp(port: u16) -> Self {
|
||||
let listener = match TcpListener::bind(("127.0.0.1", port)) {
|
||||
Ok(listener) => listener,
|
||||
Err(err) => fatal(&format!("failed to listen on DAP TCP socket: {err}")),
|
||||
};
|
||||
eprintln!("priroda dap listening on 127.0.0.1:{port}");
|
||||
let (stream, _) = match listener.accept() {
|
||||
Ok(conn) => conn,
|
||||
Err(err) => fatal(&format!("failed to accept DAP TCP connection: {err}")),
|
||||
};
|
||||
let reader = match stream.try_clone() {
|
||||
Ok(clone) => clone,
|
||||
Err(err) => fatal(&format!("failed to clone DAP TCP stream: {err}")),
|
||||
};
|
||||
|
||||
Self {
|
||||
server: Server::new(BufReader::new(reader), BufWriter::new(stream)),
|
||||
state: DapState::Fresh,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn fatal(message: &str) -> ! {
|
||||
eprintln!("priroda dap: {message}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
|
||||
impl<R: Read, W: Write> DapSession<R, W> {
|
||||
fn run_requests<'tcx>(
|
||||
&mut self,
|
||||
session: &mut PrirodaContext<'tcx>,
|
||||
@@ -99,6 +136,15 @@ impl DapSession {
|
||||
let request = match self.server.poll_request() {
|
||||
Ok(Some(request)) => request,
|
||||
Ok(None) => return Ok(()),
|
||||
// The message body has already been consumed. js-debug can send
|
||||
// commands like `enableNetworking`, which `emmy_dap_types` reports
|
||||
// as parse errors because it has no unknown-command variant.
|
||||
// FIXME: send a DAP error response once unknown commands are
|
||||
// representable.
|
||||
Err(ServerError::ParseError(_)) => {
|
||||
eprintln!("priroda dap: skipping request that could not be deserialized");
|
||||
continue;
|
||||
}
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
|
||||
@@ -138,6 +184,7 @@ impl DapSession {
|
||||
match &request.command {
|
||||
Command::Initialize(_) => self.handle_initialize(),
|
||||
Command::Launch(_) => self.handle_launch(),
|
||||
Command::Attach(_) => self.handle_attach(),
|
||||
Command::ConfigurationDone => self.handle_configuration_done(session),
|
||||
Command::Threads => self.handle_threads(),
|
||||
Command::StackTrace(args) => self.handle_stack_trace(args.thread_id, session),
|
||||
@@ -149,8 +196,7 @@ impl DapSession {
|
||||
Command::StepIn(args) =>
|
||||
self.handle_step(ResponseBody::StepIn, args.thread_id, session),
|
||||
Command::Disconnect(_) => self.handle_disconnect(),
|
||||
Command::Attach(_)
|
||||
| Command::BreakpointLocations(_)
|
||||
Command::BreakpointLocations(_)
|
||||
| Command::Cancel(_)
|
||||
| Command::Completions(_)
|
||||
| Command::DataBreakpointInfo(_)
|
||||
@@ -194,6 +240,19 @@ impl DapSession {
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_attach(&self) -> Result<HandlerSuccess, &'static str> {
|
||||
self.require_state(DapState::Initialized)?;
|
||||
|
||||
// VS Code's extension-free `debugServer` template uses `attach`.
|
||||
// Priroda still starts the same single interpreted session as `launch`.
|
||||
Ok(HandlerSuccess {
|
||||
response: HandlerResponse::Success(ResponseBody::Attach),
|
||||
state: Some(DapState::Launched),
|
||||
events: Vec::new(),
|
||||
outcome: HandlerOutcome::Continue,
|
||||
})
|
||||
}
|
||||
|
||||
fn handle_scopes<'tcx>(
|
||||
&self,
|
||||
frame_id: i64,
|
||||
@@ -555,8 +614,8 @@ impl DapSession {
|
||||
fn require_state(&self, expected: DapState) -> Result<(), &'static str> {
|
||||
if self.state != expected {
|
||||
return Err(match expected {
|
||||
DapState::Initialized => "launch requires initialize",
|
||||
DapState::Launched => "configurationDone requires launch",
|
||||
DapState::Initialized => "launch or attach requires initialize",
|
||||
DapState::Launched => "configurationDone requires launch or attach",
|
||||
_ => "invalid session state for request",
|
||||
});
|
||||
}
|
||||
|
||||
@@ -47,7 +47,7 @@ fn main() {
|
||||
#[derive(Clone, Copy)]
|
||||
enum Frontend {
|
||||
Cli,
|
||||
Dap,
|
||||
Dap { port: Option<u16> },
|
||||
}
|
||||
|
||||
impl Frontend {
|
||||
@@ -57,14 +57,36 @@ impl Frontend {
|
||||
let mut rustc_args = Vec::with_capacity(args.len());
|
||||
let mut parsing_priroda_args = true;
|
||||
|
||||
for (idx, arg) in args.drain(..).enumerate() {
|
||||
if idx != 0 && parsing_priroda_args && arg == "--dap" {
|
||||
frontend = Frontend::Dap;
|
||||
continue;
|
||||
}
|
||||
let mut arg_iter = std::mem::take(args).into_iter();
|
||||
if let Some(program) = arg_iter.next() {
|
||||
rustc_args.push(program);
|
||||
}
|
||||
|
||||
if arg == "--" {
|
||||
parsing_priroda_args = false;
|
||||
while let Some(arg) = arg_iter.next() {
|
||||
if parsing_priroda_args {
|
||||
if arg == "--dap" {
|
||||
if matches!(frontend, Frontend::Cli) {
|
||||
frontend = Frontend::Dap { port: None };
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
if arg == "--port" {
|
||||
let port_str = arg_iter
|
||||
.next()
|
||||
.unwrap_or_else(|| Self::fatal_arg_error("--port requires a value"));
|
||||
frontend = Frontend::Dap { port: Some(Self::parse_port(&port_str)) };
|
||||
continue;
|
||||
}
|
||||
|
||||
if let Some(port_str) = arg.strip_prefix("--port=") {
|
||||
frontend = Frontend::Dap { port: Some(Self::parse_port(port_str)) };
|
||||
continue;
|
||||
}
|
||||
|
||||
if arg == "--" {
|
||||
parsing_priroda_args = false;
|
||||
}
|
||||
}
|
||||
|
||||
rustc_args.push(arg);
|
||||
@@ -73,6 +95,16 @@ impl Frontend {
|
||||
*args = rustc_args;
|
||||
frontend
|
||||
}
|
||||
|
||||
fn parse_port(port: &str) -> u16 {
|
||||
port.parse()
|
||||
.unwrap_or_else(|_| Self::fatal_arg_error("--port requires a valid u16 port number"))
|
||||
}
|
||||
|
||||
fn fatal_arg_error(message: &str) -> ! {
|
||||
eprintln!("priroda: {message}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
struct PrirodaCompilerCalls {
|
||||
@@ -100,7 +132,7 @@ impl rustc_driver::Callbacks for PrirodaCompilerCalls {
|
||||
let mut session = PrirodaContext::new(ecx);
|
||||
let result = match self.frontend {
|
||||
Frontend::Cli => frontend::Cli {}.run_cli_loop(&mut session),
|
||||
Frontend::Dap => frontend::Dap {}.run_dap_loop(&mut session),
|
||||
Frontend::Dap { port } => frontend::Dap { port }.run_dap_loop(&mut session),
|
||||
};
|
||||
|
||||
match result.report_err() {
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
//@ compile-flags: --dap
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,5 @@
|
||||
Content-Length: 85
|
||||
|
||||
{"seq":1,"type":"request","command":"initialize","arguments":{"adapterID":"priroda"}}Content-Length: 60
|
||||
|
||||
{"seq":2,"type":"request","command":"attach","arguments":{}}
|
||||
@@ -0,0 +1,7 @@
|
||||
Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":1,"type":"response","request_seq":1,"success":true,"command":"initialize","body":{"supportsConfigurationDoneRequest":true,"supportsSingleThreadExecutionRequests":true},"error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":2,"type":"event","event":"initialized"}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":3,"type":"response","request_seq":2,"success":true,"command":"attach","error":null}
|
||||
@@ -0,0 +1,3 @@
|
||||
//@ compile-flags: --dap
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1,7 @@
|
||||
Content-Length: 85
|
||||
|
||||
{"seq":1,"type":"request","command":"initialize","arguments":{"adapterID":"priroda"}}Content-Length: 60
|
||||
|
||||
{"seq":2,"type":"request","command":"attach","arguments":{}}Content-Length: 56
|
||||
|
||||
{"seq":3,"type":"request","command":"configurationDone"}
|
||||
@@ -0,0 +1,11 @@
|
||||
Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":1,"type":"response","request_seq":1,"success":true,"command":"initialize","body":{"supportsConfigurationDoneRequest":true,"supportsSingleThreadExecutionRequests":true},"error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":2,"type":"event","event":"initialized"}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":3,"type":"response","request_seq":2,"success":true,"command":"attach","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":4,"type":"response","request_seq":3,"success":true,"command":"configurationDone","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":5,"type":"event","event":"stopped","body":{"reason":"entry","description":null,"threadId":1,"preserveFocusHint":null,"text":null,"allThreadsStopped":true,"hitBreakpointIds":null}}
|
||||
@@ -0,0 +1,3 @@
|
||||
//@ compile-flags: --dap
|
||||
|
||||
fn main() {}
|
||||
@@ -0,0 +1 @@
|
||||
priroda dap: skipping request that could not be deserialized
|
||||
@@ -0,0 +1,9 @@
|
||||
Content-Length: 89
|
||||
|
||||
{"seq":1,"type":"request","command":"enableNetworking","arguments":{"mirrorEvents":true}}Content-Length: 85
|
||||
|
||||
{"seq":2,"type":"request","command":"initialize","arguments":{"adapterID":"priroda"}}Content-Length: 60
|
||||
|
||||
{"seq":3,"type":"request","command":"launch","arguments":{}}Content-Length: 56
|
||||
|
||||
{"seq":4,"type":"request","command":"configurationDone"}
|
||||
@@ -0,0 +1,11 @@
|
||||
Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":1,"type":"response","request_seq":2,"success":true,"command":"initialize","body":{"supportsConfigurationDoneRequest":true,"supportsSingleThreadExecutionRequests":true},"error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":2,"type":"event","event":"initialized"}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":3,"type":"response","request_seq":3,"success":true,"command":"launch","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":4,"type":"response","request_seq":4,"success":true,"command":"configurationDone","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":5,"type":"event","event":"stopped","body":{"reason":"entry","description":null,"threadId":1,"preserveFocusHint":null,"text":null,"allThreadsStopped":true,"hitBreakpointIds":null}}
|
||||
@@ -4,7 +4,7 @@ Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":2,"type":"event","event":"initialized"}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":3,"type":"response","request_seq":2,"success":false,"message":"configurationDone requires launch","command":"configurationDone","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
{"seq":3,"type":"response","request_seq":2,"success":false,"message":"configurationDone requires launch or attach","command":"configurationDone","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
{"seq":4,"type":"response","request_seq":3,"success":true,"command":"disconnect","error":null}Content-Length: {CONTENT_LENGTH}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user