Skip to main content

ironwork_exec/
vm.rs

1//! Running on the VM (`rt::vm`): CALL's loader over load modules and the interpreter's program
2//! library, lowering each program it compiles from source, and the run itself, of a compiled
3//! program as `Execute::execute_observed` makes the interpreter's, or of a load module's.
4
5use crate::loader::{Library, loads_as};
6use crate::lower::{self, LowerError};
7use crate::unit::{Clock, Observer, Remains};
8use crate::{Compiled, Passed, cics, files, oo, sql};
9use rt::abend::{Abend, AbendCode, Ending};
10use rt::module::{LoadedModule, Modules};
11use rt::oo::{ClassCode, MethodCode, Part};
12use rt::unit::{FoundClass, LoadError, LoadedProgram, Loader, RunUnit};
13pub use rt::vm::{Code, Halt};
14use std::io::{BufRead, Write};
15use std::path::Path;
16use std::rc::Rc;
17use syntax::Pos;
18use zarch::ebcdic::CodePage;
19
20/// Where CALL finds a program on the VM (load-module.md ยง8.2): among the programs already read,
21/// those of the run's first source or module first; then `NAME.iwm` in the program libraries; then
22/// source there, lowered as CALL loads it.
23pub struct VmLibrary {
24    pub source: Library,
25    pub modules: Modules,
26    /// The run's first program came from a module, so its programs come before any source's.
27    modules_first: bool,
28}
29
30type Found = LoadedProgram<Rc<Code>>;
31type FoundCode = FoundClass<Rc<ClassCode<Rc<Code>>>>;
32
33impl VmLibrary {
34    /// The library's directories are where `NAME.iwm` is looked for, in their order.
35    pub fn new(source: Library) -> Self {
36        let modules = Modules::new(source.dirs.clone(), lower::verify);
37        Self { source, modules, modules_first: false }
38    }
39
40    /// A library for a run that begins with `module`, read from `path`, whose programs come before
41    /// any other's.
42    pub fn for_module(source: Library, path: &Path, module: LoadedModule) -> Self {
43        let mut library = Self::new(source);
44        library.modules_first = true;
45        library.modules.add_first(path.to_owned(), module);
46        library
47    }
48
49    /// Program 0 of the module the run began with, or the program `name` as a CALL of it finds
50    /// one; Err says why there is none to run.
51    fn first_program(&mut self, path: &Path, name: Option<&str>) -> Result<Found, String> {
52        let found = match name {
53            None => self.modules.take(0, 0).unwrap_or_else(|| Err(format!("{}: the module holds no program", path.display()))),
54            Some(name) => self.program(name).map_err(|e| match e {
55                LoadError::NotFound => format!("program {name} not found"),
56                LoadError::Compile(message) => message,
57            }),
58        }?;
59        match found.compiled.program() {
60            Some(p) if p.services.class.is_some() => Err(format!("{} is a class definition: run a program that uses it", p.symbols.get(p.id as usize).cloned().unwrap_or_default())),
61            _ => Ok(found),
62        }
63    }
64
65    /// A program of a source already read, lowered; None when no source read holds one.
66    fn read_source(&mut self, name: &str) -> Option<Result<Found, LoadError>> {
67        self.source.programs.iter().any(|p| loads_as(p, name)).then(|| self.lowered_source(name))
68    }
69
70    fn lowered_source(&mut self, name: &str) -> Result<Found, LoadError> {
71        let found = <Library as Loader<Rc<Compiled>>>::program(&mut self.source, name)?;
72        Ok(LoadedProgram { compiled: Rc::new(code(&found.compiled)), name: found.name, files: found.files, size: found.size, source: found.source, recorded: Vec::new() })
73    }
74
75    /// The class the interpreter's library finds and compiles, with its FACTORY and OBJECT data and
76    /// each method lowered as a program of its own, as lowering a class definition lowers them.
77    fn source_class(&mut self, external: &str) -> Result<Option<FoundCode>, String> {
78        let Some(found) = <Library as Loader<Rc<Compiled>>>::class(&mut self.source, external)? else { return Ok(None) };
79        let class = &found.code;
80        let lowered = |c: &Rc<Compiled>| Rc::new(code(c));
81        let part = |p: &oo::Part| Part { data: lowered(&p.data), records: p.records.clone() };
82        let methods = class
83            .methods
84            .iter()
85            .map(|m| MethodCode { name: m.name.clone(), factory: m.factory, params: m.params.clone(), returns: m.returns.clone(), code: lowered(&m.code), own_records: m.own_records })
86            .collect();
87        let code = ClassCode { parent: class.parent.clone(), factory: class.factory.as_ref().map(part), object: class.object.as_ref().map(part), methods };
88        Ok(Some(FoundClass { code: Rc::new(code), sources: found.sources }))
89    }
90}
91
92impl Loader<Rc<Code>> for VmLibrary {
93    fn program(&mut self, name: &str) -> Result<Found, LoadError> {
94        if !self.modules_first
95            && let Some(found) = self.read_source(name)
96        {
97            return found;
98        }
99        if let Some(found) = self.modules.loaded(name) {
100            return found;
101        }
102        if let Some(found) = self.read_source(name) {
103            return found;
104        }
105        match self.modules.search(name) {
106            Err(LoadError::NotFound) => self.lowered_source(name),
107            found => found,
108        }
109    }
110
111    fn holder(&self, entry: &str) -> Option<String> {
112        let source = || <Library as Loader<Rc<Compiled>>>::holder(&self.source, entry);
113        if self.modules_first { self.modules.holder(entry).or_else(source) } else { source().or_else(|| self.modules.holder(entry)) }
114    }
115
116    fn entry(program: &Rc<Code>, name: &str) -> Option<usize> {
117        program.entry(name)
118    }
119
120    fn shape(program: &Rc<Code>) -> (usize, usize) {
121        program.shape()
122    }
123
124    fn nested(program: &Rc<Code>) -> &[String] {
125        program.nested()
126    }
127
128    fn source(program: &Rc<Code>, file: usize) -> Option<String> {
129        let p = program.program()?;
130        p.debug.sources.get(file).map(|&s| p.symbols[s as usize].clone())
131    }
132
133    fn class(&mut self, external: &str) -> Result<Option<FoundCode>, String> {
134        let read_source = self.source.programs.iter().any(|p| oo::defined_class(p).as_deref() == Some(external));
135        if (!read_source || self.modules_first)
136            && let Some(found) = self.modules.loaded_class(external)?
137        {
138            return Ok(Some(found));
139        }
140        if !read_source && let Some(found) = self.modules.search_class(external)? {
141            return Ok(Some(found));
142        }
143        self.source_class(external)
144    }
145
146    /// A mapset a module already read holds, else one from the copy libraries.
147    fn mapset(&mut self, name: &str) -> Option<Result<rt::bms::Mapset, String>> {
148        self.modules.mapset(name).map(Ok).or_else(|| self.source.mapset(name))
149    }
150}
151
152/// A compiled program as the VM holds it: lowered, or with the construct lowering refused.
153pub fn code(compiled: &Compiled) -> Code {
154    let lowered = lower::lower(compiled).map_err(|e| match e {
155        LowerError::Unsupported(what, _) => what.to_owned(),
156        other => other.to_string(),
157    });
158    held(compiled, lowered)
159}
160
161/// A compiled program lowered for the VM, or why it does not lower, with where.
162pub fn lowered(compiled: &Compiled) -> Result<Code, LowerError> {
163    Ok(held(compiled, Ok(lower::lower(compiled)?)))
164}
165
166fn held(compiled: &Compiled, lowered: Result<rt::lir::Program, String>) -> Code {
167    let entries = compiled.entries.iter().map(|e| e.name.clone()).collect();
168    let method = compiled.program.oo.as_deref().and_then(|o| o.method()).map(|m| format!("{}.{}", m.class, m.name));
169    Code::new(lowered, entries, compiled.program.files.len(), compiled.layout.size as usize, compiled.program.nested.clone(), method)
170}
171
172/// A run unit on the VM over `library`, tracing and limited as the library says.
173#[allow(clippy::too_many_arguments)]
174fn run_unit<'w>(
175    library: VmLibrary,
176    dds: files::Dds,
177    sysin: Option<Box<dyn BufRead + 'w>>,
178    clock: Clock,
179    database: Option<&'w mut (dyn sql::Database + '_)>,
180    out: &'w mut dyn Write,
181    err: &'w mut dyn Write,
182    observer: Option<Observer<'w>>,
183) -> RunUnit<'w, Rc<Code>, VmLibrary> {
184    let (statements, taint) = (library.source.trace_statements.clone(), library.source.trace_input.then(rt::taint::Taint::default));
185    let limit = library.source.statement_limit;
186    let mut run_unit = RunUnit::new(library, dds, sysin, clock, out, err);
187    run_unit.observer = observer;
188    run_unit.statements = statements;
189    run_unit.taint = taint;
190    run_unit.statement_limit = limit;
191    run_unit.sql = database.map(sql::Session::new);
192    run_unit
193}
194
195/// Runs the first program of `run_unit`, `me`, as `code`, given `passed`, then settles the
196/// database and closes every file, unless an abend the PARM's TRAP(OFF) keeps from Language
197/// Environment ended it.
198fn run_main(code: &Code, id: &str, me: usize, run_unit: &mut RunUnit<'_, Rc<Code>, VmLibrary>, passed: Passed<'_>, page: &CodePage) -> Result<(Ending, i16), Halt> {
199    let trap_off = matches!(passed, Passed::Parm(p) if rt::le::parm::trap_off(p));
200    passed.apply_parm(run_unit);
201    let addresses = passed.addresses(run_unit, page);
202    let ending = rt::vm::run(code, me, run_unit, &addresses, passed.main());
203    let settled = run_unit.sql.as_mut().map_or(Ok(()), |s| s.settle(id, ending.is_ok()).map(drop));
204    let closed = run_unit.close_all(trap_off && matches!(&ending, Err(Halt::Abend(a)) if a.code.bypasses_trap_off()));
205    let ending = ending?;
206    settled.map_err(|a| Abend { code: a.code.into(), message: a.message, pos: Pos::default(), file: None })?;
207    closed.map_err(|m| Abend { code: AbendCode::Ironwork, message: m, pos: Pos::default(), file: None })?;
208    Ok((ending, run_unit.return_code()))
209}
210
211/// Runs `compiled`, lowered as `code`, as the first program of a run unit on the VM, given
212/// `passed` as `Execute::execute_main` and `Execute::execute_with_arguments` take it; `kept`
213/// takes what the run left in its run unit.
214#[allow(clippy::too_many_arguments)]
215pub fn execute<'w>(
216    compiled: &Compiled,
217    code: &Code,
218    library: Library,
219    dds: files::Dds,
220    sysin: Option<Box<dyn BufRead + 'w>>,
221    clock: Clock,
222    database: Option<&'w mut (dyn sql::Database + '_)>,
223    out: &'w mut dyn Write,
224    err: &'w mut dyn Write,
225    observer: Option<Observer<'w>>,
226    passed: Passed<'_>,
227    kept: &mut Option<Remains>,
228) -> Result<(Ending, i16), Halt> {
229    oo::refuse_to_run(&compiled.program)?;
230    let mut run_unit = run_unit(VmLibrary::new(library), dds, sysin, clock, database, out, err, observer);
231    let me = run_unit.add_named(None, compiled.program.id.to_ascii_uppercase(), compiled.program.files.len(), compiled.layout.size as usize);
232    let ran = run_main(code, &compiled.program.id, me, &mut run_unit, passed, compiled.options.code_page());
233    *kept = Some(Remains::of(&run_unit));
234    ran
235}
236
237fn refused(message: String) -> Halt {
238    Halt::Abend(Abend::ironwork(message, Pos::default()))
239}
240
241/// The source names of a program's debug table, which an abend's position indexes.
242fn sources(program: &rt::lir::Program) -> Vec<String> {
243    program.debug.sources.iter().map(|&s| program.symbols.get(s as usize).cloned().unwrap_or_default()).collect()
244}
245
246/// Runs program 0 of `module`, read from `path`, as the first program of a run unit on the VM,
247/// with a job step's `parm`, telling `observer` what the run does. CALL finds the module's other
248/// programs before any other, then as [`VmLibrary`] finds them in `library`'s directories.
249#[allow(clippy::too_many_arguments)]
250pub fn execute_module<'w>(
251    module: LoadedModule,
252    path: &Path,
253    library: Library,
254    dds: files::Dds,
255    sysin: Option<Box<dyn BufRead + 'w>>,
256    clock: Clock,
257    database: Option<&'w mut (dyn sql::Database + '_)>,
258    out: &'w mut dyn Write,
259    err: &'w mut dyn Write,
260    observer: Option<Observer<'w>>,
261    parm: Option<&str>,
262) -> Result<(Ending, i16), Halt> {
263    let mut library = VmLibrary::for_module(library, path, module);
264    let main = library.first_program(path, None).map_err(refused)?;
265    let code = main.compiled;
266    let Some(program) = code.program() else { return Err(refused(format!("{}: program 0 is not lowered", path.display()))) };
267    let id = program.symbols.get(program.id as usize).cloned().unwrap_or_default();
268    let page = program.options.options.code_page();
269    let mut run_unit = run_unit(library, dds, sysin, clock, database, out, err, observer);
270    let me = run_unit.add_named(None, main.name, main.files, main.size);
271    run_main(&code, &id, me, &mut run_unit, parm.map_or(Passed::Nothing, Passed::Parm), page)
272}
273
274/// Whether a CICS task of a run that began with `module` can begin with the program `name`, as a
275/// CALL of it finds one, and if so the files a module records for it ([`LoadedProgram::recorded`]);
276/// Err says why not.
277pub fn module_program(module: &LoadedModule, path: &Path, library: Library, name: &str) -> Result<Vec<(String, Option<rt::module::SourceFile>)>, String> {
278    VmLibrary::for_module(library, path, module.clone()).first_program(path, Some(name)).map(|found| found.recorded)
279}
280
281/// Runs a CICS task on the VM whose first program is program 0 of `module`, read from `path`, or
282/// with `name` the program a CALL of that name finds, as [`execute_cics`] runs a compiled one.
283/// Returns the task however the run ended, and the source names of its first program's debug
284/// table, its own source by path when a program library supplied it.
285#[allow(clippy::too_many_arguments)]
286pub fn execute_module_cics<'w>(
287    module: &LoadedModule,
288    path: &Path,
289    name: Option<&str>,
290    library: Library,
291    dds: files::Dds,
292    task: cics::Task,
293    clock: Clock,
294    database: Option<&'w mut (dyn sql::Database + '_)>,
295    out: &'w mut dyn Write,
296    err: &'w mut dyn Write,
297    observer: Option<Observer<'w>>,
298) -> (Result<Ending, Halt>, cics::Task, Vec<String>) {
299    let mut library = VmLibrary::for_module(library, path, module.clone());
300    let found = match library.first_program(path, name) {
301        Ok(found) => found,
302        Err(message) => return (Err(refused(message)), task, Vec::new()),
303    };
304    let code = found.compiled;
305    let program = code.program();
306    let mut names = program.map(sources).unwrap_or_default();
307    if let (Some(own), Some(path)) = (names.first_mut(), &found.source) {
308        *own = path.display().to_string();
309    }
310    let id = program.and_then(|p| p.symbols.get(p.id as usize).cloned()).unwrap_or_default();
311    let page = program.map_or_else(|| numeric::Options::default().code_page(), |p| p.options.options.code_page());
312    let first = crate::First { id: &id, name: found.name, files: found.files, size: found.size, page, source: found.source };
313    let run_unit = run_unit(library, dds, None, clock, database, out, err, observer);
314    let (ending, ended, task) = crate::run_task(first, run_unit, task, &mut None, |unit, me, commarea, length| rt::vm::run_task(&code, me, unit, commarea, length));
315    let ending = match ending {
316        Err(Halt::Abend(abend)) => Err(Halt::Abend(crate::asra(abend))),
317        other => other,
318    };
319    (ending.and_then(|e| ended.map(|()| e).map_err(Halt::Abend)), task, names)
320}
321
322/// Runs `compiled`, lowered as `code`, on the VM as the first program of a CICS task, as
323/// `Execute::execute_cics_observed` runs it on the interpreter; `kept` takes what the run left in
324/// its run unit, and the task comes back however the run ended.
325#[allow(clippy::too_many_arguments)]
326pub fn execute_cics<'w>(
327    compiled: &Compiled,
328    code: &Code,
329    library: Library,
330    dds: files::Dds,
331    task: cics::Task,
332    clock: Clock,
333    database: Option<&'w mut (dyn sql::Database + '_)>,
334    out: &'w mut dyn Write,
335    err: &'w mut dyn Write,
336    observer: Option<Observer<'w>>,
337    kept: &mut Option<Remains>,
338) -> (Result<Ending, Halt>, cics::Task) {
339    if let Err(abend) = oo::refuse_to_run(&compiled.program) {
340        return (Err(abend.into()), task);
341    }
342    let run_unit = run_unit(VmLibrary::new(library), dds, None, clock, database, out, err, observer);
343    let (ending, ended, task) = crate::run_task(crate::First::of(compiled), run_unit, task, kept, |unit, me, commarea, length| rt::vm::run_task(code, me, unit, commarea, length));
344    let ending = match ending {
345        Err(Halt::Abend(abend)) => Err(Halt::Abend(crate::asra(abend))),
346        other => other,
347    };
348    (ending.and_then(|e| ended.map(|()| e).map_err(Halt::Abend)), task)
349}