Skip to main content

ironwork_rt/
unit.rs

1//! The run unit: every program a run calls, sharing one memory as they share an address space on
2//! z/OS. A called program keeps its WORKING-STORAGE and open files from one CALL to the next until
3//! it is cancelled, or in a CICS task until the LINK or XCTL that started its run unit ends it
4//! (C145). A reference or pointer can reach anywhere in this memory, but never outside it.
5//!
6//! `H` is the executor's handle to a loaded program and `L` the loader CALL goes through; the run
7//! unit holds both without looking inside, and asks `L` what it needs to know about an `H`.
8
9use crate::abend::Abend;
10use crate::files::{Dds, Open};
11use crate::oo::ClassCode;
12use crate::storage::Loc;
13use crate::taint::Taint;
14use crate::vocab::{OpenMode, Pos};
15use numeric::Dialect;
16use std::collections::{HashMap, HashSet, VecDeque};
17use std::io::{BufRead, Write};
18use std::path::{Path, PathBuf};
19use std::rc::Rc;
20
21/// A pointer's value is its offset into run-unit memory plus this, so that no item's address is
22/// NULL.
23pub const ADDRESS_BASE: u32 = 0x0001_0000;
24/// RETURN-CODE, a halfword shared by every program in the run unit.
25pub const RETURN_CODE: usize = 0;
26const RESERVED: usize = 8;
27const ALIGNMENT: usize = 8;
28
29pub struct Loaded<H> {
30    /// None for the first program, which the caller of the run unit owns.
31    pub compiled: Option<H>,
32    pub name: String,
33    pub base: usize,
34    pub size: usize,
35    /// False once a CICS run unit has set the program's storage at `base` aside, or has ended and
36    /// released it: its next activation gets storage of its own.
37    pub placed: bool,
38    pub files: Vec<Option<Open>>,
39    /// The files CLOSE WITH LOCK has closed, which OPEN refuses with status 38.
40    pub locked: Vec<bool>,
41    pub initialized: bool,
42    pub active: bool,
43    /// A dynamic CALL has entered it, so CANCEL acts on it.
44    pub dynamic: bool,
45    /// For a copy a dynamic CALL of an ENTRY name loaded, that entry (numbered as
46    /// [`Loader::entry`] numbers them); None for the program loaded by its PROGRAM-ID.
47    pub entry: Option<usize>,
48    /// Where each paragraph's GO TO goes since an ALTER, by paragraph; empty until one runs.
49    pub altered: Vec<Option<usize>>,
50    /// The library file CALL loaded the program from; None for the programs of the first source.
51    pub source: Option<PathBuf>,
52}
53
54impl<H> Loaded<H> {
55    /// A program with `files` files and `size` bytes of storage at `base`, in its initial state.
56    pub fn new(compiled: Option<H>, name: String, base: usize, size: usize, files: usize) -> Self {
57        let (locked, files) = (vec![false; files], (0..files).map(|_| None).collect());
58        Self { compiled, name, base, size, placed: true, files, locked, initialized: false, active: false, dynamic: false, entry: None, altered: Vec::new(), source: None }
59    }
60
61    /// What the program's activations have left, taken away: it is in its initial state, with its
62    /// storage set aside.
63    fn set_aside(&mut self) -> Held {
64        let files = self.files.iter_mut().map(Option::take).collect();
65        let locked = std::mem::replace(&mut self.locked, vec![false; self.files.len()]);
66        let held = Held { base: self.base, placed: self.placed, files, locked, initialized: self.initialized, active: self.active, dynamic: self.dynamic, altered: std::mem::take(&mut self.altered) };
67        (self.placed, self.initialized, self.active, self.dynamic) = (false, false, false, false);
68        held
69    }
70
71    fn restore(&mut self, held: Held) {
72        (self.base, self.placed, self.files, self.locked, self.altered) = (held.base, held.placed, held.files, held.locked, held.altered);
73        (self.initialized, self.active, self.dynamic) = (held.initialized, held.active, held.dynamic);
74    }
75}
76
77/// What a CICS run unit holds that the LINK or XCTL starting another sets aside until it ends:
78/// each program's state, the EXTERNAL data and files with the connectors to them, the Language
79/// Environment heap (C126), FUNCTION RANDOM's sequence (C104) and RETURN-CODE (C105), which
80/// belong to the enclave.
81struct Enclave {
82    programs: Vec<Held>,
83    externals: Externals,
84    connectors: HashMap<(usize, usize), Connector>,
85    heap: Vec<(usize, usize, bool)>,
86    random: Option<u32>,
87    /// RETURN-CODE's bytes, and whether they may hold input.
88    return_code: ([u8; 2], bool),
89}
90
91/// A program's state in a CICS run unit that a LINK or XCTL has set aside.
92struct Held {
93    base: usize,
94    placed: bool,
95    files: Vec<Option<Open>>,
96    locked: Vec<bool>,
97    initialized: bool,
98    active: bool,
99    dynamic: bool,
100    altered: Vec<Option<usize>>,
101}
102
103pub enum LoadError {
104    NotFound,
105    /// Found, but its source does not compile or its load module does not load.
106    Compile(String),
107}
108
109/// A program a loader found and compiled.
110pub struct LoadedProgram<H> {
111    pub compiled: H,
112    /// The PROGRAM-ID, in upper case.
113    pub name: String,
114    pub files: usize,
115    pub size: usize,
116    /// The file it was read from, when a program library supplied it.
117    pub source: Option<PathBuf>,
118    /// For a program a load module holds, unless of the source the run began with: each source of
119    /// its debug table by name, with the file the module records for it, its own source first.
120    pub recorded: Vec<(String, Option<crate::module::SourceFile>)>,
121}
122
123/// A class definition a loader found and compiled, and its source table, its own source first by
124/// path when a program library supplied it.
125pub struct FoundClass<C> {
126    pub code: C,
127    pub sources: Vec<String>,
128}
129
130/// Where CALL finds programs, and what the run unit needs to know about one it loaded.
131pub trait Loader<H> {
132    /// The program whose PROGRAM-ID CALL names, compiled.
133    fn program(&mut self, name: &str) -> Result<LoadedProgram<H>, LoadError>;
134
135    /// The PROGRAM-ID of a program not yet loaded that has an ENTRY of this name.
136    fn holder(&self, entry: &str) -> Option<String>;
137
138    /// Which of a loaded program's ENTRY statements has this name.
139    fn entry(program: &H, name: &str) -> Option<usize>;
140
141    /// A loaded program's file count and storage size.
142    fn shape(program: &H) -> (usize, usize);
143
144    /// The PROGRAM-IDs of the programs a loaded program contains, which a CANCEL of it reaches.
145    fn nested(program: &H) -> &[String];
146
147    /// Source file `file` of a loaded program's source table, by name.
148    fn source(program: &H, file: usize) -> Option<String>;
149
150    /// The COBOL class definition of this external name, its data and methods each a program the
151    /// executor runs; None for a Java class.
152    fn class(&mut self, external: &str) -> Result<Option<FoundClass<Rc<ClassCode<H>>>>, String>;
153
154    /// A BMS mapset from the copy libraries, which SEND MAP and RECEIVE MAP read; None when no
155    /// library holds it.
156    fn mapset(&mut self, name: &str) -> Option<Result<crate::bms::Mapset, String>>;
157}
158
159/// An executor's activation, as each service's host trait reaches the run unit through it: `Program`
160/// is the executor's handle to a loaded program, `Loader` the loader CALL goes through.
161pub trait UnitHost<'w> {
162    type Program: Clone;
163    type Loader: Loader<Self::Program>;
164    fn unit(&mut self) -> &mut RunUnit<'w, Self::Program, Self::Loader>;
165}
166
167#[derive(Clone, Copy, Debug)]
168pub enum Clock {
169    System,
170    /// Seconds since 1970-01-01T00:00:00Z and hundredths, for runs that must repeat exactly.
171    Fixed(i64, u32),
172}
173
174/// What a run did that its evidence journal records: each file as it is opened and closed, each
175/// program CALL loads, with the source it was read from when a library supplied it, and each
176/// operation an input could steer, with its operand as the program's code page reads it.
177pub enum Event<'a> {
178    Open { dd: &'a str, mode: OpenMode, path: &'a Path },
179    Close { dd: &'a str, path: &'a Path },
180    /// `recorded` is [`LoadedProgram::recorded`], empty for a program read from source.
181    Load { program: &'a str, source: Option<&'a Path>, recorded: &'a [(String, Option<crate::module::SourceFile>)] },
182    /// Control entering paragraph (or section header) `index` of `program` at its start.
183    Paragraph { program: &'a str, name: &'a str, index: usize },
184    /// `kind` is cobolwork's name for the sink (`dynamic-program-load`, `log`, ...); `file` is the
185    /// library file or COPY member the operation is in, empty for the first program's own source;
186    /// `input`, under [`RunUnit::taint`], whether an input byte may be in the operand
187    /// ([`crate::taint::Taint::at_sink`]).
188    Sink { kind: &'static str, file: &'a str, line: u32, operand: &'a str, input: Option<bool> },
189    /// A statement starting, under [`RunUnit::statements`]; `file` as `Sink`'s.
190    Statement { file: &'a str, line: u32 },
191}
192
193/// Every kind of [`Event::Sink`] ironwork raises. A sink record joins a cobolwork finding by its
194/// kind, so each is one cobolwork's `lib/dataflow.mjs` names (fixtures/cobolwork/evidence/sinks.tsv).
195pub const SINK_KINDS: [&str; 16] = [
196    "cics-dynamic-transfer",
197    "cics-sysid",
198    "connection-target",
199    "dynamic-file-path",
200    "dynamic-program-load",
201    "dynamic-sql",
202    "http-header",
203    "log",
204    "os-command",
205    "outbound-host",
206    "outbound-http",
207    "queue-name",
208    "record-key",
209    "record-update",
210    "screen",
211    "web-response",
212];
213
214/// The statements whose start a run tells its observer of: every one, or those on these lines of
215/// any source, which the observer narrows to their files.
216#[derive(Clone, Debug, PartialEq, Eq)]
217pub enum StatementFilter {
218    All,
219    Lines(HashSet<u32>),
220}
221
222pub type Observer<'w> = Box<dyn FnMut(Event<'_>) + 'w>;
223
224/// How deep PERFORMs and CALLs may nest before the run abends, rather than exhaust the stack.
225pub const MAX_DEPTH: usize = 100;
226
227/// EXTERNAL data records and file connectors, which belong to the run unit rather than to a
228/// program: one of each name, whichever program first describes it (Language Reference
229/// SC27-8713-03, pp. 65, 184, 197).
230#[derive(Default)]
231pub struct Externals {
232    /// Each EXTERNAL data record, and each EXTERNAL file's record area, by name: where it is and
233    /// how many bytes it has.
234    storage: HashMap<(bool, String), (usize, usize)>,
235    files: Vec<Option<Open>>,
236    /// Whether each EXTERNAL file was closed WITH LOCK.
237    locked: Vec<bool>,
238    file_names: HashMap<String, usize>,
239}
240
241/// The EXTERNAL record of the run unit that holds UPSI switch `n`: one byte, 1 when the switch is
242/// on and 0 when it is off (assumption C410). No program can spell the name, so only a
243/// SPECIAL-NAMES entry for the switch reaches it.
244pub fn switch_record(n: u8) -> String {
245    format!("UPSI-{n} SWITCH")
246}
247
248/// The UPSI switch whose [`switch_record`] is named `name`.
249pub fn switch_of_record(name: &str) -> Option<u8> {
250    match name.strip_prefix("UPSI-")?.strip_suffix(" SWITCH")?.as_bytes() {
251        [d @ b'0'..=b'7'] => Some(d - b'0'),
252        _ => None,
253    }
254}
255
256/// A file of a program that is another's file connector.
257#[derive(Clone, Copy, Debug, PartialEq, Eq)]
258pub enum Connector {
259    /// The run unit's EXTERNAL file of this number.
260    External(usize),
261    /// File `k` of loaded program `p`: a GLOBAL file of a program containing this one.
262    Program(usize, usize),
263}
264
265/// The routines cobolwork reads a CALL of as running an operating-system command, whose arguments
266/// the input trace checks.
267pub const OS_COMMAND_ROUTINES: &[&str] = &["SYSTEM", "C$SYSTEM", "CBL_EXEC_RUN_UNIT", "CBL_GC_HOSTED", "BXPSYSTM"];
268
269pub struct RunUnit<'w, H, L: Loader<H>> {
270    pub mem: Vec<u8>,
271    /// PERFORMs and CALLs in progress, across every program.
272    pub depth: usize,
273    pub programs: Vec<Loaded<H>>,
274    names: HashMap<String, usize>,
275    pub library: L,
276    pub dds: Dds,
277    pub sysin: Option<Box<dyn BufRead + 'w>>,
278    pub clock: Clock,
279    pub out: &'w mut dyn Write,
280    pub err: &'w mut dyn Write,
281    /// The CICS task a harness run stands in for, with its EXEC interface block and open files.
282    pub cics: Option<crate::cics::Task>,
283    pub eib: usize,
284    pub cics_files: HashMap<String, Open>,
285    /// The database EXEC SQL statements reach, when the run has one.
286    pub sql: Option<crate::sql::Session<'w>>,
287    /// Language Environment's heap storage and message files.
288    pub le: crate::le::State,
289    /// Classes, objects and the JNI environment of the run unit's object-oriented programs.
290    pub oo: crate::oo::Objects<Rc<ClassCode<H>>>,
291    /// Told what the run opens, closes and loads, when a caller keeps evidence of it.
292    pub observer: Option<Observer<'w>>,
293    /// FUNCTION RANDOM's generator, one for the run unit, from the first reference on.
294    pub random: Option<u32>,
295    /// The job step's program arguments, which ACCEPT ... FROM COMMAND-LINE and ARGUMENT-VALUE read
296    /// under `--compliance extended`; empty without a PARM.
297    pub arguments: crate::le::parm::Arguments,
298    externals: Externals,
299    /// The files of loaded programs that are another's connector, by program and file.
300    connectors: HashMap<(usize, usize), Connector>,
301    /// The entries SET TO ENTRY has named, which function-pointers and procedure-pointers hold.
302    pub entries: Vec<crate::set::Entry>,
303    /// The statements an observer is told of as each starts; None tells it of none.
304    pub statements: Option<StatementFilter>,
305    /// Which bytes may hold input, when the run traces input.
306    pub taint: Option<Taint>,
307    /// How many more statements may start before the run ends with S322; None for no limit.
308    pub statement_limit: Option<u64>,
309    /// The last statements started under a statement limit, oldest first, and once it is spent the
310    /// loop statement the S322 waits for.
311    recent: VecDeque<Started>,
312    overrun: Option<Overrun>,
313    /// The ACCEPTs, by position, that have said they found SYSIN at its end; a loop around one
314    /// would otherwise write a line each time round.
315    pub(crate) sysin_ended: HashSet<(u16, u32, u32)>,
316    /// The CICS run units the LINKs and XCTLs running have set aside, the innermost last.
317    set_aside: Vec<Enclave>,
318}
319
320fn end_file(f: Open, unclosed: bool) -> std::io::Result<()> {
321    if unclosed { f.abandon() } else { f.close() }
322}
323
324/// How many of the last statement starts an S322 looks back over for the loop the run is in, and
325/// how many more it lets start while it waits for that loop's first statement.
326const LOOP_WINDOW: usize = 4096;
327
328/// A statement start: the loaded program, how deep PERFORMs and CALLs had nested, and where.
329#[derive(Clone, Copy, PartialEq, Eq)]
330struct Started {
331    program: usize,
332    depth: usize,
333    pos: Pos,
334}
335
336/// A spent statement limit: the loop's first statement, the S322's place, its lines, and the starts
337/// left before the run ends wherever it is.
338struct Overrun {
339    head: Started,
340    lines: Vec<u32>,
341    grace: usize,
342}
343
344/// The loop the last starts ran: the statements that started more than once among them, those of
345/// their outermost frame, in its program's own source before any COPY member, and the first of
346/// them by position. A loop's statements recur at one depth however many statements ran before
347/// it, and anything it PERFORMs or CALLs runs deeper. With none recurring, the statement starting
348/// now and no lines.
349fn loop_of(recent: &VecDeque<Started>, now: Started) -> Overrun {
350    let key = |s: &Started| (s.program, s.depth, s.pos.file, s.pos.line, s.pos.col);
351    let mut seen: HashMap<_, usize> = HashMap::new();
352    for s in recent {
353        *seen.entry(key(s)).or_default() += 1;
354    }
355    let recurring: Vec<&Started> = recent.iter().filter(|s| seen[&key(s)] > 1).collect();
356    let Some(outer) = recurring.iter().map(|s| s.depth).min() else { return Overrun { head: now, lines: Vec::new(), grace: 0 } };
357    let program = recurring.iter().rev().find(|s| s.depth == outer).map_or(now.program, |s| s.program);
358    let frame: Vec<&Started> = recurring.into_iter().filter(|s| s.depth == outer && s.program == program).collect();
359    let file = frame.iter().map(|s| s.pos.file).min().unwrap_or(now.pos.file);
360    let head = frame.iter().filter(|s| s.pos.file == file).min_by_key(|s| (s.pos.line, s.pos.col)).map_or(now, |s| **s);
361    let mut lines: Vec<u32> = frame.iter().filter(|s| s.pos.file == file).map(|s| s.pos.line).collect();
362    lines.sort_unstable();
363    lines.dedup();
364    Overrun { head, lines, grace: LOOP_WINDOW }
365}
366
367impl<H, L: Loader<H>> RunUnit<'_, H, L> {
368    /// Copies `bytes` into memory at `offset`; under taint they may hold input when the running
369    /// statement has read a byte that may. Every write of data to memory goes through here or
370    /// [`RunUnit::write_input`], or marks its bytes with [`RunUnit::mark`].
371    pub fn write(&mut self, offset: usize, bytes: &[u8]) {
372        self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
373        self.mark(offset, bytes.len());
374    }
375
376    /// Copies input into memory at `offset`: bytes a READ, ACCEPT or row brought in.
377    pub fn write_input(&mut self, offset: usize, bytes: &[u8]) {
378        self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
379        self.mark_input(offset, bytes.len(), true);
380    }
381
382    /// Marks bytes written outside [`RunUnit::write`] as it would.
383    pub fn mark(&mut self, offset: usize, len: usize) {
384        if let Some(t) = self.taint.as_mut() {
385            let pending = t.pending();
386            t.set(offset, len, pending);
387        }
388    }
389
390    /// Marks bytes as input, or as holding none: initial values, which are constants.
391    pub fn mark_input(&mut self, offset: usize, len: usize, input: bool) {
392        if let Some(t) = self.taint.as_mut() {
393            t.set(offset, len, input);
394        }
395    }
396
397    /// A read of `loc` by the running statement.
398    pub fn taint_read(&mut self, loc: Loc) {
399        if let Some(t) = self.taint.as_mut() {
400            t.read(loc.offset, loc.len);
401        }
402    }
403
404    /// [`Taint::writing`], when the run traces input.
405    pub fn writing(&mut self, on: bool) -> bool {
406        self.taint.as_mut().is_some_and(|t| t.writing(on))
407    }
408
409    /// A statement with a position starts: its writes carry only what it reads.
410    pub fn statement_starts(&mut self) {
411        if let Some(t) = self.taint.as_mut() {
412            t.start_statement();
413        }
414    }
415
416    /// [`Taint::take_input`], when the run traces input.
417    pub fn take_input(&mut self) {
418        if let Some(t) = self.taint.as_mut() {
419            t.take_input();
420        }
421    }
422
423    /// Whether any byte of the range may hold input; false without taint.
424    pub fn holds_input(&self, offset: usize, len: usize) -> bool {
425        self.taint.as_ref().is_some_and(|t| t.any(offset, len))
426    }
427
428    /// Whether the running statement has read a byte that may hold input.
429    pub fn pending(&self) -> bool {
430        self.taint.as_ref().is_some_and(Taint::pending)
431    }
432
433    /// [`Taint::resume_statement`], when the run traces input.
434    pub fn resume_statement(&mut self, read_before: bool) {
435        if let Some(t) = self.taint.as_mut() {
436            t.resume_statement(read_before);
437        }
438    }
439
440    /// The run did `what`, which taint does not follow.
441    pub fn unfollowed(&mut self, what: &'static str) {
442        if let Some(t) = self.taint.as_mut() {
443            t.unfollowed(what);
444        }
445    }
446
447    /// Whether an input byte may be in a sink's operand; None without taint.
448    pub fn input_at_sink(&self) -> Option<bool> {
449        self.taint.as_ref().and_then(Taint::at_sink)
450    }
451}
452
453impl<'w, H: Clone, L: Loader<H>> RunUnit<'w, H, L> {
454    pub fn new(library: L, dds: Dds, sysin: Option<Box<dyn BufRead + 'w>>, clock: Clock, out: &'w mut dyn Write, err: &'w mut dyn Write) -> Self {
455        Self {
456            mem: vec![0; RESERVED],
457            depth: 0,
458            programs: Vec::new(),
459            names: HashMap::new(),
460            library,
461            dds,
462            sysin,
463            clock,
464            out,
465            err,
466            cics: None,
467            eib: 0,
468            cics_files: HashMap::new(),
469            sql: None,
470            le: crate::le::State::default(),
471            oo: Default::default(),
472            observer: None,
473            random: None,
474            arguments: Default::default(),
475            externals: Externals::default(),
476            connectors: HashMap::new(),
477            entries: Vec::new(),
478            statements: None,
479            taint: None,
480            statement_limit: None,
481            recent: VecDeque::new(),
482            overrun: None,
483            sysin_ended: HashSet::new(),
484            set_aside: Vec::new(),
485        }
486    }
487
488    fn allocate(&mut self, size: usize) -> usize {
489        let base = self.mem.len().div_ceil(ALIGNMENT) * ALIGNMENT;
490        self.mem.resize(base + size, 0);
491        base
492    }
493
494    /// Adds a program to the run unit under `name` and gives it its storage.
495    pub fn add_named(&mut self, compiled: Option<H>, name: String, files: usize, size: usize) -> usize {
496        let base = self.allocate(size);
497        let index = self.programs.len();
498        self.names.insert(name.clone(), index);
499        self.programs.push(Loaded::new(compiled, name, base, size, files));
500        index
501    }
502
503    /// A CICS LINK or XCTL starts a run unit of its own (C145): every program starts in it in its
504    /// initial state, with storage of its own, it has no EXTERNAL data or files and an empty heap
505    /// (C126), FUNCTION RANDOM has not been referenced (C104) and RETURN-CODE is zero (C105), and
506    /// the state of the run unit that issued it is set aside until [`RunUnit::end_cics_run_unit`].
507    pub fn begin_cics_run_unit(&mut self) {
508        let programs = self.programs.iter_mut().map(Loaded::set_aside).collect();
509        let (externals, connectors) = (std::mem::take(&mut self.externals), std::mem::take(&mut self.connectors));
510        let return_code = ([self.mem[RETURN_CODE], self.mem[RETURN_CODE + 1]], self.holds_input(RETURN_CODE, 2));
511        self.mem[RETURN_CODE..RETURN_CODE + 2].fill(0);
512        self.mark_input(RETURN_CODE, 2, false);
513        let (heap, random) = (std::mem::take(&mut self.le.heap), self.random.take());
514        self.set_aside.push(Enclave { programs, externals, connectors, heap, random, return_code });
515    }
516
517    /// Ends the run unit [`RunUnit::begin_cics_run_unit`] started, closing the files its programs
518    /// and its EXTERNAL files left open as Language Environment closes an enclave's, and dropping
519    /// its programs' storage, EXTERNAL data and heap: a program it loaded stays loaded, in its
520    /// initial state with no storage (C129), and the run unit set aside has everything back but,
521    /// after `xctl`, RETURN-CODE, the program XCTL started having taken the issuer's place (C105).
522    pub fn end_cics_run_unit(&mut self, xctl: bool) -> Result<(), String> {
523        let mut closed = Ok(());
524        for program in &mut self.programs {
525            for f in program.files.iter_mut().filter_map(Option::take) {
526                if let Err(e) = f.close() {
527                    closed = closed.and(Err(format!("closing a file of {}: {e}", program.name)));
528                }
529            }
530            drop(program.set_aside());
531        }
532        closed = closed.and(self.close_external_files(false));
533        let Some(enclave) = self.set_aside.pop() else { return closed };
534        for (program, held) in self.programs.iter_mut().zip(enclave.programs) {
535            program.restore(held);
536        }
537        (self.externals, self.connectors, self.le.heap, self.random) = (enclave.externals, enclave.connectors, enclave.heap, enclave.random);
538        if !xctl {
539            let (bytes, input) = enclave.return_code;
540            self.mem[RETURN_CODE..RETURN_CODE + 2].copy_from_slice(&bytes);
541            self.mark_input(RETURN_CODE, 2, input);
542        }
543        closed
544    }
545
546    /// The program a CALL of `name` enters, and which of its ENTRY statements when `name` is not
547    /// its PROGRAM-ID: the one copy of the program, or with `copy` a copy of its own for the entry
548    /// name ([`crate::callee::entry_copy`]).
549    pub fn load_entry(&mut self, name: &str, copy: bool) -> Result<(usize, Option<usize>), LoadError> {
550        if let Some(i) = self.find(name) {
551            return Ok((i, self.programs[i].entry));
552        }
553        let name = name.to_ascii_uppercase();
554        let index = match self.programs.iter().position(|p| p.compiled.as_ref().is_some_and(|c| L::entry(c, &name).is_some())) {
555            Some(i) => i,
556            None => {
557                let holder = self.library.holder(&name);
558                self.load(holder.as_deref().unwrap_or(&name))?
559            }
560        };
561        let Some(compiled) = self.programs[index].compiled.clone() else { return Ok((index, None)) };
562        let Some(entry) = L::entry(&compiled, &name) else { return Ok((index, None)) };
563        if !copy {
564            return Ok((index, Some(entry)));
565        }
566        let (files, size) = L::shape(&compiled);
567        let copy = self.add_named(Some(compiled), name, files, size);
568        self.programs[copy].entry = Some(entry);
569        self.programs[copy].source = self.programs[index].source.clone();
570        Ok((copy, Some(entry)))
571    }
572
573    /// Storage for a BY CONTENT or BY VALUE argument, at the end of memory, written as
574    /// [`RunUnit::write`] writes.
575    pub fn push_temporary(&mut self, bytes: &[u8]) -> usize {
576        let at = self.allocate(bytes.len());
577        self.write(at, bytes);
578        at
579    }
580
581    /// Releases arguments pushed since `mark`, unless a program's storage, heap storage or EXTERNAL
582    /// storage was placed behind them.
583    pub fn release_temporaries(&mut self, mark: usize) {
584        let external = self.externals.storage.values().all(|&(at, _)| at < mark);
585        if self.programs.iter().all(|p| !p.placed || p.base + p.size <= mark) && self.le.heap_end() <= mark && external {
586            self.mem.truncate(mark.max(RESERVED));
587            if let Some(t) = self.taint.as_mut() {
588                t.truncate(self.mem.len());
589            }
590        }
591    }
592
593    /// One more PERFORM or CALL in progress, refused past `MAX_DEPTH` rather than exhaust the stack.
594    pub fn enter(&mut self, pos: Pos) -> Result<(), Abend> {
595        if self.depth >= MAX_DEPTH {
596            return Err(Abend::ironwork(format!("PERFORM and CALL nest deeper than {MAX_DEPTH}"), pos));
597        }
598        self.depth += 1;
599        Ok(())
600    }
601
602    /// Marks program `me` active: where its storage starts, and whether the activation starts from
603    /// fresh storage, as its first does, the first after a CANCEL, and every one of an INITIAL
604    /// program.
605    pub fn activate(&mut self, me: usize, initial: bool) -> (usize, bool) {
606        if !self.programs[me].placed {
607            let base = self.allocate(self.programs[me].size);
608            (self.programs[me].base, self.programs[me].placed) = (base, true);
609        }
610        let program = &mut self.programs[me];
611        program.active = true;
612        (program.base, !program.initialized || initial)
613    }
614
615    /// Program `me`'s storage holds its initial values, and its GO TOs go where they are written.
616    pub fn initialized(&mut self, me: usize) {
617        self.programs[me].initialized = true;
618        self.programs[me].altered.clear();
619    }
620
621    pub fn find(&self, name: &str) -> Option<usize> {
622        if name.bytes().any(|b| b.is_ascii_lowercase()) {
623            return self.names.get(&name.to_ascii_uppercase()).copied();
624        }
625        self.names.get(name).copied()
626    }
627
628    /// The program CALL names, compiling and loading it the first time.
629    pub fn load(&mut self, name: &str) -> Result<usize, LoadError> {
630        let name = name.to_ascii_uppercase();
631        if let Some(i) = self.find(&name) {
632            return Ok(i);
633        }
634        let loaded = self.library.program(&name)?;
635        self.notify(Event::Load { program: &name, source: loaded.source.as_deref(), recorded: &loaded.recorded });
636        let index = self.add_named(Some(loaded.compiled), loaded.name, loaded.files, loaded.size);
637        self.programs[index].source = loaded.source;
638        Ok(index)
639    }
640
641    pub const fn observed(&self) -> bool {
642        self.observer.is_some()
643    }
644
645    /// Whether a statement starting on `line` is told to the observer.
646    /// Counts the start of `program`'s statement at `pos` against the statement limit. Once it is
647    /// spent the run ends with S322, as z/OS ends a step that runs past its TIME=, at the next start
648    /// of the loop it is in, so the place does not depend on how many statements ran before the
649    /// loop (assumption C241).
650    pub fn start_statement(&mut self, program: usize, pos: Pos) -> Result<(), Abend> {
651        let Some(left) = self.statement_limit.as_mut() else { return Ok(()) };
652        let now = Started { program, depth: self.depth, pos };
653        if *left > 0 {
654            *left -= 1;
655            if self.recent.len() == LOOP_WINDOW {
656                self.recent.pop_front();
657            }
658            self.recent.push_back(now);
659            return Ok(());
660        }
661        let overrun = self.overrun.get_or_insert_with(|| loop_of(&self.recent, now));
662        let message = "the run reached its statement limit, as a step past its TIME= ends";
663        if now == overrun.head && !overrun.lines.is_empty() {
664            const SHOWN: usize = 24;
665            let mut lines = overrun.lines.iter().take(SHOWN).map(u32::to_string).collect::<Vec<_>>().join(", ");
666            if overrun.lines.len() > SHOWN {
667                lines += &format!(" and {} more", overrun.lines.len() - SHOWN);
668            }
669            return Err(Abend { code: crate::abend::AbendCode::TimeLimit, message: format!("{message}, in the loop over lines {lines}"), pos, file: None });
670        }
671        if overrun.grace == 0 {
672            return Err(Abend { code: crate::abend::AbendCode::TimeLimit, message: message.into(), pos, file: None });
673        }
674        overrun.grace -= 1;
675        Ok(())
676    }
677
678    pub fn traces(&self, line: u32) -> bool {
679        match &self.statements {
680            None => false,
681            Some(StatementFilter::All) => self.observer.is_some(),
682            Some(StatementFilter::Lines(lines)) => self.observer.is_some() && lines.contains(&line),
683        }
684    }
685
686    pub fn notify(&mut self, event: Event<'_>) {
687        if let Event::Sink { kind, .. } = &event {
688            debug_assert!(SINK_KINDS.contains(kind), "the sink kind {kind} is not in rt::unit::SINK_KINDS");
689        }
690        if let Some(observer) = self.observer.as_mut() {
691            observer(event);
692        }
693    }
694
695    /// Closes every file any program left open, as the runtime does when the run unit ends, normally
696    /// or by an abend under TRAP(ON). An abend TRAP(OFF) keeps from Language Environment closes
697    /// none (`unclosed`), and each VSAM data set stays marked open for output
698    /// ([`numeric::assumptions::TRAP_OFF_LEAVES_FILES_OPEN`]).
699    pub fn close_all(&mut self, unclosed: bool) -> Result<(), String> {
700        for program in &mut self.programs {
701            for f in program.files.iter_mut().filter_map(Option::take) {
702                end_file(f, unclosed).map_err(|e| format!("closing a file of {}: {e}", program.name))?;
703            }
704        }
705        self.close_external_files(unclosed)
706    }
707
708    /// Closes the EXTERNAL files left open, giving the first failure.
709    fn close_external_files(&mut self, unclosed: bool) -> Result<(), String> {
710        let mut closed = Ok(());
711        for (name, &k) in &self.externals.file_names {
712            if let Some(f) = self.externals.files[k].take()
713                && let Err(e) = end_file(f, unclosed)
714            {
715                closed = closed.and(Err(format!("closing EXTERNAL file {name}: {e}")));
716            }
717        }
718        closed
719    }
720
721    /// Where EXTERNAL record `name` is, or EXTERNAL file `name`'s record area when `file`: storage
722    /// of `size` bytes, zeroed, the first time a program describes it. A description of another
723    /// size is refused (assumption C180), except under gnucobol a shorter record's, which
724    /// shares the storage with a warning, as cobc's does.
725    pub fn external(&mut self, name: &str, file: bool, size: usize, dialect: Dialect) -> Result<usize, String> {
726        let key = (file, name.to_owned());
727        if let Some(&(at, had)) = self.externals.storage.get(&key) {
728            return if had == size {
729                Ok(at)
730            } else if size < had && !file && dialect == Dialect::Gnucobol {
731                let _ = writeln!(self.err, "ironwork: EXTERNAL record {name} has {had} bytes in the run unit, and this program describes {size}");
732                Ok(at)
733            } else {
734                let what = if file { "the record area of EXTERNAL file" } else { "EXTERNAL record" };
735                Err(format!("{what} {name} has {had} bytes in the run unit, and this program describes {size}"))
736            };
737        }
738        let at = self.allocate(size);
739        self.externals.storage.insert(key, (at, size));
740        Ok(at)
741    }
742
743    /// Sets the eight UPSI switches before a program runs, each [`switch_record`] holding 1 for
744    /// on, and marks them as input, since the PARM that sets them is (assumption C411).
745    pub fn set_switches(&mut self, on: [bool; 8]) {
746        for (n, on) in (0..).zip(on) {
747            let at = self.push_temporary(&[u8::from(on)]);
748            self.externals.storage.insert((false, switch_record(n)), (at, 1));
749            self.mark_input(at, 1, true);
750        }
751    }
752
753    /// The run unit's connector for EXTERNAL file `name`.
754    pub fn external_file(&mut self, name: &str) -> Connector {
755        let (files, locked) = (&mut self.externals.files, &mut self.externals.locked);
756        let k = *self.externals.file_names.entry(name.to_owned()).or_insert_with(|| {
757            files.push(None);
758            locked.push(false);
759            files.len() - 1
760        });
761        Connector::External(k)
762    }
763
764    /// Program `me`'s file k is the connector `to`, for as long as the run unit lasts.
765    pub fn connect(&mut self, me: usize, k: usize, to: Connector) {
766        self.connectors.insert((me, k), to);
767    }
768
769    fn connector(&self, mut me: usize, mut k: usize) -> Option<Connector> {
770        let mut to = None;
771        while let Some(&c) = self.connectors.get(&(me, k)) {
772            to = Some(c);
773            match c {
774                Connector::External(_) => break,
775                Connector::Program(p, j) => (me, k) = (p, j),
776            }
777        }
778        to
779    }
780
781    /// Program `me`'s file k, open or not: its own, or the connector it shares.
782    pub fn file(&mut self, me: usize, k: usize) -> &mut Option<Open> {
783        match self.connector(me, k) {
784            None => &mut self.programs[me].files[k],
785            Some(Connector::External(e)) => &mut self.externals.files[e],
786            Some(Connector::Program(p, j)) => &mut self.programs[p].files[j],
787        }
788    }
789
790    /// Whether program `me`'s file k, or the connector it shares, was closed WITH LOCK.
791    pub fn locked(&mut self, me: usize, k: usize) -> &mut bool {
792        match self.connector(me, k) {
793            None => &mut self.programs[me].locked[k],
794            Some(Connector::External(e)) => &mut self.externals.locked[e],
795            Some(Connector::Program(p, j)) => &mut self.programs[p].locked[j],
796        }
797    }
798
799    pub fn file_ref(&self, me: usize, k: usize) -> &Option<Open> {
800        match self.connector(me, k) {
801            None => &self.programs[me].files[k],
802            Some(Connector::External(e)) => &self.externals.files[e],
803            Some(Connector::Program(p, j)) => &self.programs[p].files[j],
804        }
805    }
806
807    pub fn return_code(&self) -> i16 {
808        i16::from_be_bytes([self.mem[RETURN_CODE], self.mem[RETURN_CODE + 1]])
809    }
810
811    /// The current time: seconds since the epoch, and hundredths.
812    pub fn now(&self) -> (i64, u32) {
813        match self.clock {
814            Clock::Fixed(s, h) => (s, h),
815            Clock::System => {
816                let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
817                (d.as_secs() as i64, d.subsec_millis() / 10)
818            }
819        }
820    }
821}