Skip to main content

cargo/compiler/job_queue/
job_state.rs

1//! See [`JobState`].
2
3use std::cell::Cell;
4use std::marker;
5use std::mem::DropGuard;
6use std::sync::Arc;
7
8use cargo_util::ProcessBuilder;
9
10use crate::compiler::future_incompat::FutureBreakageItem;
11use crate::compiler::locking::LockKey;
12use crate::compiler::timings::SectionTiming;
13use crate::context::WarningHandling;
14use crate::util::Queue;
15use crate::util::interning::InternedString;
16use crate::{CargoResult, compiler::locking::LockManager};
17
18use super::{Artifact, DiagDedupe, Job, JobId, Message};
19
20/// A `JobState` is constructed by `JobQueue::run` and passed to `Job::run`. It includes everything
21/// necessary to communicate between the main thread and the execution of the job.
22///
23/// The job may execute on either a dedicated thread or the main thread. If the job executes on the
24/// main thread, the `output` field must be set to prevent a deadlock.
25pub struct JobState<'a, 'gctx> {
26    /// Channel back to the main thread to coordinate messages and such.
27    ///
28    /// When the `output` field is `Some`, care must be taken to avoid calling `push_bounded` on
29    /// the message queue to prevent a deadlock.
30    messages: Arc<Queue<Message>>,
31
32    /// Normally output is sent to the job queue with backpressure. When the job is fresh
33    /// however we need to immediately display the output to prevent a deadlock as the
34    /// output messages are processed on the same thread as they are sent from. `output`
35    /// defines where to output in this case.
36    ///
37    /// Currently the [`Shell`] inside [`GlobalContext`] is wrapped in a `RefCell` and thus can't
38    /// be passed between threads. This means that it isn't possible for multiple output messages
39    /// to be interleaved. In the future, it may be wrapped in a `Mutex` instead. In this case
40    /// interleaving is still prevented as the lock would be held for the whole printing of an
41    /// output message.
42    ///
43    /// [`Shell`]: cargo_util_terminal::Shell
44    /// [`GlobalContext`]: crate::GlobalContext
45    output: Option<&'a DiagDedupe<'gctx>>,
46
47    /// The job id that this state is associated with, used when sending
48    /// messages back to the main thread.
49    id: JobId,
50
51    /// Whether or not we're expected to have a call to `rmeta_produced`. Once
52    /// that method is called this is dynamically set to `false` to prevent
53    /// sending a double message later on.
54    rmeta_required: Cell<bool>,
55
56    /// Manages locks for build units when fine grain locking is enabled.
57    lock_manager: Arc<LockManager>,
58
59    warning_handling: WarningHandling,
60
61    // Historical versions of Cargo made use of the `'a` argument here, so to
62    // leave the door open to future refactorings keep it here.
63    _marker: marker::PhantomData<&'a ()>,
64}
65
66impl<'a, 'gctx> JobState<'a, 'gctx> {
67    pub(super) fn new(
68        id: JobId,
69        messages: Arc<Queue<Message>>,
70        output: Option<&'a DiagDedupe<'gctx>>,
71        rmeta_required: bool,
72        lock_manager: Arc<LockManager>,
73        warning_handling: WarningHandling,
74    ) -> Self {
75        Self {
76            id,
77            messages,
78            output,
79            rmeta_required: Cell::new(rmeta_required),
80            lock_manager,
81            warning_handling,
82            _marker: marker::PhantomData,
83        }
84    }
85
86    pub fn running(&self, cmd: &ProcessBuilder) {
87        self.messages.push(Message::Run(self.id, cmd.to_string()));
88    }
89
90    pub fn stdout(&self, stdout: String) -> CargoResult<()> {
91        if let Some(dedupe) = self.output {
92            writeln!(dedupe.gctx.shell().out(), "{}", stdout)?;
93        } else {
94            self.messages.push_bounded(Message::Stdout(stdout));
95        }
96        Ok(())
97    }
98
99    pub fn stderr(&self, stderr: String) -> CargoResult<()> {
100        if let Some(dedupe) = self.output {
101            let mut shell = dedupe.gctx.shell();
102            shell.print_ansi_stderr(stderr.as_bytes())?;
103            shell.err().write_all(b"\n")?;
104        } else {
105            self.messages.push_bounded(Message::Stderr(stderr));
106        }
107        Ok(())
108    }
109
110    /// See [`Message::Diagnostic`] and [`Message::WarningCount`].
111    pub fn emit_diag(
112        &self,
113        level: &str,
114        diag: String,
115        lint: bool,
116        fixable: bool,
117    ) -> CargoResult<()> {
118        if level == "warning" && lint && self.warning_handling == WarningHandling::Allow {
119            tracing::warn!("{diag}");
120        } else if let Some(dedupe) = self.output {
121            let emitted = dedupe.emit_diag(&diag)?;
122            if level == "warning" {
123                self.messages.push(Message::WarningCount {
124                    id: self.id,
125                    lint,
126                    emitted,
127                    fixable,
128                });
129            }
130        } else {
131            self.messages.push_bounded(Message::Diagnostic {
132                id: self.id,
133                level: level.to_string(),
134                diag,
135                lint,
136                fixable,
137            });
138        }
139        Ok(())
140    }
141
142    /// See [`Message::Warning`].
143    pub fn warning(&self, warning: String) {
144        self.messages.push_bounded(Message::Warning {
145            id: self.id,
146            warning,
147        });
148    }
149
150    /// A method used to signal to the coordinator thread that the rmeta file
151    /// for an rlib has been produced. This is only called for some rmeta
152    /// builds when required, and can be called at any time before a job ends.
153    /// This should only be called once because a metadata file can only be
154    /// produced once!
155    pub fn rmeta_produced(&self) {
156        self.rmeta_required.set(false);
157        self.messages
158            .push(Message::Finish(self.id, Artifact::Metadata, Ok(())));
159    }
160
161    pub fn lock_exclusive(&self, lock: &LockKey) -> CargoResult<()> {
162        self.lock_manager.lock(lock)
163    }
164
165    pub fn downgrade_to_shared(&self, lock: &LockKey) -> CargoResult<()> {
166        self.lock_manager.downgrade_to_shared(lock)
167    }
168
169    pub fn on_section_timing_emitted(&self, section: SectionTiming) {
170        self.messages.push(Message::SectionTiming(self.id, section));
171    }
172
173    /// Reports the peak resident set size (in bytes) of this unit's process,
174    /// for the `--timings` report.
175    pub fn peak_memory(&self, bytes: u64) {
176        self.messages.push(Message::PeakMemory(self.id, bytes));
177    }
178
179    /// Drives a [`Job`] to finish. This ensures that a [`Message::Finish`] is
180    /// sent even if our job panics.
181    pub(super) fn run_to_finish(self, job: Job) {
182        // Use a DropGuard to guarantee that
183        // a `Finish` message is sent even if our job panics.
184        // We shouldn't panic unless there's a bug in Cargo,
185        // so we just need to make sure nothing hangs by accident.
186        let on_panic = DropGuard::new((), |()| {
187            let err = Err(anyhow::format_err!("worker panicked"));
188            self.messages
189                .push(Message::Finish(self.id, Artifact::All, err));
190        });
191        let result = job.run(&self);
192
193        // If the `rmeta_required` wasn't consumed but it was set
194        // previously, then we either have:
195        //
196        // 1. The `job` didn't do anything because it was "fresh".
197        // 2. The `job` returned an error and didn't reach the point where
198        //    it called `rmeta_produced`.
199        // 3. We forgot to call `rmeta_produced` and there's a bug in Cargo.
200        //
201        // Ruling out the third, the other two are pretty common for 2
202        // we'll just naturally abort the compilation operation but for 1
203        // we need to make sure that the metadata is flagged as produced so
204        // send a synthetic message here.
205        if self.rmeta_required.get() && result.is_ok() {
206            self.messages
207                .push(Message::Finish(self.id, Artifact::Metadata, Ok(())));
208        }
209
210        DropGuard::dismiss(on_panic);
211        self.messages
212            .push(Message::Finish(self.id, Artifact::All, result));
213    }
214
215    pub fn future_incompat_report(&self, report: Vec<FutureBreakageItem>) {
216        self.messages
217            .push(Message::FutureIncompatReport(self.id, report));
218    }
219
220    /// The rustc emitted the list of unused `--extern` args.
221    ///
222    /// This is useful for checking unused dependencies.
223    /// Should only be called once, as the compiler only emits it once per compilation.
224    pub fn unused_externs(&self, unused_externs: std::collections::BTreeSet<InternedString>) {
225        self.messages
226            .push(Message::UnusedExterns(self.id, unused_externs));
227    }
228}