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; 14] = [
196    "cics-dynamic-transfer",
197    "cics-sysid",
198    "connection-target",
199    "dynamic-program-load",
200    "http-header",
201    "log",
202    "os-command",
203    "outbound-host",
204    "outbound-http",
205    "queue-name",
206    "record-key",
207    "record-update",
208    "screen",
209    "web-response",
210];
211
212/// The statements whose start a run tells its observer of: every one, or those on these lines of
213/// any source, which the observer narrows to their files.
214#[derive(Clone, Debug, PartialEq, Eq)]
215pub enum StatementFilter {
216    All,
217    Lines(HashSet<u32>),
218}
219
220pub type Observer<'w> = Box<dyn FnMut(Event<'_>) + 'w>;
221
222/// How deep PERFORMs and CALLs may nest before the run abends, rather than exhaust the stack.
223pub const MAX_DEPTH: usize = 100;
224
225/// EXTERNAL data records and file connectors, which belong to the run unit rather than to a
226/// program: one of each name, whichever program first describes it (Language Reference
227/// SC27-8713-03, pp. 65, 184, 197).
228#[derive(Default)]
229pub struct Externals {
230    /// Each EXTERNAL data record, and each EXTERNAL file's record area, by name: where it is and
231    /// how many bytes it has.
232    storage: HashMap<(bool, String), (usize, usize)>,
233    files: Vec<Option<Open>>,
234    /// Whether each EXTERNAL file was closed WITH LOCK.
235    locked: Vec<bool>,
236    file_names: HashMap<String, usize>,
237}
238
239/// A file of a program that is another's file connector.
240#[derive(Clone, Copy, Debug, PartialEq, Eq)]
241pub enum Connector {
242    /// The run unit's EXTERNAL file of this number.
243    External(usize),
244    /// File `k` of loaded program `p`: a GLOBAL file of a program containing this one.
245    Program(usize, usize),
246}
247
248/// The routines cobolwork reads a CALL of as running an operating-system command, whose arguments
249/// the input trace checks.
250pub const OS_COMMAND_ROUTINES: &[&str] = &["SYSTEM", "C$SYSTEM", "CBL_EXEC_RUN_UNIT", "CBL_GC_HOSTED", "BXPSYSTM"];
251
252pub struct RunUnit<'w, H, L: Loader<H>> {
253    pub mem: Vec<u8>,
254    /// PERFORMs and CALLs in progress, across every program.
255    pub depth: usize,
256    pub programs: Vec<Loaded<H>>,
257    names: HashMap<String, usize>,
258    pub library: L,
259    pub dds: Dds,
260    pub sysin: Option<Box<dyn BufRead + 'w>>,
261    pub clock: Clock,
262    pub out: &'w mut dyn Write,
263    pub err: &'w mut dyn Write,
264    /// The CICS task a harness run stands in for, with its EXEC interface block and open files.
265    pub cics: Option<crate::cics::Task>,
266    pub eib: usize,
267    pub cics_files: HashMap<String, Open>,
268    /// The database EXEC SQL statements reach, when the run has one.
269    pub sql: Option<crate::sql::Session<'w>>,
270    /// Language Environment's heap storage and message files.
271    pub le: crate::le::State,
272    /// Classes, objects and the JNI environment of the run unit's object-oriented programs.
273    pub oo: crate::oo::Objects<Rc<ClassCode<H>>>,
274    /// Told what the run opens, closes and loads, when a caller keeps evidence of it.
275    pub observer: Option<Observer<'w>>,
276    /// FUNCTION RANDOM's generator, one for the run unit, from the first reference on.
277    pub random: Option<u32>,
278    externals: Externals,
279    /// The files of loaded programs that are another's connector, by program and file.
280    connectors: HashMap<(usize, usize), Connector>,
281    /// The entries SET TO ENTRY has named, which function-pointers and procedure-pointers hold.
282    pub entries: Vec<crate::set::Entry>,
283    /// The statements an observer is told of as each starts; None tells it of none.
284    pub statements: Option<StatementFilter>,
285    /// Which bytes may hold input, when the run traces input.
286    pub taint: Option<Taint>,
287    /// How many more statements may start before the run ends with S322; None for no limit.
288    pub statement_limit: Option<u64>,
289    /// The last statements started under a statement limit, oldest first, and once it is spent the
290    /// loop statement the S322 waits for.
291    recent: VecDeque<Started>,
292    overrun: Option<Overrun>,
293    /// The ACCEPTs, by position, that have said they found SYSIN at its end; a loop around one
294    /// would otherwise write a line each time round.
295    pub(crate) sysin_ended: HashSet<(u16, u32, u32)>,
296    /// The CICS run units the LINKs and XCTLs running have set aside, the innermost last.
297    set_aside: Vec<Enclave>,
298}
299
300fn end_file(f: Open, unclosed: bool) -> std::io::Result<()> {
301    if unclosed { f.abandon() } else { f.close() }
302}
303
304/// How many of the last statement starts an S322 looks back over for the loop the run is in, and
305/// how many more it lets start while it waits for that loop's first statement.
306const LOOP_WINDOW: usize = 4096;
307
308/// A statement start: the loaded program, how deep PERFORMs and CALLs had nested, and where.
309#[derive(Clone, Copy, PartialEq, Eq)]
310struct Started {
311    program: usize,
312    depth: usize,
313    pos: Pos,
314}
315
316/// A spent statement limit: the loop's first statement, the S322's place, its lines, and the starts
317/// left before the run ends wherever it is.
318struct Overrun {
319    head: Started,
320    lines: Vec<u32>,
321    grace: usize,
322}
323
324/// The loop the last starts ran: the statements that started more than once among them, those of
325/// their outermost frame, in its program's own source before any COPY member, and the first of
326/// them by position. A loop's statements recur at one depth however many statements ran before
327/// it, and anything it PERFORMs or CALLs runs deeper. With none recurring, the statement starting
328/// now and no lines.
329fn loop_of(recent: &VecDeque<Started>, now: Started) -> Overrun {
330    let key = |s: &Started| (s.program, s.depth, s.pos.file, s.pos.line, s.pos.col);
331    let mut seen: HashMap<_, usize> = HashMap::new();
332    for s in recent {
333        *seen.entry(key(s)).or_default() += 1;
334    }
335    let recurring: Vec<&Started> = recent.iter().filter(|s| seen[&key(s)] > 1).collect();
336    let Some(outer) = recurring.iter().map(|s| s.depth).min() else { return Overrun { head: now, lines: Vec::new(), grace: 0 } };
337    let program = recurring.iter().rev().find(|s| s.depth == outer).map_or(now.program, |s| s.program);
338    let frame: Vec<&Started> = recurring.into_iter().filter(|s| s.depth == outer && s.program == program).collect();
339    let file = frame.iter().map(|s| s.pos.file).min().unwrap_or(now.pos.file);
340    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);
341    let mut lines: Vec<u32> = frame.iter().filter(|s| s.pos.file == file).map(|s| s.pos.line).collect();
342    lines.sort_unstable();
343    lines.dedup();
344    Overrun { head, lines, grace: LOOP_WINDOW }
345}
346
347impl<H, L: Loader<H>> RunUnit<'_, H, L> {
348    /// Copies `bytes` into memory at `offset`; under taint they may hold input when the running
349    /// statement has read a byte that may. Every write of data to memory goes through here or
350    /// [`RunUnit::write_input`], or marks its bytes with [`RunUnit::mark`].
351    pub fn write(&mut self, offset: usize, bytes: &[u8]) {
352        self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
353        self.mark(offset, bytes.len());
354    }
355
356    /// Copies input into memory at `offset`: bytes a READ, ACCEPT or row brought in.
357    pub fn write_input(&mut self, offset: usize, bytes: &[u8]) {
358        self.mem[offset..offset + bytes.len()].copy_from_slice(bytes);
359        self.mark_input(offset, bytes.len(), true);
360    }
361
362    /// Marks bytes written outside [`RunUnit::write`] as it would.
363    pub fn mark(&mut self, offset: usize, len: usize) {
364        if let Some(t) = self.taint.as_mut() {
365            let pending = t.pending();
366            t.set(offset, len, pending);
367        }
368    }
369
370    /// Marks bytes as input, or as holding none: initial values, which are constants.
371    pub fn mark_input(&mut self, offset: usize, len: usize, input: bool) {
372        if let Some(t) = self.taint.as_mut() {
373            t.set(offset, len, input);
374        }
375    }
376
377    /// A read of `loc` by the running statement.
378    pub fn taint_read(&mut self, loc: Loc) {
379        if let Some(t) = self.taint.as_mut() {
380            t.read(loc.offset, loc.len);
381        }
382    }
383
384    /// [`Taint::writing`], when the run traces input.
385    pub fn writing(&mut self, on: bool) -> bool {
386        self.taint.as_mut().is_some_and(|t| t.writing(on))
387    }
388
389    /// A statement with a position starts: its writes carry only what it reads.
390    pub fn statement_starts(&mut self) {
391        if let Some(t) = self.taint.as_mut() {
392            t.start_statement();
393        }
394    }
395
396    /// [`Taint::take_input`], when the run traces input.
397    pub fn take_input(&mut self) {
398        if let Some(t) = self.taint.as_mut() {
399            t.take_input();
400        }
401    }
402
403    /// Whether any byte of the range may hold input; false without taint.
404    pub fn holds_input(&self, offset: usize, len: usize) -> bool {
405        self.taint.as_ref().is_some_and(|t| t.any(offset, len))
406    }
407
408    /// Whether the running statement has read a byte that may hold input.
409    pub fn pending(&self) -> bool {
410        self.taint.as_ref().is_some_and(Taint::pending)
411    }
412
413    /// [`Taint::resume_statement`], when the run traces input.
414    pub fn resume_statement(&mut self, read_before: bool) {
415        if let Some(t) = self.taint.as_mut() {
416            t.resume_statement(read_before);
417        }
418    }
419
420    /// The run did `what`, which taint does not follow.
421    pub fn unfollowed(&mut self, what: &'static str) {
422        if let Some(t) = self.taint.as_mut() {
423            t.unfollowed(what);
424        }
425    }
426
427    /// Whether an input byte may be in a sink's operand; None without taint.
428    pub fn input_at_sink(&self) -> Option<bool> {
429        self.taint.as_ref().and_then(Taint::at_sink)
430    }
431}
432
433impl<'w, H: Clone, L: Loader<H>> RunUnit<'w, H, L> {
434    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 {
435        Self {
436            mem: vec![0; RESERVED],
437            depth: 0,
438            programs: Vec::new(),
439            names: HashMap::new(),
440            library,
441            dds,
442            sysin,
443            clock,
444            out,
445            err,
446            cics: None,
447            eib: 0,
448            cics_files: HashMap::new(),
449            sql: None,
450            le: crate::le::State::default(),
451            oo: Default::default(),
452            observer: None,
453            random: None,
454            externals: Externals::default(),
455            connectors: HashMap::new(),
456            entries: Vec::new(),
457            statements: None,
458            taint: None,
459            statement_limit: None,
460            recent: VecDeque::new(),
461            overrun: None,
462            sysin_ended: HashSet::new(),
463            set_aside: Vec::new(),
464        }
465    }
466
467    fn allocate(&mut self, size: usize) -> usize {
468        let base = self.mem.len().div_ceil(ALIGNMENT) * ALIGNMENT;
469        self.mem.resize(base + size, 0);
470        base
471    }
472
473    /// Adds a program to the run unit under `name` and gives it its storage.
474    pub fn add_named(&mut self, compiled: Option<H>, name: String, files: usize, size: usize) -> usize {
475        let base = self.allocate(size);
476        let index = self.programs.len();
477        self.names.insert(name.clone(), index);
478        self.programs.push(Loaded::new(compiled, name, base, size, files));
479        index
480    }
481
482    /// A CICS LINK or XCTL starts a run unit of its own (C145): every program starts in it in its
483    /// initial state, with storage of its own, it has no EXTERNAL data or files and an empty heap
484    /// (C126), FUNCTION RANDOM has not been referenced (C104) and RETURN-CODE is zero (C105), and
485    /// the state of the run unit that issued it is set aside until [`RunUnit::end_cics_run_unit`].
486    pub fn begin_cics_run_unit(&mut self) {
487        let programs = self.programs.iter_mut().map(Loaded::set_aside).collect();
488        let (externals, connectors) = (std::mem::take(&mut self.externals), std::mem::take(&mut self.connectors));
489        let return_code = ([self.mem[RETURN_CODE], self.mem[RETURN_CODE + 1]], self.holds_input(RETURN_CODE, 2));
490        self.mem[RETURN_CODE..RETURN_CODE + 2].fill(0);
491        self.mark_input(RETURN_CODE, 2, false);
492        let (heap, random) = (std::mem::take(&mut self.le.heap), self.random.take());
493        self.set_aside.push(Enclave { programs, externals, connectors, heap, random, return_code });
494    }
495
496    /// Ends the run unit [`RunUnit::begin_cics_run_unit`] started, closing the files its programs
497    /// and its EXTERNAL files left open as Language Environment closes an enclave's, and dropping
498    /// its programs' storage, EXTERNAL data and heap: a program it loaded stays loaded, in its
499    /// initial state with no storage (C129), and the run unit set aside has everything back but,
500    /// after `xctl`, RETURN-CODE, the program XCTL started having taken the issuer's place (C105).
501    pub fn end_cics_run_unit(&mut self, xctl: bool) -> Result<(), String> {
502        let mut closed = Ok(());
503        for program in &mut self.programs {
504            for f in program.files.iter_mut().filter_map(Option::take) {
505                if let Err(e) = f.close() {
506                    closed = closed.and(Err(format!("closing a file of {}: {e}", program.name)));
507                }
508            }
509            drop(program.set_aside());
510        }
511        closed = closed.and(self.close_external_files(false));
512        let Some(enclave) = self.set_aside.pop() else { return closed };
513        for (program, held) in self.programs.iter_mut().zip(enclave.programs) {
514            program.restore(held);
515        }
516        (self.externals, self.connectors, self.le.heap, self.random) = (enclave.externals, enclave.connectors, enclave.heap, enclave.random);
517        if !xctl {
518            let (bytes, input) = enclave.return_code;
519            self.mem[RETURN_CODE..RETURN_CODE + 2].copy_from_slice(&bytes);
520            self.mark_input(RETURN_CODE, 2, input);
521        }
522        closed
523    }
524
525    /// The program a CALL of `name` enters, and which of its ENTRY statements when `name` is not
526    /// its PROGRAM-ID: the one copy of the program, or with `copy` a copy of its own for the entry
527    /// name ([`crate::callee::entry_copy`]).
528    pub fn load_entry(&mut self, name: &str, copy: bool) -> Result<(usize, Option<usize>), LoadError> {
529        if let Some(i) = self.find(name) {
530            return Ok((i, self.programs[i].entry));
531        }
532        let name = name.to_ascii_uppercase();
533        let index = match self.programs.iter().position(|p| p.compiled.as_ref().is_some_and(|c| L::entry(c, &name).is_some())) {
534            Some(i) => i,
535            None => {
536                let holder = self.library.holder(&name);
537                self.load(holder.as_deref().unwrap_or(&name))?
538            }
539        };
540        let Some(compiled) = self.programs[index].compiled.clone() else { return Ok((index, None)) };
541        let Some(entry) = L::entry(&compiled, &name) else { return Ok((index, None)) };
542        if !copy {
543            return Ok((index, Some(entry)));
544        }
545        let (files, size) = L::shape(&compiled);
546        let copy = self.add_named(Some(compiled), name, files, size);
547        self.programs[copy].entry = Some(entry);
548        self.programs[copy].source = self.programs[index].source.clone();
549        Ok((copy, Some(entry)))
550    }
551
552    /// Storage for a BY CONTENT or BY VALUE argument, at the end of memory, written as
553    /// [`RunUnit::write`] writes.
554    pub fn push_temporary(&mut self, bytes: &[u8]) -> usize {
555        let at = self.allocate(bytes.len());
556        self.write(at, bytes);
557        at
558    }
559
560    /// Releases arguments pushed since `mark`, unless a program's storage, heap storage or EXTERNAL
561    /// storage was placed behind them.
562    pub fn release_temporaries(&mut self, mark: usize) {
563        let external = self.externals.storage.values().all(|&(at, _)| at < mark);
564        if self.programs.iter().all(|p| !p.placed || p.base + p.size <= mark) && self.le.heap_end() <= mark && external {
565            self.mem.truncate(mark.max(RESERVED));
566            if let Some(t) = self.taint.as_mut() {
567                t.truncate(self.mem.len());
568            }
569        }
570    }
571
572    /// One more PERFORM or CALL in progress, refused past `MAX_DEPTH` rather than exhaust the stack.
573    pub fn enter(&mut self, pos: Pos) -> Result<(), Abend> {
574        if self.depth >= MAX_DEPTH {
575            return Err(Abend::ironwork(format!("PERFORM and CALL nest deeper than {MAX_DEPTH}"), pos));
576        }
577        self.depth += 1;
578        Ok(())
579    }
580
581    /// Marks program `me` active: where its storage starts, and whether the activation starts from
582    /// fresh storage, as its first does, the first after a CANCEL, and every one of an INITIAL
583    /// program.
584    pub fn activate(&mut self, me: usize, initial: bool) -> (usize, bool) {
585        if !self.programs[me].placed {
586            let base = self.allocate(self.programs[me].size);
587            (self.programs[me].base, self.programs[me].placed) = (base, true);
588        }
589        let program = &mut self.programs[me];
590        program.active = true;
591        (program.base, !program.initialized || initial)
592    }
593
594    /// Program `me`'s storage holds its initial values, and its GO TOs go where they are written.
595    pub fn initialized(&mut self, me: usize) {
596        self.programs[me].initialized = true;
597        self.programs[me].altered.clear();
598    }
599
600    pub fn find(&self, name: &str) -> Option<usize> {
601        if name.bytes().any(|b| b.is_ascii_lowercase()) {
602            return self.names.get(&name.to_ascii_uppercase()).copied();
603        }
604        self.names.get(name).copied()
605    }
606
607    /// The program CALL names, compiling and loading it the first time.
608    pub fn load(&mut self, name: &str) -> Result<usize, LoadError> {
609        let name = name.to_ascii_uppercase();
610        if let Some(i) = self.find(&name) {
611            return Ok(i);
612        }
613        let loaded = self.library.program(&name)?;
614        self.notify(Event::Load { program: &name, source: loaded.source.as_deref(), recorded: &loaded.recorded });
615        let index = self.add_named(Some(loaded.compiled), loaded.name, loaded.files, loaded.size);
616        self.programs[index].source = loaded.source;
617        Ok(index)
618    }
619
620    pub const fn observed(&self) -> bool {
621        self.observer.is_some()
622    }
623
624    /// Whether a statement starting on `line` is told to the observer.
625    /// Counts the start of `program`'s statement at `pos` against the statement limit. Once it is
626    /// spent the run ends with S322, as z/OS ends a step that runs past its TIME=, at the next start
627    /// of the loop it is in, so the place does not depend on how many statements ran before the
628    /// loop (assumption C241).
629    pub fn start_statement(&mut self, program: usize, pos: Pos) -> Result<(), Abend> {
630        let Some(left) = self.statement_limit.as_mut() else { return Ok(()) };
631        let now = Started { program, depth: self.depth, pos };
632        if *left > 0 {
633            *left -= 1;
634            if self.recent.len() == LOOP_WINDOW {
635                self.recent.pop_front();
636            }
637            self.recent.push_back(now);
638            return Ok(());
639        }
640        let overrun = self.overrun.get_or_insert_with(|| loop_of(&self.recent, now));
641        let message = "the run reached its statement limit, as a step past its TIME= ends";
642        if now == overrun.head && !overrun.lines.is_empty() {
643            const SHOWN: usize = 24;
644            let mut lines = overrun.lines.iter().take(SHOWN).map(u32::to_string).collect::<Vec<_>>().join(", ");
645            if overrun.lines.len() > SHOWN {
646                lines += &format!(" and {} more", overrun.lines.len() - SHOWN);
647            }
648            return Err(Abend { code: crate::abend::AbendCode::TimeLimit, message: format!("{message}, in the loop over lines {lines}"), pos, file: None });
649        }
650        if overrun.grace == 0 {
651            return Err(Abend { code: crate::abend::AbendCode::TimeLimit, message: message.into(), pos, file: None });
652        }
653        overrun.grace -= 1;
654        Ok(())
655    }
656
657    pub fn traces(&self, line: u32) -> bool {
658        match &self.statements {
659            None => false,
660            Some(StatementFilter::All) => self.observer.is_some(),
661            Some(StatementFilter::Lines(lines)) => self.observer.is_some() && lines.contains(&line),
662        }
663    }
664
665    pub fn notify(&mut self, event: Event<'_>) {
666        if let Event::Sink { kind, .. } = &event {
667            debug_assert!(SINK_KINDS.contains(kind), "the sink kind {kind} is not in rt::unit::SINK_KINDS");
668        }
669        if let Some(observer) = self.observer.as_mut() {
670            observer(event);
671        }
672    }
673
674    /// Closes every file any program left open, as the runtime does when the run unit ends, normally
675    /// or by an abend under TRAP(ON). An abend TRAP(OFF) keeps from Language Environment closes
676    /// none (`unclosed`), and each VSAM data set stays marked open for output
677    /// ([`numeric::assumptions::TRAP_OFF_LEAVES_FILES_OPEN`]).
678    pub fn close_all(&mut self, unclosed: bool) -> Result<(), String> {
679        for program in &mut self.programs {
680            for f in program.files.iter_mut().filter_map(Option::take) {
681                end_file(f, unclosed).map_err(|e| format!("closing a file of {}: {e}", program.name))?;
682            }
683        }
684        self.close_external_files(unclosed)
685    }
686
687    /// Closes the EXTERNAL files left open, giving the first failure.
688    fn close_external_files(&mut self, unclosed: bool) -> Result<(), String> {
689        let mut closed = Ok(());
690        for (name, &k) in &self.externals.file_names {
691            if let Some(f) = self.externals.files[k].take()
692                && let Err(e) = end_file(f, unclosed)
693            {
694                closed = closed.and(Err(format!("closing EXTERNAL file {name}: {e}")));
695            }
696        }
697        closed
698    }
699
700    /// Where EXTERNAL record `name` is, or EXTERNAL file `name`'s record area when `file`: storage
701    /// of `size` bytes, zeroed, the first time a program describes it. A description of another
702    /// size is refused (assumption C180), except under --dialect gnucobol a shorter record's, which
703    /// shares the storage with a warning, as cobc's does.
704    pub fn external(&mut self, name: &str, file: bool, size: usize, dialect: Dialect) -> Result<usize, String> {
705        let key = (file, name.to_owned());
706        if let Some(&(at, had)) = self.externals.storage.get(&key) {
707            return if had == size {
708                Ok(at)
709            } else if size < had && !file && dialect == Dialect::Gnucobol {
710                let _ = writeln!(self.err, "ironwork: EXTERNAL record {name} has {had} bytes in the run unit, and this program describes {size}");
711                Ok(at)
712            } else {
713                let what = if file { "the record area of EXTERNAL file" } else { "EXTERNAL record" };
714                Err(format!("{what} {name} has {had} bytes in the run unit, and this program describes {size}"))
715            };
716        }
717        let at = self.allocate(size);
718        self.externals.storage.insert(key, (at, size));
719        Ok(at)
720    }
721
722    /// The run unit's connector for EXTERNAL file `name`.
723    pub fn external_file(&mut self, name: &str) -> Connector {
724        let (files, locked) = (&mut self.externals.files, &mut self.externals.locked);
725        let k = *self.externals.file_names.entry(name.to_owned()).or_insert_with(|| {
726            files.push(None);
727            locked.push(false);
728            files.len() - 1
729        });
730        Connector::External(k)
731    }
732
733    /// Program `me`'s file k is the connector `to`, for as long as the run unit lasts.
734    pub fn connect(&mut self, me: usize, k: usize, to: Connector) {
735        self.connectors.insert((me, k), to);
736    }
737
738    fn connector(&self, mut me: usize, mut k: usize) -> Option<Connector> {
739        let mut to = None;
740        while let Some(&c) = self.connectors.get(&(me, k)) {
741            to = Some(c);
742            match c {
743                Connector::External(_) => break,
744                Connector::Program(p, j) => (me, k) = (p, j),
745            }
746        }
747        to
748    }
749
750    /// Program `me`'s file k, open or not: its own, or the connector it shares.
751    pub fn file(&mut self, me: usize, k: usize) -> &mut Option<Open> {
752        match self.connector(me, k) {
753            None => &mut self.programs[me].files[k],
754            Some(Connector::External(e)) => &mut self.externals.files[e],
755            Some(Connector::Program(p, j)) => &mut self.programs[p].files[j],
756        }
757    }
758
759    /// Whether program `me`'s file k, or the connector it shares, was closed WITH LOCK.
760    pub fn locked(&mut self, me: usize, k: usize) -> &mut bool {
761        match self.connector(me, k) {
762            None => &mut self.programs[me].locked[k],
763            Some(Connector::External(e)) => &mut self.externals.locked[e],
764            Some(Connector::Program(p, j)) => &mut self.programs[p].locked[j],
765        }
766    }
767
768    pub fn file_ref(&self, me: usize, k: usize) -> &Option<Open> {
769        match self.connector(me, k) {
770            None => &self.programs[me].files[k],
771            Some(Connector::External(e)) => &self.externals.files[e],
772            Some(Connector::Program(p, j)) => &self.programs[p].files[j],
773        }
774    }
775
776    pub fn return_code(&self) -> i16 {
777        i16::from_be_bytes([self.mem[RETURN_CODE], self.mem[RETURN_CODE + 1]])
778    }
779
780    /// The current time: seconds since the epoch, and hundredths.
781    pub fn now(&self) -> (i64, u32) {
782        match self.clock {
783            Clock::Fixed(s, h) => (s, h),
784            Clock::System => {
785                let d = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap_or_default();
786                (d.as_secs() as i64, d.subsec_millis() / 10)
787            }
788        }
789    }
790}