Skip to content

thread 'rustc' panicked at 'Box<dyn Any>' #93002

Closed
@nbittich

Description

@nbittich

Code

use std::{sync::{mpsc, Arc, Mutex}, thread, time::Duration, rc::Rc};

fn main() {
    let m = Mutex::new(String::from("hello"));
    let (tx, rx) = mpsc::channel();
    let cl = tx.clone();
    let cl2 = tx.clone();
    thread::spawn(move || {
        let mut i:i32 = 0;
        let x = Arc::new(String::from("heyyy"));
        while cl
            .send(Arc::new(String::from(format!(
                "hello! {:?}",
                std::time::SystemTime::now()
            ))))
            .is_ok()
        {
            i+=1;
            cl.send(x.clone()).unwrap();
            thread::sleep(Duration::from_secs(2));
            let mut s = m.lock().unwrap();
            *s = String::from(format!("change me! {i}"));
            println!("from thread & mutex: {x:?} / {s}");
        }
    });
    thread::spawn(move || {
        while cl2.send(Arc::new(String::from(format!("here! {:?}", std::time::SystemTime::now())))).is_ok(){
            let mut x = &m.lock().unwrap();
            &*x=String::from("i changed u");
            println!("from thread 2, mutex {x}");
            thread::sleep(Duration::from_secs(1));
        }
    });

    loop {
        match rx.try_recv() {
            Ok(res) => println!("{res}"),
            Err(e) =>{
            thread::sleep(Duration::from_millis(200));
            },
        }
    }
}

Meta

rustc --version --verbose:

rustc 1.58.0 (02072b482 2022-01-11)
binary: rustc
commit-hash: 02072b482a8b5357f7fb5e5637444ae30e423c40
commit-date: 2022-01-11
host: x86_64-apple-darwin
release: 1.58.0
LLVM version: 13.0.0

Error output

thread 'rustc' panicked at 'Box<dyn Any>', /rustc/02072b482a8b5357f7fb5e5637444ae30e423c40/compiler/rustc_errors/src/lib.rs:1115:9

Backtrace

stack backtrace:
   0: std::panicking::begin_panic::<rustc_errors::ExplicitBug>
   1: std::panic::panic_any::<rustc_errors::ExplicitBug>
   2: <rustc_errors::HandlerInner>::span_bug::<rustc_span::span_encoding::Span>
   3: <rustc_errors::Handler>::span_bug::<rustc_span::span_encoding::Span>
   4: rustc_middle::util::bug::opt_span_bug_fmt::<rustc_span::span_encoding::Span>::{closure#0}
   5: rustc_middle::ty::context::tls::with_opt::<rustc_middle::util::bug::opt_span_bug_fmt<rustc_span::span_encoding::Span>::{closure#0}, ()>::{closure#0}
   6: rustc_middle::ty::context::tls::with_opt::<rustc_middle::util::bug::opt_span_bug_fmt<rustc_span::span_encoding::Span>::{closure#0}, ()>
   7: rustc_middle::util::bug::opt_span_bug_fmt::<rustc_span::span_encoding::Span>
   8: rustc_middle::util::bug::span_bug_fmt::<rustc_span::span_encoding::Span>
   9: <rustc_codegen_llvm::context::CodegenCx as rustc_middle::ty::layout::LayoutOfHelpers>::handle_layout_err
  10: <rustc_codegen_llvm::context::CodegenCx as rustc_middle::ty::layout::LayoutOf>::spanned_layout_of::{closure#0}
  11: <rustc_codegen_llvm::context::CodegenCx as rustc_middle::ty::layout::LayoutOf>::spanned_layout_of
  12: <core::iter::adapters::map::Map<core::slice::iter::Iter<rustc_middle::mir::LocalDecl>, rustc_codegen_ssa::mir::analyze::non_ssa_locals<rustc_codegen_llvm::builder::Builder>::{closure#0}> as core::iter::traits::iterator::Iterator>::fold::<(), core::iter::traits::iterator::Iterator::for_each::call<rustc_codegen_ssa::mir::analyze::LocalKind, <alloc::vec::Vec<rustc_codegen_ssa::mir::analyze::LocalKind> as alloc::vec::spec_extend::SpecExtend<rustc_codegen_ssa::mir::analyze::LocalKind, core::iter::adapters::map::Map<core::slice::iter::Iter<rustc_middle::mir::LocalDecl>, rustc_codegen_ssa::mir::analyze::non_ssa_locals<rustc_codegen_llvm::builder::Builder>::{closure#0}>>>::spec_extend::{closure#0}>::{closure#0}>
  13: rustc_codegen_ssa::mir::analyze::non_ssa_locals::<rustc_codegen_llvm::builder::Builder>
  14: rustc_codegen_ssa::mir::codegen_mir::<rustc_codegen_llvm::builder::Builder>
  15: rustc_codegen_ssa::base::codegen_instance::<rustc_codegen_llvm::builder::Builder>
  16: <rustc_middle::mir::mono::MonoItem as rustc_codegen_ssa::mono_item::MonoItemExt>::define::<rustc_codegen_llvm::builder::Builder>
  17: rustc_codegen_llvm::base::compile_codegen_unit::module_codegen
  18: <rustc_query_system::dep_graph::graph::DepGraph<rustc_middle::dep_graph::dep_node::DepKind>>::with_task::<rustc_middle::ty::context::TyCtxt, rustc_span::symbol::Symbol, rustc_codegen_ssa::ModuleCodegen<rustc_codegen_llvm::ModuleLlvm>>
  19: rustc_codegen_llvm::base::compile_codegen_unit
  20: rustc_codegen_ssa::base::codegen_crate::<rustc_codegen_llvm::LlvmCodegenBackend>
  21: <rustc_codegen_llvm::LlvmCodegenBackend as rustc_codegen_ssa::traits::backend::CodegenBackend>::codegen_crate
  22: <rustc_interface::queries::Queries>::ongoing_codegen
  23: <rustc_interface::interface::Compiler>::enter::<rustc_driver::run_compiler::{closure#1}::{closure#2}, core::result::Result<core::option::Option<rustc_interface::queries::Linker>, rustc_errors::ErrorReported>>
  24: rustc_span::with_source_map::<core::result::Result<(), rustc_errors::ErrorReported>, rustc_interface::interface::create_compiler_and_run<core::result::Result<(), rustc_errors::ErrorReported>, rustc_driver::run_compiler::{closure#1}>::{closure#1}>
  25: <scoped_tls::ScopedKey<rustc_span::SessionGlobals>>::set::<rustc_interface::util::setup_callbacks_and_run_in_thread_pool_with_globals<rustc_interface::interface::run_compiler<core::result::Result<(), rustc_errors::ErrorReported>, rustc_driver::run_compiler::{closure#1}>::{closure#0}, core::result::Result<(), rustc_errors::ErrorReported>>::{closure#0}::{closure#0}, core::result::Result<(), rustc_errors::ErrorReported>>
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

Activity

added
C-bugCategory: This is a bug.
I-ICEIssue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️
T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.
on Jan 17, 2022
trentj

trentj commented on Jan 17, 2022

@trentj

Looks like the ICE is fixed on nightly and in 1.59.0-beta.1, although the diagnostic suggestion is still a bit odd:

  --> src/main.rs:40:17
   |
40 |             &*x = String::from("i changed u");
   |             --- ^
   |             |
   |             cannot assign to this expression
   |
help: you might have meant to use pattern destructuring
   |
32 |         while let cl2
   |               +++
matthiaskrgr

matthiaskrgr commented on Jan 17, 2022

@matthiaskrgr
Member

Might be duplicate of #92979

pymongo

pymongo commented on Feb 18, 2022

@pymongo
Contributor

still reproduce in rustc 1.60.0

error: internal compiler error: /rustc/30b3f35c420694a4f24e5a4df00f06073f4f3a37/compiler/rustc_codegen_ssa/src/mir/constant.rs:42:20: encountered bad ConstKind after monomorphizing: Error(DelaySpanBugEmitted(()))
  --> src/lib.rs:99:9
   |
99 |         dbg!(line!());
   |         ^^^^^^^^^^^^^
   |
   = note: this error: internal compiler error originates in the macro `dbg` (in Nightly builds, run with -Z macro-backtrace for more info)

thread 'rustc' panicked at 'Box<dyn Any>', /rustc/30b3f35c420694a4f24e5a4df00f06073f4f3a37/compiler/rustc_errors/src/lib.rs:1106:9
stack backtrace:
   0: std::panicking::begin_panic::<rustc_errors::ExplicitBug>
   1: std::panic::panic_any::<rustc_errors::ExplicitBug>
   2: <rustc_errors::HandlerInner>::span_bug::<rustc_span::span_encoding::Span>
   3: <rustc_errors::Handler>::span_bug::<rustc_span::span_encoding::Span>
   4: rustc_middle::ty::context::tls::with_opt::<rustc_middle::util::bug::opt_span_bug_fmt<rustc_span::span_encoding::Span>::{closure#0}, ()>
   5: rustc_middle::util::bug::opt_span_bug_fmt::<rustc_span::span_encoding::Span>
   6: rustc_middle::util::bug::span_bug_fmt::<rustc_span::span_encoding::Span>
   7: <rustc_codegen_ssa::mir::FunctionCx<rustc_codegen_llvm::builder::Builder>>::codegen_rvalue_operand
   8: rustc_codegen_ssa::mir::codegen_mir::<rustc_codegen_llvm::builder::Builder>
   9: rustc_codegen_llvm::base::compile_codegen_unit::module_codegen
  10: <rustc_query_system::dep_graph::graph::DepGraph<rustc_middle::dep_graph::dep_node::DepKind>>::with_task::<rustc_middle::ty::context::TyCtxt, rustc_span::symbol::Symbol, rustc_codegen_ssa::ModuleCodegen<rustc_codegen_llvm::ModuleLlvm>>
  11: rustc_codegen_llvm::base::compile_codegen_unit
  12: rustc_codegen_ssa::base::codegen_crate::<rustc_codegen_llvm::LlvmCodegenBackend>
  13: <rustc_codegen_llvm::LlvmCodegenBackend as rustc_codegen_ssa::traits::backend::CodegenBackend>::codegen_crate
  14: <rustc_session::session::Session>::time::<alloc::boxed::Box<dyn core::any::Any>, rustc_interface::passes::start_codegen::{closure#0}>
  15: <rustc_interface::passes::QueryContext>::enter::<<rustc_interface::queries::Queries>::ongoing_codegen::{closure#0}::{closure#0}, core::result::Result<alloc::boxed::Box<dyn core::any::Any>, rustc_errors::ErrorReported>>
  16: <rustc_interface::queries::Queries>::ongoing_codegen
  17: rustc_interface::interface::create_compiler_and_run::<core::result::Result<(), rustc_errors::ErrorReported>, rustc_driver::run_compiler::{closure#1}>
note: Some details are omitted, run with `RUST_BACKTRACE=full` for a verbose backtrace.

note: the compiler unexpectedly panicked. this is a bug.

note: we would appreciate a bug report: https://github.com/rust-lang/rust/issues/new?labels=C-bug%2C+I-ICE%2C+T-compiler&template=ice.md

note: rustc 1.60.0-nightly (30b3f35c4 2022-02-17) running on x86_64-unknown-linux-gnu

note: compiler flags: -C embed-bitcode=no -C debuginfo=2 -C incremental

note: some of the compiler flags provided by cargo are hidden

query stack during panic:
end of query stack
warning: `reproduce_ice` (lib test) generated 3 warnings
error: could not compile `reproduce_ice`; 3 warnings emitted
The terminal process "cargo 'test', '--package', 'reproduce_ice', '--lib', '--', 'test', '--exact', '--nocapture'" terminated with exit code: 101.

src/lib.rs

mod prelude {
    pub use std::collections::HashMap;
    pub use std::hash::Hash;
    pub trait Lru<K: Default + Hash + Eq + Clone, V: Default> {
        fn new(capacity: usize) -> Self;
        unsafe fn put(&mut self, key: K, val: V);
        unsafe fn get(&mut self, key: K) -> Option<V>;
    }    
}
use prelude::*;

struct ListNode<K, V> {
    key: K,
    val: V,
    next: *mut ListNode<K, V>,
    prev: *mut ListNode<K, V>
}

impl<K: Default, V: Default> Default for ListNode<K, V> {
    fn default() -> Self {
        Self {
            key: K::default(),
            val: V::default(),
            next: std::ptr::null_mut(),
            prev: std::ptr::null_mut()
        }
    }
}

struct LruImpl<K: Default, V: Default> {
    // TODO limit linkedlist capacity
    // capacity: usize
    head: ListNode<K, V>,
    tail: ListNode<K, V>,
    cache: HashMap<K, *mut ListNode<K, V>>
}

impl<K: Default, V: Default> LruImpl<K, V> {
    unsafe fn detach_node(&mut self, node: *mut ListNode<K, V>) {
        // detach node
        (*(*node).next).prev = (*(*node).prev).next;
        (*(*node).prev).next = (*(*node).next).next;
    }

    /// before: head->...->node->...->tail
    /// after : head->node->...->tail
    unsafe fn move_node_to_head(&mut self, node: *mut ListNode<K, V>) {
        // let a = (*(*node).prev).next;

        // detach node
        if !(*node).prev.is_null() && !(*node).next.is_null() {
            self.detach_node(node);
        }
        
        // head->next connect to node
        (*node).next = (*self.head.next).prev;
        (*self.head.next).prev = node;
        // head connect to node
        self.head.next = node;
        (*node).prev = &mut self.head;
    }
}

impl<K: Default + Hash + Eq + Clone, V: Default + Clone> Lru<K, V> for LruImpl<K, V> {
    fn new(_capacity: usize) -> Self {
        let mut head = ListNode::default();
        let mut tail = ListNode::default();
        head.next = &mut tail;
        tail.prev = &mut head;
        Self {
            head,
            tail,
            cache: HashMap::new()
        }
    }

    unsafe fn put(&mut self, key: K, val: V) {
        if let Some(node_ptr) = self.cache.get(&key) {
            (*(*node_ptr)).val = val;
            self.move_node_to_head(*node_ptr);
            return;
        }

        let mut node = ListNode {
            key,
            val,
            next: self.head.prev,
            prev: &mut self.head,
        };
        self.cache.insert(node.key.clone(), &mut node);
    }

    // FIXME SIGSEGV
    unsafe fn get(&mut self, key: K) -> Option<V> {
        // ownership problem
        // let self_ = self as *mut Self;

        dbg!(line!());
        if let Some(node_ptr) = self.cache.get(&key) {
            dbg!(line!());
            self.move_node_to_head(*node_ptr);
        }

        dbg!(line!());
        let ret = self.cache.get(&key).map(|node_ptr| {
            // (*self_).move_node_to_head(*node_ptr);
            (*(*node_ptr)).val.clone()
        });
        ret
    }
}

#[test]
fn test() {
    let mut lru = LruImpl::<&'static str, &'static str>::new(10);
    unsafe {
        lru.put("key1", "val1");
        lru.put("key2", "val2");
        dbg!(lru.get("key1"));
    }
}
pigflying

pigflying commented on Mar 1, 2022

@pigflying

still reproduce in rustc 1.60.0

rustc --version --verbose
rustc 1.60.0-nightly (17d29dc 2022-01-21)
binary: rustc
commit-hash: 17d29dc
commit-date: 2022-01-21
host: x86_64-apple-darwin
release: 1.60.0-nightly
LLVM version: 13.0.0

nbittich

nbittich commented on Aug 30, 2022

@nbittich
Author

looks fixed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-bugCategory: This is a bug.I-ICEIssue: The compiler panicked, giving an Internal Compilation Error (ICE) ❄️T-compilerRelevant to the compiler team, which will review and decide on the PR/issue.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @trentj@matthiaskrgr@nbittich@pigflying@pymongo

        Issue actions

          thread 'rustc' panicked at 'Box<dyn Any>' · Issue #93002 · rust-lang/rust